I have a WPF application that is crashing on some computers with an AccessViolationException when a drag operation is started.
The difficulty is it is only occurring on builds from our build server, and never crashes when I build locally in Visual Studio 2010. So I cannot step through the code.
I have the following information:
We're using .net 4.0
Only crashes when the application is run as a 64bit process, 32bit is fine.
Only crashes for builds from the build server.
Doesn't crash on every computer, just on a small subset of laptops we have here. Which incidentally are all the same model
and hardware configuration. All have
Windows 7, and some have sp1, some
don't.
What is the next step I should take to diagnose this issue?
Here's the stack trace from the crash, it seems to be occurring in unmanaged code:
at MS.Win32.UnsafeNativeMethods.DoDragDrop(IDataObject dataObject, IOleDropSource dropSource, Int32 allowedEffects, Int32[] finalEffect)
at System.Windows.OleServicesContext.OleDoDragDrop(IDataObject dataObject, IOleDropSource dropSource, Int32 allowedEffects, Int32[] finalEffect)
at System.Windows.DragDrop.OleDoDragDrop(DependencyObject dragSource, DataObject dataObject, DragDropEffects allowedEffects)
at Acquire.Common.UI.Behaviours.DragDropBehaviour.StartDrag(RoutedEventArgs e)
at Acquire.Common.UI.Behaviours.DragDropBehaviour.AttachedElementMouseMove(Object sender, MouseEventArgs e)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(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)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
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.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run()
at Acquire.Mica.Application.App.Main()
Update:
Through trial and error I was able to determine the exact line of code that was causing this crash, and it appears to be perfectly valid. As an experiment I disabled code optimization for the method containing the offending line of code, and the application no longer crashes.
AV exception are the worst, you should be aware that the problem may originate from completely different part in the system.
What normally happens is that you accidently access a memory location that you don't have access to, the program continues to execute as usual, however later on another method tries to access that memory location and causes an error by reading incorrect data place there by mistake.
To debug I suggest that you take advantage of gflags, a tool offered by Microsoft to detect deap corruptions. I used it several times and it saved me hours if not days of debugging effort.
Just a hunch, but since you indicated you are optimizing code, and using a mixed 32/64 bit environment:
Verify the build server a x64 bit environment.
Verify the clients have the proper version .Net environment.
Verify the clients that are running the app are running the right version, ie. 64 bit is only being run by win7 x64 systems and vice versa.
Make sure you clear out the servers temp directories, previous builds in temp directories can cause odd issues such as this.
Also note, the Microsoft developers are idiotic in they way they segregated the two environments, and registry keys / program files etc. are not stored where the program indicates. This was a major stumbling block I had to get past with some apps we created at my company.
Also I belive clipboard & drag+drop calls are STA(Single threaded apratments) calls. The crash could be from a conflict between STA to MTA. Do you have the Main() function decorated with the [STAThread] ?
I personally found this article on 64 bit migration useful: http://www.codeguru.com/cpp/misc/samples/basicprogramming/article.php/c16093/Seven-Steps-of-Migrating-a-Program-to-a-64bit-System.htm
First of all check if all updates are installed on the machines.
Later you could use debugdiag to create a crashdump and check the firstchance and secondchance exceptions to get more info on the matter.
Greetings,
Ian
1st thing I would do is to update the video card driver of those laptops.
at MS.Win32.UnsafeNativeMethods..
This usually means that MS .NET engineer trying to tell you:
"Hey, we didn't write this and it crashed."
Related
I am developing an 3D app using the Helix3d Toolkit Viewport. The app also communicates with an OPC Server in the background and is continously receiving data. It basically works as it should but when i run it "longer" times like 5-10 days there is a possibility that it suddenly crashes.
The crash may occur when i change from the menu with the 3D Viewport to any other menu. In the menu of the 3D Viewport it continously adds and removes 3D Model to the View based upon the data coming from the OPC Server.
So of course the 3D models will allocate their memory but it basically reaches its maximum when all models are constructed and displayed once. After having a look in the task manager, regarding the used memory, it reaches like 350 MB which is totally okay and it stays there...
But like i said after a run time of 5 days and more it occurs that the program crashes when i simply hide the UserControl containing the 3D view.
In the debugger it says:
{"Insufficient memory to continue the execution of the program."} System.OutOfMemoryException
When this happens the Task Manager displays a value of around 2400 MB used for the app. But i really dont know why, because the 3D display and the server communication runs good for a relatively long time.
What i tried so far:
I installed 16 RAM (8GB before) in the PC...
From my experience so far the error appears not so often anymore...
I gave the app a higher priority in memore allocation with
System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.High;
but i does not seem to have any effect at all.
I checked my code that it uses no Constructions of any new myClass();
in the methods and program parts which "run continously" so that i basically should not get "more" memory allocation
Before adding or removing a 3D Model i check system ressources
ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
ManagementObjectCollection results = searcher.Get();
But it is not useful because i get the crash when i make a user input like changing a menu.. not while displaying models in 3d...
I switched to 64 Bit
Maybe had the same effect like increasing the RAM...
I would really appreciate if someone could give me a tip how to further locate my problem or maybe what to check exactly. In the background i also write on an MYSQL DB and it also allocates more memory in time but i dont think it has to do something with my original problem...
Concerning the error when it crashes
{"Insufficient memory to continue the execution of the program."} System.OutOfMemoryException
The Strack Trace is:
at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
at System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean enableRenderTarget, Nullable 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 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
But i really cant figure out something with this.
Thanks for any advice.
Greetings Knally
I'm having an issue with a roughly 15y WinForms application, which is being actively maintained. It's being used by around ten companies, each running it on around 5 - 20 clients. Therein we are using a commercial printer driver (PDF X-Change) to create PDFs from printouts, which employs an asynchronous callback mechanism to inform the application that the PDF has been created (or not). The application uses this information to display the PDF file in a window. Basically something like this:
void pdfCreationStatusCallback(PdfCreationStatusArgs pcsa)
{
if (InvokeRequired)
{
Invoke(new PdfCreationStatus(pdfCreationStatusCallback), pcsa);
return;
}
displayPdf(pcsa);
}
A new company started using the software and reported that the application hangs from time to time. Upon debugging I noticed that call to Invoke() sometimes takes between 20 seconds to almost two hours to return! I used remote debugging in combination with .NET Framework debugging (with dotPeek) to see what happens under the hood. I was able to trace it all the way down to the following code in WaitHandle.cs:
[SecurityCritical]
internal static bool InternalWaitOne(
SafeHandle waitableSafeHandle,
long millisecondsTimeout,
bool hasThreadAffinity,
bool exitContext)
{
if (waitableSafeHandle == null)
throw new ObjectDisposedException((string) null, Environment.GetResourceString("ObjectDisposed_Generic"));
int num = WaitHandle.WaitOneNative(waitableSafeHandle, (uint) millisecondsTimeout, hasThreadAffinity, exitContext);
if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
if (num == 128)
WaitHandle.ThrowAbandonedMutexException();
return num != 258;
}
Here I noticed that on a "healthy" system the call to WaitHandle.WaitOneNative(...) returns 0, thus the method returns true and all is good. On the affected system WaitHandle.WaitOneNative(...) returns 258 (after 1000 ms, which is the value of millisecondsTimeout), thus the method returns false. The method calling InternalWaitOne(..) then calls it in a loop for as long as it takes for WaitHandle.WaitOneNative(...) to finally return a value other than 258 (which as stated above, can even take two hours). My problem is, that I couldn't find the source code to WaitOneNative(..), only the following declaration:
[SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int WaitOneNative(
SafeHandle waitableSafeHandle,
uint millisecondsTimeout,
bool hasThreadAffinity,
bool exitContext);
When I set a breakpoint at the line int num = WaitHandle.WaitOneNative(..) I have two threads which both hit that spot, both returning num = 258:
This is the stacktrace for the PDF-creating callback function (_pdfPrinter_OnFileSaved):
> mscorlib.dll!System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext) Line 193 C#
mscorlib.dll!System.Threading.WaitHandle.WaitOne(int millisecondsTimeout, bool exitContext) Line 125 C#
System.Windows.Forms.dll!System.Windows.Forms.Control.WaitForWaitHandle(System.Threading.WaitHandle waitHandle) Line 2788 C#
System.Windows.Forms.dll!System.Windows.Forms.Control.MarshaledInvoke(System.Windows.Forms.Control caller, System.Delegate method, object[] args, bool synchronous) Line 4825 C#
System.Windows.Forms.dll!System.Windows.Forms.Control.Invoke(System.Delegate method, object[] args) Line 4551 C#
GUISubsystem.dll!GUISubsystem.CalculationForms.Printouts.PrintoutAnbotsartikel.FrmAnbotsartikelDruckParameter.pdfCreationStatusCallback(PdfCreationStatusArgs pcsa) Line 597 C#
PrinterSubsystem.dll!PrinterSubsystem.PrintingManager._pdfPrinter_OnFileSaved(int jobID, string fileName) Line 885 C#
[Übergang von Nativ zu Verwaltet]
[Übergang von Verwaltet zu Nativ]
mscorlib.dll!System.Delegate.DynamicInvokeImpl(object[] args) Line 113 C#
mscorlib.dll!System.Runtime.InteropServices.ComEventsMethod.DelegateWrapper.Invoke(object[] args) Line 158 C#
mscorlib.dll!System.Runtime.InteropServices.ComEventsMethod.Invoke(object[] args) Line 121 C#
mscorlib.dll!System.Runtime.InteropServices.ComEventsSink.System.Runtime.InteropServices.NativeMethods.IDispatch.Invoke(int dispid, ref System.Guid riid, int lcid, System.Runtime.InteropServices.ComTypes.INVOKEKIND wFlags, ref System.Runtime.InteropServices.ComTypes.DISPPARAMS pDispParams, System.IntPtr pvarResult, System.IntPtr pExcepInfo, System.IntPtr puArgErr) Line 153 C#
This is the stacktrace of the other thread (looks like the main message loop):
> mscorlib.dll!System.Threading.WaitHandle.InternalWaitOne(System.Runtime.InteropServices.SafeHandle waitableSafeHandle, long millisecondsTimeout, bool hasThreadAffinity, bool exitContext) Line 193 C#
mscorlib.dll!System.Threading.WaitHandle.WaitOne(int millisecondsTimeout, bool exitContext) Line 125 C#
System.Windows.Forms.dll!System.Windows.Forms.Control.WaitForWaitHandle(System.Threading.WaitHandle waitHandle) Line 2793 C#
System.Windows.Forms.dll!System.Windows.Forms.Control.MarshaledInvoke(System.Windows.Forms.Control caller, System.Delegate method, object[] args, bool synchronous) Line 4825 C#
System.Windows.Forms.dll!System.Windows.Forms.Control.Invoke(System.Delegate method, object[] args) Line 4551 C#
System.Windows.Forms.dll!System.Windows.Forms.WindowsFormsSynchronizationContext.Send(System.Threading.SendOrPostCallback d, object state) Line 74 C#
System.dll!Microsoft.Win32.SystemEvents.SystemEventInvokeInfo.Invoke(bool checkFinalization, object[] args) Line 1272 C#
System.dll!Microsoft.Win32.SystemEvents.RaiseEvent(bool checkFinalization, object key, object[] args) Line 970 C#
System.dll!Microsoft.Win32.SystemEvents.OnUserPreferenceChanged(int msg, System.IntPtr wParam, System.IntPtr lParam) Line 728 C#
System.dll!Microsoft.Win32.SystemEvents.WindowProc(System.IntPtr hWnd, int msg, System.IntPtr wParam, System.IntPtr lParam) Line 1130 C#
[Übergang von Nativ zu Verwaltet]
[Übergang von Verwaltet zu Nativ]
System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(System.IntPtr dwComponentID, int reason, int pvLoopData) Line 1258 C#
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(int reason, System.Windows.Forms.ApplicationContext context) Line 2042 C#
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop(int reason, System.Windows.Forms.ApplicationContext context) Line 1982 C#
System.Windows.Forms.dll!System.Windows.Forms.Application.Run(System.Windows.Forms.Form mainForm) Line 988 C#
MainEntry.exe!MainEntry.Main(string[] args) Line 118 C#
An additional observation: it only takes this long the first time Invoke() (and thus WaitOneNative()) is called. Once WaitOneNative() returns 0 (instead of 258) the application runs without any delays. This is "reset" once the application is restarted. This is the first time and the first company that is experiencing this problem on 3/7 clients. One of the clients is using Windows 10, the other two Windows 8.1 with the .Net Framework 4.8. Our application is targeting .Net Framework 4.5.
Can anybody tell me where I can find the source code for static extern int WaitOneNative(..), such that I can further investigate what it's waiting for?
And/or does anybody have a hint what might be going on here, ie. what WaitOnNative() could be waiting for between a few seconds up to hours? What should I be looking for in the stacktraces, threads, etc.?
I was able to identify the problem. It was one of those OnUserPreferenceChanged issues #klaus-gütter mentioned above. We had a Windows.Forms.Form being created one one of the background threads. The pdfCreationStatusCallback callback was simply one of those that would hang due to the "bug" (it wasn't itself the culprit), probably because it was the first one to be called after the background thread mentioned earlier. I debugged it using the method described here: link (...there are a lot of dead links on this topic).
What I don't really understand is why it eventually would be executed (after 1-2h), as well as why it only affected only 3-4 computers out of around 70 using the software, but I can live with that.
Many thanks to everybody who commented on the original post, especially #klaus-gütter and #Jimi: it helped a great deal to know what to look for.
I have a filestream enabled database
I am able to write to the database but when I try to read the data back i get this error
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.Data.dll
Additional information: The user name or password is incorrect
The code I am trying to execute is this
public void ReadFromDatabase()
{
using (SqlConnection connection = new SqlConnection(sql_ConnectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT TOP(1) Video.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() FROM Library", connection);
SqlTransaction sqlTrans = connection.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = sqlTrans;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string path = reader.GetString(0);
byte[] transContext = reader.GetSqlBytes(1).Buffer;
using (Stream fileStream = new SqlFileStream(path, transContext, FileAccess.Read, FileOptions.SequentialScan, allocationSize: 0))
{
byte[] data = new byte[fileStream.Length];
fileStream.Read(data, 0, (int)fileStream.Length);
File.WriteAllBytes(#"C:\Users\Georgi\AppData\Local\VideoPresenter\temp.mp4", data);
}
}
}
}
}
I am using integrated security so the user and password are unchanged and hard coded into the application.
Here is the connection string code
//Create a string builder object
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
//Set the properties of the builder
builder.AsynchronousProcessing = false;
builder.DataSource = "xxx.xxx.xxx.xxx";
builder.IntegratedSecurity = true;
builder.InitialCatalog = "VideoLibrary";
//Set the connection string and connection objects' data
sql_ConnectionString = builder.ToString();
//try to connect to the server
And then I just use the string to open connections
The connection string passed is
"Data Source=xxx.xxx.xxx.xxx;Initial Catalog=VideoLibrary;Integrated Security=True"
Here is the stack trace
System.Data.dll!System.Data.SqlTypes.SqlFileStream.OpenSqlFileStream(string path, byte[] transactionContext, System.IO.FileAccess access, System.IO.FileOptions options, long allocationSize) Unknown
System.Data.dll!System.Data.SqlTypes.SqlFileStream.SqlFileStream(string path, byte[] transactionContext, System.IO.FileAccess access, System.IO.FileOptions options, long allocationSize) Unknown
SQL FILESTREAM TEST CLIENT.exe!SQL_FILESTREAM_TEST_CLIENT.SQLOperations.ReadFromDatabase() Line 158 C#
SQL FILESTREAM TEST CLIENT.exe!SQL_FILESTREAM_TEST_CLIENT.MainWindow.GetButton_Click(object sender, System.Windows.RoutedEventArgs e) Line 47 C#
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.RaiseEvent(System.Windows.RoutedEventArgs e) Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnClick() Unknown
PresentationFramework.dll!System.Windows.Controls.Button.OnClick() Unknown
PresentationFramework.dll!System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) Unknown
PresentationCore.dll!System.Windows.UIElement.OnMouseLeftButtonUpThunk(object sender, System.Windows.Input.MouseButtonEventArgs e) Unknown
PresentationCore.dll!System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) 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.Input.MouseButtonEventArgs.InvokeEventHandler(System.Delegate genericHandler, object genericTarget) 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.UIElement.RaiseEvent(System.Windows.RoutedEventArgs args, bool trusted) 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!MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(object source, System.Delegate method, 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
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) Unknown
WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() Unknown
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) Unknown
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) Unknown
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) Unknown
PresentationFramework.dll!System.Windows.Application.Run() Unknown
SQL FILESTREAM TEST CLIENT.exe!SQL_FILESTREAM_TEST_CLIENT.App.Main() C#
[Native to Managed Transition]
mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) Unknown
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() Unknown
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) Unknown
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) Unknown
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Unknown
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() Unknown
When I open Management Studio I see the row that is filled with the data but I am not able to read it from the application
NOTE: There is the default SQL Server user 'sa' only. And I did try using it too but the result is the same. I create the database with the the Windows User and not with the 'sa' one
NOTE: If I am to run the code with a DataSource=(local) in the connection string it works.
NOTE: Database is in READ_WRITE mode
What I have tried:
I tried recreating the table and the whole database
I tried reinstalling SQL Server Express
I tried add features to Windows, particularly Internet Information Services -> World Wide Web Services -> Security -> Windows Authentication/Basic Authentication
I tried manipulating the rights of the user I am using but it is a dbo so there should be no problem.
I tried running the same code on a different machine (With the same Microsoft account)*
I tried setting tried to set FILESTREAM( NON_TRANSACTED_ACCESS = FULL )
** I know that FileStream is working only with Windows Authentication and I am using windows 8 so everything is the same (or at least should be) in terms of accounts**
Am I missing something?
The fact that you get a Win32Exception, not a SqlException, indicates that the issue occurs when you open the FILESTREAM. There are a number of steps you need to take to ensure remote FILESTREAM access via Win32 API (which is what you try to do). the important changes are to enable the Firewall on the server for port 445 (see Configure a Firewall for FILESTREAM Access) and (most importantly) configure the server to Allow remote clients to have streaming access to FILESTREAM data. SQL configuration filestream access level must be set to 2.
I also recommend going through the Filestream Storage whitepaper, if you still have problems. I've seen cases of mysterious FILESTREAM access denied errors ultimately being diagnosed as administrators messing with the filestream shared folders storage permissions.
I hope you already understand that FILESTREAM can only be accessed using integrated security. Integrated security must be used to obtain the handle path/context (your SELECT statement) and also will be used behind the scenes when using the Win32 API access (ie. when you try to open the SqlFileStream object).
If I am to run the code with a DataSource=(local) in the connection string it works.
Because this works and using the IP Address does not, I suspect SQL Server is treating your connection as a remote connection instead of local.
Open SQL Server Configuration Manager. Select SQL Server Services. Locate the SQL Server instance you are using, right click and select Properties. On the FILESTREAM tab, select Allow remote clients access to FILESTREAM data.
If I am correct, that will solve your issue.
Try using reader.GetSqlBytes(1).Value instead of reader.GetSqlBytes(1).Buffer. The buffer size isn't always the same as the value size. The buffer may contain garbage after the real data. By using the buffer, you may specify an invalid context.
You might have a delegation problem.
Assuming the following machine layout:
clientPC - the machine running your software
sqlSrv - your SQL-Server
fStream - the machine with the filestream-share
You are working with integrated security, so clientPC is using Kerberos for authentication against sqlSrv. Then sqlSrv tries to authenticate the user for access to fStream, but fails.
This might be a Kerberos delegation scenario and you have to meet some requirements to allow that.
The service account, which runs your SQL Server process must be trusted for delegation (or constraint delegation). The delegation has probably to be allowed to the CIFS/fStream ServicePrincipalName.
Kerberos Constraint Delegation: http://technet.microsoft.com/en-us/library/jj553400.aspx
Some screens about Delegation: http://blogs.msdn.com/b/autz_auth_stuff/archive/2011/05/03/kerberos-delegation.aspx
Infos about ServicePrincipalNames: http://blogs.iis.net/brian-murphy-booth/archive/2007/03/09/the-biggest-mistake-serviceprincipalname-s.aspx
I imagine this Win32Exception was raised and handled within the WPF application stack?
You can experience this many times when debugging WPF applications, because it makes API calls and it could fail or handle the exception and continue the processing.
The background:
I have some model which should give predictions once it is trained. The training has to be done only once - which is rather costly (few seconds). The predictions can then be done very fast.
The training is done implicitely when the first prediction is requested. Because I do not know how many models to be trained at startup time and training all at once is much faster than one by one.
My Problem:
When I am starting my training I am waiting for some tasks to finish. Now Windows is realizing that the UI thread is not busy an more and asking other controls if there is some paint to.
Now some other control also wants a model prediction. In my function I see that the training is not finished and start the training again. Result my function goes crazy - undefined behavior. A lock is of no use here because the second function call is from the same (UI) thread!
What makes it even more iteresting is that this is only an issue in Release mode without Visual Studio attached. So no chance of debugging. Only logging. Took me quite some time to figure out the problem...
Start compiling on thread 1
at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at MyComp.MyApp.Model.BestModelEvaluator.Compile()
at MyComp.MyApp.Model.BestModelEvaluator.Evaluate(Double[] in_array)
at MyComp.MyApp.Model.BestModel.ScriptBulkEvaluate(DMyAppionary`2 dMyAppactor, Int32 dicCount)
at MyComp.MyApp.Model.BestModel.BulkEvaluate(DMyAppionary`2 dMyAppactor)
at MyComp.MyApp.Model.MyAppModel.Evaluate(DMyAppionary`2 actuatorValues)
at __Evaluate(MyCompModel* MyComp_model, Int32 regressor_index, uArray<double>* xvalues, uArray<double>* yvalues, uArray<double>* ylower, uArray<double>* yupper, uArray<int>* yvalues_inrange)
at MyCompModel.MakePlot(MyCompModel* , Int32 regressor_index)
at MyAppShell.UpdateCanvasPlots(MyAppShell* , OverlayInfo* ovi, PrintInfo* print_info)
at MyAppShell.UpdateCanvas(MyAppShell* )
at MyAppShell.Notify(MyAppShell* , XMEvent* ev)
at XMWidget.SendEvent(XMWidget* , XMEventType et, XMMailbox* mb, Int32 info, Int32 info1, Int32 info2, Int32 info3)
at XMDrawingArea.DoPaint(XMDrawingArea* , xmRect* rect)
at XMDrawingArea.Message(XMDrawingArea* , MessageType type)
at DrawingAreaWndProc(HWND__* hWnd, UInt32 msg, UInt32 wParam, Int32 lParam)
at CallWindowProcA(IntPtr , HWND__* , UInt32 , UInt32 , Int32 )
at XMDrawingAreaWndProc(HWND__* hWnd, UInt32 msg, UInt32 wParam, Int32 lParam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageA(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 ecYaRlzjebO5lJJRJM.eAlVyhEdyCVdmimFqq.koonrpaTJfLI7QASS3()
at ecYaRlzjebO5lJJRJM.eAlVyhEdyCVdmimFqq.e5ChpHZQl(Byte[] )
at ecYaRlzjebO5lJJRJM.eAlVyhEdyCVdmimFqq.GetLicense(LicenseContext , Type , Object , Boolean )
at System.ComponentModel.LicenseManager.ValidateInternalRecursive(LicenseContext context, Type type, Object instance, Boolean allowExceptions, License& license, String& licenseKey)
at System.ComponentModel.LicenseManager.Validate(Type type)
at MyComp.MyApp.Scripting.Script..ctor(String source, ScriptLanguage language)
at MyComp.MyApp.Model.BestEvaluation.BestModelScriptCompiler.PrepareCompilation()
at MyComp.MyApp.Model.BestEvaluation.BestModelScriptCompiler.CompileSynchronous()
at MyComp.MyApp.Model.BestModelEvaluator.Compile()
at MyComp.MyApp.Model.BestModelEvaluator.Evaluate(Double[] in_array)
at MyComp.MyApp.Model.BestModel.Evaluate(DMyAppionary`2 dMyAppactor)
at MyComp.MyApp.Model.MyAppModel.Evaluate(DMyAppionary`2 actuatorValues)
at __Evaluate(MyCompModel* MyComp_model, uArray<double>* xvalues, uArray<double>* yvalues, SByte* comment)
at MyCompModel.MakePredMyAppion(MyCompModel* )
at MyAppShell.UpdateCanvasPlots(MyAppShell* , OverlayInfo* ovi, PrintInfo* print_info)
at MyAppShell.UpdateCanvas(MyAppShell* )
at MyAppShell.Notify(MyAppShell* , XMEvent* ev)
at XMWidget.SendEvent(XMWidget* , XMEventType et)
at MyAppShell.UpdateTree(MyAppShell* )
at MyAppShell.Notify(MyAppShell* , XMEvent* ev)
at XMWidget.SendEvent(XMWidget* , XMEventType et, XMMailbox* mb, Int32 info, Int32 info1, Int32 info2, Int32 info3)
at XMTreeView.SelectItem(XMTreeView* , uTreeNode* item, Int32 send_event)
at XMTreeView.WMessage(XMTreeView* , WidgetMessage msg)
at XMDrawingArea.DoInput(XMDrawingArea* , Void* m, Int32 had_focus)
at XMDrawingArea.Message(XMDrawingArea* , MessageType type)
at DrawingAreaWndProc(HWND__* hWnd, UInt32 msg, UInt32 wParam, Int32 lParam)
at CallWindowProcA(IntPtr , HWND__* , UInt32 , UInt32 , Int32 )
at XMDrawingAreaWndProc(HWND__* hWnd, UInt32 msg, UInt32 wParam, Int32 lParam)
at DispatchMessageA(tagMSG* )
at WinMain(HINSTANCE__* hInstance, HINSTANCE__* hPrevInstance, SByte* lpCmdLine, Int32 nCmdShow)
at _WinMainCRTStartup()
My function is call from an outside application where I have no chance to change that to put the call in background worker.
private bool Compile()
{
lock (compilerLock)
{
if (!isCompiled && CanCompile())
{
CompileSynchronous();
}
}
return isCompiled;
}
I already tried to do the work myself in background and put those calls in Tasks and wait for them. Now my application is waiting for itself forever. Because the second task is waiting for the first to complete. But the first cannot complete because the second is not done - thread and call stack are the same in the end.
I even tried to switch to "blocking" waiting for my task - to no avail...
foreach (Task t in runningTasks)
{
try
{
while (t.IsCompleted == false) ;
//t.Wait();
t.Dispose();
}
catch (Exception ex)
{
// some logging
}
}
I have no idea what else can be done...
EDIT
Running VS 2010 and .net 4.0
EDIT No. 2
To be more clear. My function should block. But it is called twice within the same thread. Even though the first call is not finished. Because it is the same thread locks are no good!
at MyComp.MyApp.Model.BestModelEvaluator.Compile()
...
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageA(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 MyComp.MyApp.Model.BestModelEvaluator.Compile()
Can't you just have the Compile function return the current value of isCompiled if it's called a second time? So instead of blocking to obtain the lock, you try to take the lock, and return the current value of isCompiled if you can't. Like this:
private bool Compile()
{
if (!Monitor.TryEnter(compilerLock))
{
// Lock already taken. There is a compile in progress.
return isCompiled;
}
try
{
if (!isCompiled && CanCompile())
{
CompileSynchronous();
}
return isCompiled;
}
finally
{
Monitor.Exit(compilerLock);
}
}
Edit
I see now that you can't use Monitor because it allows re-entrant calls. You can use Semaphore, though.
private Semaphore CompileSemaphore = new Semaphore(1, 1);
private bool Compile()
{
if (!CompileSemaphore.WaitOne(0))
{
// Lock already taken. There is a compile in progress.
return false;
}
try
{
if (!isCompiled && CanCompile())
{
CompileSynchronous();
}
return isCompiled;
}
finally
{
CompileSemaphore.Releae();
}
}
That will prevent re-entrant calls to CompileSynchronous, which should limit the problems. You can't block the thread on re-entrant calls, because it's the thread that's doing the compile. The best you can hope is that the second call sees the false return and ignores it.
The real problem, though, is that CompileSynchronous re-enters the message loop. That's going to cause you no end of trouble, and there's not much you can do about it except change the program so that can't happen. If you've designed the program so that it calls DoEvents (or otherwise re-enables the message loop), then you've created a huge problem for yourself and you need to re-think your design.
I finally figured out the true problem!
We are encrypting our assemblies with a 3rd party tool. This tool adds a static constructor which is used for some license checking stuff.
Within that code, Application.DoEvents() is called several times which caused all my problems! See (encrypted) Stacktrace:
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at ecYaRlzjebO5lJJRJM.eAlVyhEdyCVdmimFqq.koonrpaTJfLI7QASS3()
Now on startup, I just create a dummy instance of my class. Suddenly all my problems are gone...
Thanks for all your effort!
Okay, then... you have a library.
This is a possible architectural solution to what I understand as your problem:
Decouple calls to your library from calculations your library does
You have to do at least two things to achive that.
Decouple calls to your library from calculation
This can be easily achieved by using a command pattern.
Every time your library gets called, take all information from the call,
put it into one object, and put that object into some (concurrent) queue.
Start a thread to work on that queue, i.e. dequeue object from it and
perform your calculations (this can be on another thread, too).
You can find more information on the command pattern here (as a starter)
Return values from your library
This can be somewhat problematic. At least as you cannot immediately return
a valid result without blocking the UI thread for the first call.
But blocking the UI thread is one of your major problems here.
I would suggest to return a null value at first. On subsequent calls, you
can return the latest result of your calculations.
I would store the latest result of your learning / trained results somewhere
near the UI thread so that you can return immediately after packing things
into the queue described above. The inital / starting value would be a
perfect match for a null-object.
What is gained so far?
Your calculations can be performed indepentently from the UI thread,
you can return instantly and always provide a sane value, and
multiple calls to your library are no longer a problem.
HTH
I am facing the same problem as described here:
Dispatcher throws InvalidOperationException on Messagebox.Show in Textchanged event
Although the solution works for me, I want to solve another problem: When I have no control on whether a message box is shown (external code), how do I gracefully recover from it?
If I set e.Handled = false an exception propagates thought the rest of the code until it is caught somewhere else it making some trivial warning or informational message box mess up the rest of the application.
On the other hand if I set e.Handled = true the dispatcher unhandled exception handler is called over and over again until I press "Ok" in the message box, at which point the application stays "frozen". Pressing pause, this is the call stack:
New: Pressing any key with the (window focused) after closing the MessageBox causes the application to unfreeze and continue execution as normal.
How do I cause the MessageBox to be closed without breaking my application? (even if the messagebox is not shown at all)
EDIT
As requested here is the exception stack trace.
Dispatcher processing has been suspended, but messages are still being processed.
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, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
More behaviour detected, see "new"