Related
I have a Windows Forms App as a Client (in VB.NET) and I have a DataGridView where I want to see in real time changes that took place in a table in a database. I have another Windows Forms App as a Server that compares every 5 seconds old and new state and post to the client through WCF.
At the client side I read new data in a background worker thread (in order to have a responsive UI) and I run a loop inside the worker thread of new rows. Then when I try to update DataGridView table in the main thread using DataGridView1.Invoke method while scrolling continuesly the vertical scrollbar it throws the following exception.
at System.Collections.Hashtable.HashtableEnumerator.MoveNext()
at Janus.Windows.GridEX.JNSA.a(GridEXRow )
at Janus.Windows.GridEX.GridEX.a(Graphics , Boolean )
at Janus.Windows.GridEX.GridEX.a(Graphics )
at Janus.Windows.GridEX.GridEX.t()
at Janus.Windows.GridEX.GridEX.set_FirstRow(Int32 value)
at Janus.Windows.GridEX.GridEX.OnScrollBarScroll(Int32 scrollCode)
at Janus.Windows.GridEX.ScrollableBase.a(Object , ScrollEventArgs )
at Janus.Windows.GridEX.EditControls.JNSBY.OnScroll(ScrollEventArgs e)
at Janus.Windows.GridEX.EditControls.JNSBY.a(Int32 , Int32 )
at System.Windows.Forms.Control.WmMouseMove(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Client.mdlMain.Main(String[] args)
Here is my code
Private Delegate Sub addrowcallback(table As DataTable, addedRow As DataRow)
Private Sub Add(table As DataTable, addedRow As DataRow)
If Me.IsHandleCreated Or GridControl1.IsHandleCreated Then
If (GridControl1.InvokeRequired Or Me.InvokeRequired) Then
Dim d As New addrowcallback(AddressOf Add)
Me.Invoke(d, table, addedRow)
Else
Dim gridHandle As IntPtr = GridControl1.Handle
GridControl1.Invoke(New Action(Sub()
table.ImportRow(addedRow)
End Sub))
Application.DoEvents()
End If
End If
End Sub
The exception is not happening when I stop WCF Service and I keep scrolling continuesly.
Important note!
I have about 30.000 records and every 5 seconds I have to update about between 0 - 30. If I don't scroll I have no exception. The exception is only while scrolling and updating.
As you can see in my code I implement the following line in order to request specific handle of the control in the main thread:
Dim gridHandle As IntPtr = GridControl1.Handle
I have a very interesting (and confusing) issue for quite a while, but cannot get to the bottom of it
I have a WPF Project built on Entity Framework, with about 100 different entities/tables, which all work smoothly. except for one entity type, named SaleProduct
Saving a SaleProduct takes about 5 minutes, sometimes even more (other entities take under 2 seconds usually). And only in the window.
For testing purposes, I put this code in app startup:
Using d = GetSystemContext(True)
Dim sp = d.Find(Of SaleProduct)(66246)
sp.DiscountAmount += 1
d.SaveChanges()
End Using
And saving there is OK(11 seconds, bearable).
But when I open a window with the SaleProduct as the DataContext and save there, it takes several minutes.
So, I would like to debug this. Maybe I have some bad code somewhere. But I'm not managing with this either. If I press pause in Visual Studio while the app is stuck saving, it freezes on the SaveChanges line, meaning not some custom code. So what difference should it make if we are in the app startup or in the window?
But lets take this a step further, I disabled Just My Code to get a better picture of whats freezing. And it gets stuck here:
InternalDispatcher.cs
try
{
interceptionContext.MutableData.SetExecuted(operation(target, interceptionContext));
}
Where the target is a pretty simple SQL statement
UPDATE [dbo].[Sales]
SET [LastEditedOn] = #0
WHERE ([ID] = #1)
SELECT [AutoPurchaseDate], [GrantingDate], [ReceivedOn], [Name], [TotalVatRate]
FROM [dbo].[Sales]
WHERE ##ROWCOUNT > 0 AND [ID] = #1
Running this in SSMS takes <1 seconds.
But looking at the complete call stack I see that actually its stuck someplace in System.Data.dll. Though try as I might I cant find its .pdb.
So I tried to use decompile, but I get an error
Unable to compile the module
Even though, in the modules window the status is "Symbols loaded".
So I cannot pinpoint precisely.
For kicks, I tried upgrading to .net 4.8 (from 4.7). same problem.
What can I do? How to proceed? Where more can I Investigate?
NOTES
Tables Sales and SaleProducts both have Clustered Primary Keys.
Running SELECT * FROM sys.sysprocesses WHERE open_tran = 1 in SSMS while the code is stuck, returns 0 rows.
InSaveChanges, ChangeTracker.Entries returns precisely 2 entities. The SaleProduct, and its parent Sale.
I've posted a Profiler Trace here https://pastebin.com/enLgE0Ln
Here's the full StackTrace if it might help someone
[Managed to Native Transition]
System.Data.dll!SNINativeMethodWrapper.SNIReadSyncOverAsync(System.Runtime.InteropServices.SafeHandle pConn, ref System.IntPtr packet, int timeout) Unknown
System.Data.dll!System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync() Unknown
System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket() Unknown
System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer() Unknown
System.Data.dll!System.Data.SqlClient.TdsParserStateObject.TryReadByte(out byte value) Unknown
System.Data.dll!System.Data.SqlClient.TdsParser.TryRun(System.Data.SqlClient.RunBehavior runBehavior, System.Data.SqlClient.SqlCommand cmdHandler, System.Data.SqlClient.SqlDataReader dataStream, System.Data.SqlClient.BulkCopySimpleResultSet bulkCopyHandler, System.Data.SqlClient.TdsParserStateObject stateObj, out bool dataReady) Unknown
System.Data.dll!System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() Unknown
System.Data.dll!System.Data.SqlClient.SqlDataReader.MetaData.get() Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.FinishExecuteReader(System.Data.SqlClient.SqlDataReader ds, System.Data.SqlClient.RunBehavior runBehavior, string resetOptionsString, bool isInternal, bool forDescribeParameterEncryption, bool shouldCacheForAlwaysEncrypted) Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, bool async, int timeout, out System.Threading.Tasks.Task task, bool asyncWrite, bool inRetry, System.Data.SqlClient.SqlDataReader ds, bool describeParameterEncryptionRequest) Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReader(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, string method, System.Threading.Tasks.TaskCompletionSource<object> completion, int timeout, out System.Threading.Tasks.Task task, out bool usedCache, bool asyncWrite, bool inRetry) Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.RunExecuteReader(System.Data.CommandBehavior cmdBehavior, System.Data.SqlClient.RunBehavior runBehavior, bool returnStream, string method) Unknown
System.Data.dll!System.Data.SqlClient.SqlCommand.ExecuteReader(System.Data.CommandBehavior behavior, string method) Unknown
> EntityFramework.dll!System.Data.Entity.Infrastructure.Interception.InternalDispatcher<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor>.Dispatch<System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>, System.Data.Common.DbDataReader>(System.Data.Common.DbCommand target, System.Func<System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>, System.Data.Common.DbDataReader> operation, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader> interceptionContext, System.Action<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor, System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>> executing, System.Action<System.Data.Entity.Infrastructure.Interception.IDbCommandInterceptor, System.Data.Common.DbCommand, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext<System.Data.Common.DbDataReader>> executed) Line 138 C#
EntityFramework.dll!System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(System.Data.Common.DbCommand command, System.Data.Entity.Infrastructure.Interception.DbCommandInterceptionContext interceptionContext) Line 103 C#
EntityFramework.dll!System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(System.Collections.Generic.Dictionary<int, object> identifierValues, System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<System.Data.Entity.Core.Mapping.Update.Internal.PropagatorResult, object>> generatedValues) Line 118 C#
EntityFramework.dll!System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() Line 532 C#
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction<int>(System.Func<int> func, System.Data.Entity.Infrastructure.IDbExecutionStrategy executionStrategy, bool startLocalTransaction, bool releaseConnectionOnSuccess) Line 2203 C#
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(System.Data.Entity.Core.Objects.SaveOptions options, System.Data.Entity.Infrastructure.IDbExecutionStrategy executionStrategy, bool startLocalTransaction) Line 2148 C#
EntityFramework.SqlServer.dll!System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute<int>(System.Func<int> operation) Unknown
EntityFramework.dll!System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(System.Data.Entity.Core.Objects.SaveOptions options, bool executeInExistingTransaction) Line 2046 C#
EntityFramework.dll!System.Data.Entity.Internal.InternalContext.SaveChanges() Line 483 C#
Machshevet.dll!Machshevet.Core.RecordContext.SaveChanges() Line 762 Basic
Machshevet.dll!Machshevet.Windows.RecordWindow.Save() Line 169 Basic
Machshevet.dll!Machshevet.Windows.RecordWindow.<closure>.<lambda35-0>() Line 44 Basic
PresentationCore.dll!System.Windows.Input.CommandBinding.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.ExecuteCommandBinding(object sender, System.Windows.Input.ExecutedRoutedEventArgs e, System.Windows.Input.CommandBinding commandBinding) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.FindCommandBinding(System.Windows.Input.CommandBindingCollection commandBindings, object sender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.FindCommandBinding(object sender, System.Windows.RoutedEventArgs e, System.Windows.Input.ICommand command, bool execute) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.Input.RoutedCommand.ExecuteImpl(object parameter, System.Windows.IInputElement target, bool userInitiated) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.TransferEvent(System.Windows.IInputElement newSource, System.Windows.Input.ExecutedRoutedEventArgs e) Unknown
PresentationCore.dll!System.Windows.Input.CommandManager.OnExecuted(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.Input.RoutedCommand.ExecuteImpl(object parameter, System.Windows.IInputElement target, bool userInitiated) Unknown
PresentationFramework.dll!MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(System.Windows.Input.ICommandSource commandSource, bool userInitiated) Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick() Unknown
PresentationFramework.dll!System.Windows.Controls.Button.OnClick() Unknown
System.Windows.Controls.Ribbon.dll!System.Windows.Controls.Ribbon.RibbonButton.OnClick() Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.ReRaiseEventAs(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args, System.Windows.RoutedEvent newEvent) Unknown
PresentationCore.dll!System.Windows.UIElement.OnMouseUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e) Unknown
PresentationCore.dll!System.Windows.RoutedEventArgs.InvokeHandler(System.Delegate handler, object target) Unknown
PresentationCore.dll!System.Windows.RoutedEventHandlerInfo.InvokeHandler(object target, System.Windows.RoutedEventArgs routedEventArgs) Unknown
PresentationCore.dll!System.Windows.EventRoute.InvokeHandlersImpl(object source, System.Windows.RoutedEventArgs args, bool reRaised) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseEventImpl(System.Windows.DependencyObject sender, System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.UIElement.RaiseTrustedEvent(System.Windows.RoutedEventArgs args) Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessStagingArea() Unknown
PresentationCore.dll!System.Windows.Input.InputManager.ProcessInput(System.Windows.Input.InputEventArgs input) Unknown
PresentationCore.dll!System.Windows.Input.InputProviderSite.ReportInput(System.Windows.Input.InputReport inputReport) Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.ReportInput(System.IntPtr hwnd, System.Windows.Input.InputMode mode, int timestamp, System.Windows.Input.RawMouseActions actions, int x, int y, int wheel) Unknown
PresentationCore.dll!System.Windows.Interop.HwndMouseInputProvider.FilterMessage(System.IntPtr hwnd, MS.Internal.Interop.WindowMessage msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
PresentationCore.dll!System.Windows.Interop.HwndSource.InputFilterMessage(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
WindowsBase.dll!MS.Win32.HwndWrapper.WndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam, ref bool handled) Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.DispatcherCallbackOperation(object o) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.InternalRealCall(System.Delegate callback, object args, int numArgs) Unknown
WindowsBase.dll!System.Windows.Threading.ExceptionWrapper.TryCatchWhen(object source, System.Delegate callback, object args, int numArgs, System.Delegate catchHandler) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority priority, System.TimeSpan timeout, System.Delegate method, object args, int numArgs) Unknown
WindowsBase.dll!MS.Win32.HwndSubclass.SubclassWndProc(System.IntPtr hwnd, int msg, System.IntPtr wParam, System.IntPtr lParam) Unknown
[Native to Managed Transition]
[Managed to Native Transition]
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame) Unknown
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) Unknown
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) Unknown
The specific answer to this issue will require seeing the specific code responsible. It likely is not an issue with a single table beyond the relationships that table has defined within the DbContext and database schema, and the current state of what the DbContext is tracking. (And what the Database might be locking, though that is usually a more intermittent type of problem)
Some things to check:
In your App example, you appear to be getting a fresh instance of the DbContext and disposing it. (Good) Does the 11s time reflect the Find+Save, or just Save? The very first query that a DbContext executes in an application incurs a 1-off (think Static) spin-up cost to initialize the model. For a more accurate timing with a first run scenario, you could do something like:
Using d = GetSystemContext(True)
Dim dump = d.Sales.Any()
' Start timing here...
Dim sp = d.Find(Of SaleProduct)(66246)
sp.DiscountAmount += 1
d.SaveChanges()
' End timing here...
End Using
*Sorry, my VB.Net is sadly out of date.. :) In any case, using a quick operation against the DbContext like an Any() will incur the 1-off spin-up cost. Any operation after that should be a more pure representation of the time needed to load & save data.
In your problematic code, are DbContext's guaranteed to be short-lived like this? DbContexts that are alive longer accrue references to a number of entities and any time any entity is persisted, it will scour it's tree of entities to determine if any related ones may need to be updated. Short-lived, disposed DbContexts are the way to go.
Have you run a profiler against the database to capture the exact SQL being run? Your example SQL doesn't look like an EF query, and references a "Sales" table rather than "SalesProduct". Having a profiler running while debugging your EF application operations is invaluable for revealing stuff going on behind the scenes that you don't expect.
Other possibilities would really depend on the code in question, but a profiler combined with breakpoints will generally help spot issues. Is the delay confirmed to be just when DbContext.SaveChanges happens, or the whole save process? If it's something like from the time the user clicks a Save button, then a Profiler might reveal that your code is tripping a lot of lazy-load calls (loading data to check and update prior to saving) or loading unexpected data. (common issues I've seen are misplaced ToList() calls before filtering statements, usually because the devs want to do something that EF cannot translate and ToList() seems like a "fix") If the delay is just from SaveChanges then the profiler can confirm what Update statements and the like are being produced and how long they are taking to run.
In the end it seems that the error disappeared after a index rebuild. Even though I cant understand if it was an index issue, how come it worked flawlessly time and again via SSMS and EF without window. But for now its working just dandy. Thanks again for all posters, as you were extremely helpful in narrowing down and focusing.
Entity framework is slow , very slow
in production code you need to use c# SQL command
Is there any way to disable mouse promotion from code, that is preventing windows to interpret touch events as mouse events?
I capture touch events in my WPF application, and I don't want these interactions to effect mouse pointer visibility and position.
There is a TouchFrameEventArgs.SuspendMousePromotionUntilTouchUp Method that seems to be doing exactly that. Unfortunately it's available only for Silverlight and Windows Phone.
In addition there are some system settings you can use to disable double click and right click promotion, but nothing to disable mouse promotion as a whole.
A Windows 8 specific solution or a low level solution would also help.
The plain Win32 API way of disabling touch promotion to mouse is to handle WM_POINTER* messages in your window's WindowProc (actually, it seems just WM_POINTERDOWN is enough) and NOT call DefWindowProc().
This is what we actually do in some of our commercial applications, and what is suggested here.
This is ONLY available from Windows 8 and later, since the WM_POINTER* messages are not generated by Windows 7 and below.
Now, in the WPF world, this gets more complicated.
First of all, in order to get proper WM_POINTER* handling by the WPF stack, you first need to
Use .NET 4.7
Change some configuration in your WPF app:
(Reporting the code here, just in case the MS page disappears) You need to insert this in your app.config file:
<configuration>
<runtime>
<AppContextSwitchOverrides value="Switch.System.Windows.Input.Stylus.EnablePointerSupport=true"/>
</runtime>
</configuration>
Now the new shiny WPF stack is activated, but it's bugged and moves the mouse cursor even if you handle the OnTouchDown, OnTouchUp, OnTouchMove events and set the Handled flag to true.
We discovered, through the use of a HwndSourceHook and blocking the WM_POINTERDOWN message, that the mouse cursor was finally staying still (although we were blocking all touch-down interactions!)
So, we deducted that the shiny new WPF is actually calling DefWindowProc, even if we are handling the OnTouch* events.
Our soultion was to use Microsoft Detours, in order to intercept the DefWindowProc call, and block the WM_POINTERDOWN from reaching the real DefWindowProc.
The detour code is:
#include <Windows.h>
#include <detours.h>
static LRESULT(WINAPI * _originalDefWindowProcA)(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) = DefWindowProcA;
static LRESULT(WINAPI * _originalDefWindowProcW)(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) = DefWindowProcW;
static LRESULT WINAPI myDefWindowProcA(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch (Msg)
{
case WM_POINTERDOWN:
return 0;
default:
return _originalDefWindowProcA(hWnd, Msg, wParam, lParam);
}
}
static LRESULT WINAPI myDefWindowProcW(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch (Msg)
{
case WM_POINTERDOWN:
return 0;
default:
return _originalDefWindowProcW(hWnd, Msg, wParam, lParam);
}
}
void SetupDefWindowProcDetour()
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)_originalDefWindowProcA, myDefWindowProcA);
DetourAttach(&(PVOID&)_originalDefWindowProcW, myDefWindowProcW);
DetourTransactionCommit();
}
NOTE: SetupDefWindowProcDetour must be called by the main (UI) thread of your app.
public static class PreventTouchToMousePromotion
{
public static void Register(FrameworkElement root)
{
root.PreviewMouseDown += Evaluate;
root.PreviewMouseMove += Evaluate;
root.PreviewMouseUp += Evaluate;
}
private static void Evaluate(object sender, MouseEventArgs e)
{
if (e.StylusDevice != null)
{
e.Handled = true;
}
}
}
Excample Usage:
public MainWindow()
{
InitializeComponent();
PreventTouchToMousePromotion.Register(this);
}
or take a look at this post
http://social.msdn.microsoft.com/Forums/vstudio/en-US/9b05e550-19c0-46a2-b19c-40f40c8bf0ec/prevent-a-wpf-application-to-interpret-touch-events-as-mouse-events?forum=wpf#9965f159-04a4-41ed-b199-30394991f120
There doesn't seem to be any such option (at least up to Windows 8.1 and .NET 4.5).
The only way to disable mouse promotion is to disable finger input completely, either from within the system control panel (open control panel, open "Pen and Touch", select "Touch" tab, disbale "Use your finger as an input device") or via Registry (HKLM\Software\Microsoft\Wisp\Touch, TouchGate = 0 =disable touch)
Then you can still process touch input using one of the following (nasty) alternatives:
Write your own WinUSB driver for your touch device
Get raw touch input data using the RawInput API
Find a 3rd party USB driver for your device (e.g. UPDD TouchBase)
Finally, you can inject the collected touch data into your application using custom routed events or using touch injection.
In any case you will, of course, loose touch support for any other application on your system, so this solution will in general not be too helpfull to you.
I get this exception in my application.
I have found links discussing it on the web but nothing indicating how to track it down and/or workaround it.
Please do not reply with links from the internet.
Please reply with strategies of tracking the source.
Please reply with workarounds if you found them.
Source: PresentationCore
Message: Exception from HRESULT: 0x88980406
Stack Trace:
at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
at System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean enableRenderTarget, Nullable`1 channelSet)
at System.Windows.Interop.HwndTarget.UpdateWindowPos(IntPtr lParam)
at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
This is old, but I will answer anyways, since I had the same issue that I just resolved.https://stackoverflow.com/a/18003004/1415307
Basically, my issue with this error came down to an outdated video card driver. After updating to the newest driver, the issue has been resolved.
In my case it turned out the application in question was already pressing up on memory limits of its specced hardware. Any time I added code that used a decent amount of memory this would crop up.
I ended up using a MemoryFailPoint mechanism when I implemented a feature that placed processing an image buffer on another thread.
https://learn.microsoft.com/en-us/dotnet/api/system.runtime.memoryfailpoint
First implementation did the trick but after many tries QA caused a OOM bomb.
So I implemented a MemoryFailPoint() with GC.Collect() loop (hackish I know...but sometimes...get er done).
The main things I learned were:
This is a really bad bug in WPF.
You only have to worry about it if you have truly consumed an inordinate amount of memory.
With Microsoft's excellent help, we just solved a SyncFlush problem that has plagued us for more than a year. It turns out that we were creating multimedia timers in native code, but we weren't freeing them every time. More specifically, we called timeBeginPeriod and timeEndPeriod, but we called begin more times than end, thus creating a resource leak. The WPF rendering thread needs to use those timers, but we exhausted a limited supply of them (perhaps 65k). The result was that the rendering thread stopped rendering and either hung or caused a crash. Watch out for timers!
As part of learning wpf I'm working through some MS 'lab' sample apps; The finished exercise looks right, but I'm hitting a NullReferenceException with "Source code unavailable" issue (exception detail below). It appears to be thrown after the main window is shown.
I suspect the issue is in the XAML, but the debugger isn't helping me as much as I'd like. I've put break points everywhere the NavigationService is called in code, and none are being hit before the exception occurs. The type that the page function(s) returns was changed from string to object as part of the exercise.
In a real project. there would likely be enough unit tests and checks in place to not get in this state, but as long as I am and as part of the exercise of learning wpf, it surely can't hurt to know how to debug better!
How can I debug something like this better?
<--- EDITED COMMENTS
#electronherder
The closest guess I can make is that there is a Frame in Window1 that is not hooked up correctly. The idea is that the Frame displays contact information about the currently selected contact in a ListBox; this is done in code as follows:
void ListItemSelected(object sender, SelectionChangedEventArgs args) {
// show first page function on the right hand side frame
var pageFunction = new ContactDetailPage1(false, lstBoxAllContacts.SelectedIndex);
pageFunction.Return += pageFunction0_Return;
Frame_RightPane.Navigate(pageFunction);
//update status bar
if (lstBoxAllContacts.SelectedItem != null) {
var contact = lstBoxAllContacts.SelectedItem as Contact;
statusBar.Text = contact.FirstName + " " + contact.LastName;
}
else {
statusBar.Text = "No contacts on file.";
}
}
Before Window1 exits the call to Show(), this method executes without crashing. It does have that call to do some navigation, which I do not fully understand but is copied from the lab exercise notes. The navigation is related to a different window called ContactDetailPage1, and here's how the lab notes explain things:
"We want to be able to display this page in two modes: Read and Edit. That way we can reuse the Read mode in the contact details frame, Frame_RightPane."
The event hookup (pageFunction.Return += pageFunction0_Return;) is also a bit suspect, since it is intentionally a no-op to keep the compiler happy. I put an assert inside it though, as you can see in the code below:
// This is the ContactDetailPage1 page function's return handler; merely a placeholder
// since the page is displayed in read mode and doesn't return anything.
private static void pageFunction0_Return(object sender, ReturnEventArgs<object> e) {
Debug.Assert(false, "We should never actually be here!");
}
Finally, here is the XAML from Window1 that covers the frame:
<!-- RHS Panel -->
<Frame Name="Frame_RightPane" Grid.Column="0" Grid.ColumnSpan="1" Grid.Row="0" Grid.RowSpan="1"
Margin="201,65,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto"/>
That's the best I can do here, but here is the link to the lab for anyone that really wants to understand it (http://windowsclient.net/downloads/folders/hands-on-labs/entry3719.aspx).
<--- END OF EDIT --->
Cheers,
Berryl
<-- exception -->
System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object." Source="mscorlib"
StackTrace:
at System.Object.GetType()
at MS.Internal.AppModel.ReturnEventSaver._Detach(PageFunctionBase pf)
at System.Windows.Navigation.NavigationService.HookupNewTree(Object newTree, NavigateInfo navInfo, Uri newUri)
at System.Windows.Navigation.NavigationService.OnBeforeSwitchContent(Object newBP, NavigateInfo navInfo, Uri newUri)
at System.Windows.Navigation.NavigationService.MS.Internal.AppModel.IContentContainer.OnContentReady(ContentType contentType, Object bp, Uri bpu, Object navState)
at System.Windows.Navigation.NavigationService.DoNavigate(Object bp, NavigationMode navFlags, Object navState)
at System.Windows.Navigation.NavigateQueueItem.Dispatch(Object obj)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Application.RunInternal(Window window)
at AddressBook.MyApp.Main() in C:\Users\Berryl\Documents\Visual Studio 2008\Projects\UI related\DEV007 Building WPF Applications\Source\CS\Ex1\Task1\AddressBook\obj\Debug\MyApp.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Did you rename any of the classes - like Window1.xaml? I have seen similar failures in WPF projects when I have renamed the window class and missed some references. They are a number of them in the project in generated code. If you search the entire project for the old name you should be able to find orphaned references that might be causing the null ref.