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
I am getting a error when trying to verify container.
The configuration is invalid. Creating the instance for type
SettingModel failed. The registered delegate for type SettingModel
threw an exception. Invalid URI: Invalid port specified.
It seems to be caused by ThemeManager which belongs to mahapps.metro dll I can't seem to get it to play nicely with Simple Injector.
public SettingModel()
{
ThemeColor = ThemeManager.AppThemes.Select(t => t.Name).ToList();
AccentColor = ThemeManager.Accents.Select(a => a.Name).ToList();
var currentSetting = ThemeManager.DetectAppStyle(Application.Current);
CurrentTheme = currentSetting.Item1.Name;
CurrentAccent = currentSetting.Item2.Name;
}
I slowly remove stuff and it got to the point where every where I used theme manager it was breaking. So I start taking out pieces until I got to the point where I kept getting xamlparseexception when I compile which is strange because my code complied before I put in the simple injector.
I followed the tutorial for WPF integration unless that is out dated. I really wanted to try simple injector but it isn't integrating nicely.
Update: Full exception
System.InvalidOperationException was unhandled
HResult=-2146233079
Message=The configuration is invalid. Creating the instance for type MainWindow failed. The registered delegate for type MainWindow threw an exception. Invalid URI: Invalid port specified.
Source=SimpleInjector
StackTrace:
at SimpleInjector.InstanceProducer.VerifyInstanceCreation()
at SimpleInjector.Container.VerifyInstanceCreation(InstanceProducer[] producersToVerify)
at SimpleInjector.Container.VerifyThatAllRootObjectsCanBeCreated()
at SimpleInjector.Container.VerifyInternal()
at SimpleInjector.Container.Verify(VerificationOption option)
at SimpleInjector.Container.Verify()
at Program.Bootstrap() in c:\Users\Work\Documents\Visual Studio 2012\Projects\AzurePeek\AzurePeek\Program.cs:line 35
at Program.Main() in c:\Users\Work\Documents\Visual Studio 2012\Projects\AzurePeek\AzurePeek\Program.cs:line 14
at System.AppDomain._nExecuteAssembly(RuntimeAssembly 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.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: SimpleInjector.ActivationException
HResult=-2146233088
Message=The registered delegate for type MainWindow threw an exception. Invalid URI: Invalid port specified.
Source=SimpleInjector
StackTrace:
at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.InstanceProducer.VerifyInstanceCreation()
InnerException: System.UriFormatException
HResult=-2146233033
Message=Invalid URI: Invalid port specified.
Source=System
StackTrace:
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString)
at MahApps.Metro.ThemeManager.get_AppThemes()
at AzurePeek.M
odel.SettingModel..ctor() in c:\Users\Work\Documents\Visual Studio 2012\Projects\AzurePeek\AzurePeek\Model\SettingModel.cs:line 24
at lambda_method(Closure )
at SimpleInjector.InstanceProducer.GetInstance()
InnerException:
UPDATE
After a discussion with #punker76, who is one of the colaborators of the MahApps.Metro library, we concluded that this exception happens because you are running that code out of the scope of a WPF application. Most likely because you are testing your configuration inside a unit test.
There are two things you can do here. Either you need to fool your test suite to think it runs as a WPF application or you will have to move the code that depends on MyApps out of the SettingModel's constructor.
As discussed with #punker76, when starting a WPF application, a call to new FrameworkElement() somehow ensures that the internal UriParser is able to parse pack:// uris (talk about weird hidden ugly scary dependencies).
The other option, which is my preference, is to make constructor's simple and resilient to failure. This means that any code that is not related to building up the object graph should be moved out of the constructor and should be done at runtime.
There are a lot of ways to do this, but a simple way to do this is by postponing the initialization of the properties of the SettingsModel or postponing the creation of SettingsModel itself, since it doesn't look like a service that should be maintained by your DI container at all.
Postponing the creation of SettingsModel is easy by introducing an abstraction that allows access to the settings at runtime:
public interface ISettingsProvider {
SettingsModel CurrentSettings { get; }
}
With the following implementation:
public class SettingsProvider : ISettingsProvider {
private readonly Lazy<SettingsModel> model = new Lazy<SettingsModel>(
() => new SettingsModel());
public SettingsModel CurrentSettings {
get { return this.model.Value; }
}
}
This can be registered as follows:
container.RegisterSingle<ISettingsProvider>(new SettingsProvider());
ORIGINAL ANSWER
The problem is unlikely to be caused by Simple Injector. There isn't anything special about Simple Injector's Verify() method. If you replace the call to Verify() with new SettingModel();, you will most likely see the same exception.
As a matter of fact, if you look at the source code of the MahApps.Metro.ThemeManager.AppThemes property, you'll see the following code:
var themes = new[] { "BaseLight", "BaseDark" };
_appThemes = new List<AppTheme>(themes.Length);
foreach (var color in themes)
{
var appTheme = new AppTheme(color, new Uri(string.Format("pack://application:,,,/MahApps.Metro;component/Styles/Accents/{0}.xaml", color)));
_appThemes.Add(appTheme);
}
return _appThemes;
If you look at the url that is supplied to the Uri constructor, you can understand why it throws an "Invalid URI: Invalid port specified" exception. If you run the following code in a console application, you will get the same error:
new Uri("pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml");
So I have to conclude that there is a bug in the MahApps.Metro.ThemeManager.AppThemes property that is causing this. I'm wondering how you actually managed to get this working before, because I don't see a way to work around that bug. Did you happen to upgrade to a newer version of MahApps.Metro at the same time as you introduced Simple Injector?
I have a question about ThreadStart delegates in vb.net. I am taking over a senior programmer's project, and he is much more experienced then myself so I'm kind of lost on what he was trying to do. I am trying to do some research on Threading but there is a lot out there on this topic and don't want to waste my time with stuff that doesn't pertain to my error here. I will post the whole exception message and hopefully someone can point me in the direction of an article that I could read to learn more about it.
System.InvalidOperationException was unhandled
Message=The thread was created with a ThreadStart delegate that does not accept a parameter.
Source=mscorlib
StackTrace:
at System.Threading.Thread.Start(Object parameter)
at LabelLibrary.LabelPrinter.Print(PrintQueue queue) in C:\Documents and Settings\bjorandb\Desktop\LabelPrintingService\LabelTemplates\clsLabelPrinter.vb:line 94
at LabelLibrary.LabelPrinter.Print() in C:\Documents and Settings\bjorandb\Desktop\LabelPrintingService\LabelTemplates\clsLabelPrinter.vb:line 53
at PrintApplyApplication.HomeController.PrintThread.Print() in C:\Documents and Settings\bjorandb\Desktop\LabelPrintingService\PrintApplyApplication\Controllers\HomeController.vb:line 85
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Here is the function that the error is getting thrown in, but I don't know how much help it will be by itself.
Public Function Print(ByVal queue As PrintQueue) As PrintResult
Dim result As PrintResult = Nothing
Dim job As PrintSystemJobInfo = Nothing
Dim thread As Threading.Thread = Nothing
result = New PrintResult
If queue Is Nothing Then
result.Status = "Can not find printer " & queue.Name & "."
ElseIf PrintFilePath Is Nothing Then
result.Status = "Print File Path Cannot be nothing."
Else
Try
thread = New Threading.Thread(AddressOf AddJob)
thread.SetApartmentState(Threading.ApartmentState.STA)
thread.Start(queue) <--- (Exception is being thrown here!!)
result.Status &= "Print Sent Successfully"
Catch ex As PrintJobException
If ex.InnerException.Message = "File contains corrupted data." Then
result.Status &= "Could not generate a label with given xps file. Check the xps file format and if it is corrupted."
End If
result.Status &= "There was an error printing."
result.ErrorMessage = ex.Message
End Try
If queue.IsOutOfPaper Then
result.Status &= "The printer is out of Paper."
End If
If queue.IsPaperJammed Then
result.Status &= "The Printer is jammed."
End If
If (queue.IsOutOfMemory) Then
result.Status &= "The Printer is out of memory."
End If
End If
Return result
End Function
And here is the AddJob method
Private Sub AddJob()
Dim job As PrintSystemJobInfo = Nothing
Try
job = LocalPrintServer.GetDefaultPrintQueue.AddJob("Text", PrintFilePath, False)
job.Refresh()
While Not (job.IsCompleted Or job.IsDeleted)
job.Refresh()
End While
Catch ex As PrintJobException
End Try
If System.IO.File.Exists(PrintFilePath) Then
System.IO.File.Delete(PrintFilePath)
End If
End Sub
Without the code I can only speculate that you're creating the thread using ThreadStart and then calling the overload of Start that takes a parameter.
You should either use ParameterizedThreadStart or simply call the Start method with no parameters.
Edit: Like I said, the thread start method call is not compatible with the definition of AddJob. Simply use Thread.Start().
The AddJob method doesn't have the right signature, it needs to have exactly 1 object parameter.
Your AddJob sub does not accept a parameter. If you want it to accept a parameter, you'll need to change its signature to accept a single parameter of type Object. You will, of course, need to modify the body of the message to make use of that parameter for it to have any actual effect, though.
I am trying to make a call from a Silverlight application to a WCF service returning JSON. It's simply returning an integer. I have used Fiddler to verify that it is never making the call to my webservice. I am getting an error that says "Operation is not valid due to the current state of the object." It occurs on the line, HttpWebResponse response = (HttpWebResponse) _webRequest.EndGetResponse(result); Stacktrace can be provided if needed.
public MainPage()
{
InitializeComponent();
StartWebRequest();
}
void StartWebRequest()
{
HttpWebRequest _webRequest = (HttpWebRequest)WebRequest.Create(new Uri("http://www.example.com/MyJSON.svc/onlineusercount"));
_webRequest.ContentType = "text/json";
_webRequest.Method = "GET";
_webRequest.BeginGetResponse(FinishWebRequest, _webRequest);
}
void FinishWebRequest(IAsyncResult result)
{
HttpWebRequest _webRequest = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)_webRequest.EndGetResponse(result);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
needle.Value = Convert.ToInt32(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
}
}
UPDATE: I have commented out the line above that says
_webRequest.ContentType = "text/json";
My new error says: SecurityException unhandled by user code. I believe this means I should use a try catch, but I am not sure what type of exception to catch.
My stack trace is as follows:
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at FuelizerGuage.MainPage.FinishWebRequest(IAsyncResult result)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassd.<InvokeGetResponseCallback>b__b(Object state2)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Also according to Fiddler, my silverlight application is now making at call to my webservice domain looking for clientaccesspolicy.xml and then looks for crossdomain.xml, neither of which exist.
"GET" requests cannot have a Content-Type header (they cannot have content). The HttpWebRequest implementation in Silverlight is more strict than the one in the desktop framework. Try removing the ling which defines that property and it should work.
Update: you're hitting a cross-domain problem in your application. To prevent some kinds of cross-domain attacks, SL requires that any requests going to a domain other than the one where the SL applicaiton (the .xap file) originated to be subject to a cross-domain policy - they're disallowed by default. You can find more information about this at http://msdn.microsoft.com/en-us/library/cc645032(VS.95).aspx.
To solve this problem you'll essentially have to add a cross-domain policy to your service to allow SL apps to consume it.
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.