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.
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 have a NancyFX API, and when one of the endpoints is hit, I need to kick of a longer running asynchonous task that's decoupled from the endpoint itself. So I'm trying to use a Azure Service Bus queue.
I'm successfully writing a message to the queue when the NancyFX endpoint is hit. I can also successfully subscribe and read from the queue from something other than NancyFX (I tested from Linqpad).
However, if I try to subscribe from the NancyFX app, I get a timeout exception within a second or two from starting the app. I'm doing this in another thread which is kicked off from the NancyFX Bootstrapper.ApplicationStartup override.
I'm unsure why this would be different than doing it not in the NancyFX app. I can't see anything of relevance in the web.config file.
Below is the code I'm using to subscribe to the queue ...
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider("Main", AccessKey);
var factory = await MessagingFactory.CreateAsync("sb://myapp.servicebus.windows.net", tokenProvider);
var receiver = await factory.CreateMessageReceiverAsync("MyQueue");
receiver.OnMessage(bm =>
{
// Do something here
}, new OnMessageOptions
{
MaxConcurrentCalls = 1,
});
Below is the exception ...
System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: A timeout has occurred during the operation. b6b8e25a-714f-4f55-8a79-91e390f47a96_G25 (Fault Detail is equal to An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.TimeoutException: A timeout has occurred during the operation.
).
And here is the callstack when I caught it in the debugger ...
Microsoft.ServiceBus.dll!Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.ThrowIfFaultMessage(System.ServiceModel.Channels.Message wcfMessage) Line 463 C#
Microsoft.ServiceBus.dll!Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.HandleMessageReceived(System.IAsyncResult result) Line 313 C#
Microsoft.ServiceBus.dll!Microsoft.ServiceBus.Messaging.Sbmp.DuplexRequestBindingElement.DuplexRequestSessionChannel.OnMessageReceived(System.IAsyncResult result) Line 381 C#
System.ServiceModel.Internals.dll!System.Runtime.AsyncResult.Complete(bool completedSynchronously) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.TransportDuplexSessionChannel.TryReceiveAsyncResult.OnReceive(System.IAsyncResult result) Unknown
System.ServiceModel.Internals.dll!System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult result) Unknown
System.ServiceModel.Internals.dll!System.Runtime.AsyncResult.Complete(bool completedSynchronously) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult.OnReceiveComplete(object state) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(object state) Unknown
System.ServiceModel.Internals.dll!System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(System.IAsyncResult result) Unknown
System.dll!System.Net.LazyAsyncResult.Complete(System.IntPtr userToken) Unknown
System.dll!System.Net.LazyAsyncResult.ProtectedInvokeCallback(object result, System.IntPtr userToken) Unknown
System.dll!System.Net.Security._SslStream.ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, System.Net.AsyncProtocolRequest asyncRequest) Unknown
System.dll!System.Net.Security._SslStream.ReadFrameCallback(System.Net.AsyncProtocolRequest asyncRequest) Unknown
System.dll!System.Net.AsyncProtocolRequest.CompleteRequest(int result) Unknown
System.dll!System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(int bytes) Unknown
System.dll!System.Net.FixedSizeReader.ReadCallback(System.IAsyncResult transportResult) Unknown
System.ServiceModel.Internals.dll!System.Runtime.AsyncResult.Complete(bool completedSynchronously) Unknown
System.ServiceModel.dll!System.ServiceModel.Channels.ConnectionStream.IOAsyncResult.OnAsyncIOComplete(object state) Unknown
System.dll!System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(System.Net.Sockets.SocketAsyncEventArgs e) Unknown
System.dll!System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(System.Net.Sockets.SocketError socketError, int bytesTransferred, System.Net.Sockets.SocketFlags flags) Unknown
System.dll!System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* nativeOverlapped) Unknown
mscorlib.dll!System.Threading._IOCompletionCallback.PerformIOCompletionCallback(uint errorCode, uint numBytes, System.Threading.NativeOverlapped* pOVERLAP) Unknown
[Native to Managed Transition]
The exception you got is an indication of the client not being able to go past ASB gateway to talk to the backend. You could use the provided tracking ID (b6b8e25a-714f-4f55-8a79-91e390f47a96_G25) to open a support case. In case that exception persists, try a different namespace to see if that rules it out.
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"
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."
I am trying to set the PinX and PinY values for the currently selected shape in Visio on a keyboard sequence, e.g. [Ctrl]+[G]. The purpose of this endeavor is to programmatically drop a shape onto the Visio drawing based on the pin coordinates of the currently selected shape. I am using C# and the Microsoft.Office.Interop.Visio API to do this. I am using .NET 4.0 (mscorlib.dll is version 4.0.30319.1).
So far I have this code:
Application myApp; // the reference to the Visio Application instance, which is passed into this class via constructor
Shape currShape; // a global variable for this class
//... down to the method in question
void app_KeyUp(int KeyCode, int KeyButtonState, ref bool CancelDefault)
{
currShape = myApp.ActiveWindow.Selection[0];
String xCoord = currShape.get_Cells("PinX").Formula;
String yCoord = currShape.get_Cells("PinY").Formula;
//handle keyboard events here
//...
}
This code causes a COMException; after investigating, it turns out that even though myApp.ActiveWindow.Selection has an element [0] (its only element if only one shape is selected), I am not able to actually store that element into currShape. I do not know why that is. Strangely enough, the COMException does not cause the program to stop. The program exits out of the method when trying to assign to currShape, but execution continues.
I tried getting the current shape in another method; this raised the same COMException, except this time I was able to get a look at it because this exception stopped execution, unlike the previous.
This code:
public void test()
{
currShape = myApp.ActiveWindow.Selection[0];
String x = currShape.Shapes[1].get_Cells("PinX").Formula;
currShape.Shapes[1].get_Cells("PinX").FormulaForce = "5";
}
caused this exception:
System.Runtime.InteropServices.COMException was unhandled
Message="\n\nInvalid selection identifier."
Source="Microsoft Visio"
ErrorCode=-2032465753
StackTrace:
at Microsoft.Office.Interop.Visio.SelectionClass.get_Item(Int32 Index)
at WindowsFormsApplication4.Handler.test() in C:\Users\pvs5x\Documents\Visual Studio 2008\Projects\ACCESS(1)\Handler.cs:line 91
at WindowsFormsApplication4.Form3.changeColorToolStripMenuItem_Click(Object sender, EventArgs e) in C:\Users\pvs5x\Documents\Visual Studio 2008\Projects\ACCESS(1)\OpenSafetyCase.cs:line 355
at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
at System.Windows.Forms.ToolStripMenuItem.OnClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.ToolStripDropDown.OnMouseUp(MouseEventArgs mea)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ToolStrip.WndProc(Message& m)
at System.Windows.Forms.ToolStripDropDown.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.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(Int32 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 System.Windows.Forms.Application.Run(Form mainForm)
at WindowsFormsApplication4.Program.Main() in C:\Users\pvs5x\Documents\Visual Studio 2008\Projects\ACCESS(1)\Program.cs:line 20
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
I have no clue what "Invalid selection identifier" means, and Googling only yields this topic, which is for Visual Basic and not C#.
My two questions are:
(1) What is going wrong here?
(2) What is the proper way to access the currently selected shape for this kind of manipulation?
Thanks for any help.
I've run into troubles with selecting shapes in Visio in the past. How I solved it was by creating a Selection object and then using the Select method. I'm not sure if that will help you.
Also, you might cross-post this at VisGuy.com. That's where the Visio programmability experts are.
I wonder if the issue is related to the index of the Selection collection.
Give this a try:
currShape = myApp.ActiveWindow.Selection.Cast<Shape>().FirstOrDefault()
Dont forget to add a reference to Linq library by using System.Linq;.
It turns out that I needed to access [1] instead of [0], e.g.
currShape = myApp.ActiveWindow.Selection[1];
because Visio starts numbering objects from 1. Even though the Watch in Visual Studio on myApp.ActiveWindow.Selection had only one object at [0], I had to access it using [1].