nhibernate, async loading - nhibernate

I have a question about hibernate. I use different controls in my application (treeview, combobox, ...). I get the content for these controls through nhibernate. The problem is, that it takes a lot of time to get the data. Drung this time the form is frozen.
I want to load the data in another thread. But i don't know where to put that thread. I'm new at hibernate, maybe you have more experience about that.

This isn't really an NHibernate problem, but rather a .NET Windows Forms threading one. Anyways, on a Forms environment, the easiest way to load all the NHibernate on a background thread would be to use the BackgroundWorker component.
private void LoadData(object sender, EventArgs e)
{
// This event fires whatever's in DoWork() on a separate thread.
backgroundWorker1.RunWorkerAsync();
// Things to do asynchronous operation.
timer1.Start();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// NHibernate loading goes here...
var employees = Session.CreateCriteria<Employee>();
combobox1.DataSource = employees;
}

Related

Helix Toolkit How to use MouseWheelEventHandler to run specific methods in other classes

I would like to run particular methods of a custom Camera class whenever the user zooms in or out in the helix toolkit view that my program is running inside of.
A key feature of this functionality is getting the mouseargs from the event so I can adjust the camera in a way that is proportional to the number of scroll ticks.
I began to try this:
public event PropertyChangedEventHandler PropertyChanged;
public virtual void onMouseWheeled(MouseDevice Mouse, int time,
MouseWheelEventArgs e) {
MouseWheel?.Invoke(this, new MouseWheelEventArgs(Mouse, time,
e.Delta)); }
//This next line goes in a MainWindow_Loaded method that gets called in the
//MainWindowConstructor
void MainWindow_Loaded(object sender, RoutedEventArgs e) {
view1.MouseWheel += new MouseWheelEventHandler(onMouseWheeled(Cursor,
Time.simTime, view1.MouseWheeledEventArgs)); }
but was having a lot of trouble figuring out how to pass a MouseWheelEventArgs object into the onMouseWheeled method when I'm trying to add the onMouseWheeled method to the MouseWheelEventHandler. Assuming nothing is fundamentally wrong with that sentence, which is nothing more than wishful thinking, The last thing I am trying to figure out is how to get mouse wheel event args so that I can pass it into a method.
Then I tried this:
public event MouseWheelEventHandler MouseWheel;
public virtual void onMouseWheeled(object sender, MouseWheelEventArgs e)
{
Console.WriteLine(e.Delta);
}
//In Main Window Loaded method...
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
view1.MouseWheel += onMouseWheeled;
}
But I get no output when i scroll the wheel. I assumed this might actually work because view1 is the helix window I'm attaching all of my objects to, as children of view1.
Basically my main questions are:
What does invoke actually do? I only have this running to try to see if its working because onPropertyChanged methods I always use run the Invoke command like so. I'm actually not sure where I'm going with this.
How does the handler work?
How do the event args get called out so that I can use them and pass them as objects to other methods?
Thank you for your time. And Thank you twice for any and all pointers and advice you may give me.
Try to use preview mouse wheel event

Unhandled exception handler not called for Metro / WinRT UI async void event handler

Consider the following to be extracts from a Windows 8 Metro / WinRT app, which have been reduced to the bare minimum required to show the anomaly:
public class App : Application
{
public App()
{
UnhandledException += (sender, e) => e.Handled = true;
}
}
public class MainPage : Page
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
}
So given a Metro UI with two buttons and their click event handlers, the only difference is that the second event handler is marked as async.
Then clicking on each button, I would expect the UnhandledException handler to be called in both cases, since they (should) both be entered via the UI thread and associated synchronization context.
My understanding is that, for async void methods, any exceptions should be captured and 'rethrown' (preserving the original stacktrace) via the initial synchronization context, which is also clearly stated in the Async / Await FAQ.
But the UnhandledException handler is not called in the async case, so the application crashes! Since this challenges what I consider an otherwise very intuitive model, I need to know why! Yes, I know I could wrap the body of the handler in a try { } catch { }, but my question is why isn't the backstop UnhandledException handler called?
To further emphasise why this doesn't make sense, consider the following practically identical extracts from a WPF app also using async / await and targeting .NET Framework 4.5:
public class App : Application
{
public App()
{
DispatcherUnhandledException += (sender, e) => e.Handled = true;
}
}
public class MainWindow : Window
{
private void Button_Click_1(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
private async void Button_Click_2(object sender, RoutedEventArgs e)
{
throw new NotSupportedException();
}
}
[There is a subtle difference that WPF has both an Application DispatcherUnhandledException event handler as well as an AppDomain UnhandledException event handler, but you can only mark the exception as 'handled' in the DispatcherUnhandledException, which aligns with the Metro / WinRT Application UnhandledException event handler above.]
Then clicking on each button, the DispatcherUnhandledException handler is indeed called in both cases, as expected, and the application does not crash.
Answered here: No UnhandledException fired from async event callback
It is a known limitation of WinRT. Hopefully, it gets fixed in the next update.
The solution in the following post worked for me, with one small change: I had to move AsyncSynchronizationContext.Register(); to the App.OnLaunched event
http://www.markermetro.com/2013/01/technical/handling-unhandled-exceptions-with-asyncawait-on-windows-8-and-windows-phone-8/
As explained in the documentation (source: http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.application.unhandledexception.aspx):
It’s important to be aware of several limitations of the
Application.UnhandledException event. This event is only used with
exceptions encountered by the XAML framework. Exceptions encountered
by other Windows Runtime components or parts of the application that
are not connected to the XAML framework will not result in this event
being raised.
For example, if a different Windows component calls
into application code and an exception is thrown and not caught, the
UnhandledException event won’t be raised. If the application creates
a worker thread, and then raises an exception on the worker thread,
the UnhandledException event won’t be raised.
As pointed out in this conversation, only way to retrieve exceptions happening in a worker thread is to wrap them in a try/catch block. As a consequence, here's the workaround I'm using in my app: instead of using Task.Run or equivalents to execute code on a worker thread from the UI, I'm using this method:
/// <summary>
/// Runs code in a worker thread and retrieves a related exception if any.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="action">The action.</param>
public static void SafeRun(this DependencyObject target, Action action)
{
Task task = ThreadPool.RunAsync(o =>
{
try
{
action();
}
catch (Exception ex)
{
/* Call the same error logging logic as in the UnhandledException event handler here. */
}
}).AsTask();
task.Wait();
}
Bottom line is that to log all errors in your app, you should:
Subscribre to the UnhandledException event to get XAML stack related errors,
Wrap actions happening in a worker threads in a try/catch block.
From my point of view the only right answere was downvoted here (Try UnobservedTaskException event of TaskScheduler)
the problem is that you are using 'async void' where the exceptions cannot be handled. This is not a WinRT limitation but as design behaviour of async. You need to understand the async deeply to correctly implement exception handling here. See this article: http://msdn.microsoft.com/en-us/magazine/jj991977.aspx
Exceptions are rethrown whe GC collects the tasks as unobserved. You can get them by registering TaskScheduler UnobservedTaskException event. Note - it takes some time till the exception arrives there, because it is noted with garbage collector.
Generally do not use 'async void', but in UI event handlers you have to, so this is thy only way..
This question is old; nonetheless, a similar issue now plagues my UWP app. Occasionally I must unwind the call stack by allowing an exception to propagate up it. I need the exception to reach the app's UnhandledException handler, but that wasn't always happening. This issue included the obvious case of throwing on a non-UI thread. It also included a non-obvious case, the causality of which I have yet to pin down, of throwing on the UI thread.
I conjured up the below solution. I catch the exception and then explicitly post it to the synchronization context. Due to the strange aforementioned issue, I must do this even while already running on the current synchronization context. Otherwise, the exception sometimes doesn't reach the UnhandledException handler.
private void Throw( Exception exception )
{
uiContext.Post( arg => throw exception, null );
throw new OperationCanceledException();
}
Try UnobservedTaskException event of TaskScheduler

How to know when a project is finished opening

After initiating a new project, I would like to know when Petrel has completed the new project creation. When subscribed to the DataManager.WorkspaceOpened event, the event get called when the workspace is opened, but this may not be when the main thread has completed creating the new project.
Any ideas on when to know when Petrel is finished creating the new project ?
Perhaps you can try to find another way to solve your underlying problem than listening for the project event? Could you do a lazy evaluation and wait until the user actually need your code to do what it will do after the project is loaded?
Sometimes you might end up chasing these kind of problems in a circle: I need A to happen after B, and B to happen after C, and C to happen after A.
Anyway... here is a hack that you can try in you IModule:
void WorkspaceOpened(object sender, EventArgs e)
{
Application.Idle += new EventHandler(Application_Idle);
}
void Application_Idle(object sender, EventArgs e)
{
// Deatach from this, since this event can be raised 100 times per second,
// and we only want it once per project.
Application.Idle -= new EventHandler(Application_Idle);
DoMyStuffHereAfterTheProjectHasFinishedOpening();
}

Removing all event handlers in one go

Problem: I have a document class which contains a list of objects. These objects raise events such as SolutionExpired, DisplayExpired etc. The document needs to respond to this.
Documents can sometimes exchange objects, but a single object should never be 'part' of more than one document.
My document class contains a bunch of methods which serve as event handlers. Whenever an object enters the document, I use AddHandler to set up the events, and whenever an object is removed from the document I use RemoveHandler to undo the damage. However, there are cases where it's difficult to make sure all the steps are properly taken and I might thus end up with rogue event handlers.
Long story short; how do I remove all the handlers that are pointing to a specific method? Note, I don't have a list of potential event sources, these could be stored anywhere.
Something like:
RemoveHandler *.SolutionExpired, AddressOf DefObj_SolutionExpired
You can use Delegate.RemoveAll(). (The part you're interested in is in button2_Click)
public void Form_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(button1_Click);
button1.Click += new EventHandler(button1_Click);
button2.Click += new EventHandler(button2_Click);
TestEvent += new EventHandler(Form_TestEvent);
}
event EventHandler TestEvent;
void OnTestEvent(EventArgs e)
{
if (TestEvent != null)
TestEvent(this, e);
}
void Form_TestEvent(object sender, EventArgs e)
{
MessageBox.Show("TestEvent fired");
}
void button2_Click(object sender, EventArgs e)
{
Delegate d = TestEvent as Delegate;
TestEvent = Delegate.RemoveAll(d, d) as EventHandler;
}
void button1_Click(object sender, EventArgs e)
{
OnTestEvent(EventArgs.Empty);
}
You should note that it doesn't alter the contents of the delegates you pass in to it, it returns an altered delegate. Consequently, you won't be able to alter the events on a button you've dropped on a form from the form, as button1.Click can only have += or -= used on it, not =. This won't compile:
button1.Click = Delegate.RemoveAll(d, d) as EventHandler;
Also, be sure that wherever you're implementing this you're watching out for the potential of race conditions. You could end up with some really strange behavior if you're removing handlers from an event that is being called by another thread!
public class TheAnswer
{
public event EventHandler MyEvent = delegate { };
public void RemoveFromMyEvent(string methodName)
{
foreach (var handler in MyEvent.GetInvocationList())
{
if (handler.Method.Name == methodName)
{
MyEvent -= (EventHandler)handler;
}
}
}
}
EDIT 2: Apologies for my misunderstanding--I see that you were pretty clear about not having access to the event sources in your original post.
The simplest way I can think of to solve this problem involves implementing a Shared dictionary of object-to-document bindings. When an object enters a document, check the dictionary for an existing binding to another document; if present, remove handlers that refer to the old document before adding them for the new. Either way, update the dictionary with the new binding.
I think in most cases the performance and memory impacts would be negligible: unless you're dealing with many tens of thousands of small objects and frequently exchange them between documents, the memory overhead of each key/value pair and performance hit for each lookup operation should be fairly small.
As an alternative: if you can detect (in the document event handlers) that the sender of the event is no longer relevant to the document, you can detach the events there.
These seem like the kind of ideas you might have already rejected--but maybe not!
Use Delegate.RemoveAll (maybe using reflection if the Delegate instance is private).

What is the most efficient way to handle the lifecycle of an object with COM interop?

I have a Windows Workflow application that uses classes I've written for COM automation. I'm opening Word and Excel from my classes using COM.
I'm currently implementing IDisposable in my COM helper and using Marshal.ReleaseComObject(). However, if my Workflow fails, the Dispose() method isn't being called and the Word or Excel handles stay open and my application hangs.
The solution to this problem is pretty straightforward, but rather than just solve it, I'd like to learn something and gain insight into the right way to work with COM. I'm looking for the "best" or most efficient and safest way to handle the lifecycle of the classes that own the COM handles. Patterns, best practices, or sample code would be helpful.
I can not see what failure you have that does not calls the Dispose() method. I made a test with a sequential workflow that contains only a code activity which just throws an exception and the Dispose() method of my workflow is called twice (this is because of the standard WorkflowTerminated event handler). Check the following code:
Program.cs
class Program
{
static void Main(string[] args)
{
using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
{
AutoResetEvent waitHandle = new AutoResetEvent(false);
workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
{
waitHandle.Set();
};
workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
{
Console.WriteLine(e.Exception.Message);
waitHandle.Set();
};
WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WorkflowConsoleApplication1.Workflow1));
instance.Start();
waitHandle.WaitOne();
}
Console.ReadKey();
}
}
Workflow1.cs
public sealed partial class Workflow1: SequentialWorkflowActivity
{
public Workflow1()
{
InitializeComponent();
this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode);
}
[DebuggerStepThrough()]
private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
Console.WriteLine("Throw ApplicationException.");
throw new ApplicationException();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
// Here you must free your resources
// by calling your COM helper Dispose() method
Console.WriteLine("Object disposed.");
}
}
}
Am I missing something? Concerning the lifecycle-related methods of an Activity (and consequently of a Workflow) object, please check this post: Activity "Lifetime" Methods. If you just want a generic article about disposing, check this.
Basically, you should not rely on hand code to call Dispose() on your object at the end of the work. You probably have something like this right now:
MyComHelper helper = new MyComHelper();
helper.DoStuffWithExcel();
helper.Dispose();
...
Instead, you need to use try blocks to catch any exception that might be triggered and call dispose at that point. This is the canonical way:
MyComHelper helper = new MyComHelper();
try
{
helper.DoStuffWithExcel();
}
finally()
{
helper.Dispose();
}
This is so common that C# has a special construct that generates the same exact code [see note] as shown above; this is what you should be doing most of the time (unless you have some special object construction semantics that make a manual pattern like the above easier to work with):
using(MyComHelper helper = new MyComHelper())
{
helper.DoStuffWithExcel();
}
EDIT:
NOTE: The actual code generated is a tiny bit more complicated than the second example above, because it also introduces a new local scope that makes the helper object unavailable after the using block. It's like if the second code block was surrounded by { }'s. That was omitted for clarify of the explanation.