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?
Related
Recently, we are facing crash issue's in our application(Not on regular basis, generally on the client side) and we are not able to track the reason for the error. Most of the time the error that we get from the log is something like this ..
Type : System.IndexOutOfRangeException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Message : Index was outside the bounds of the array.
Source : mscorlib
Help link :
Data : System.Collections.ListDictionaryInternal
TargetSite : Void Add(T)
HResult : -2146233080
Stack Trace : at System.Collections.Generic.List`1.Add(T item)
System.ComponentModel.BackgroundWorker.OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
at System.ComponentModel.BackgroundWorker.AsyncOperationCompleted(Object arg)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_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.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
Also in order to handle the crash at the application level, we have written certain code in App.xaml.cs file i.e.
private void CurrentDomain_UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
try
{
var exception = (Exception) e.ExceptionObject;
ExceptionHandler.HandleException(exception);
WpfMessageBox.Show(LocalizationManager.GetValue("AppErrorUnhandledException").ToString(),
LocalizationManager.GetValue("AppErrorUnhandledException").ToString(),
WpfMessageBoxButtons.OK,
WpfMessageBoxIcon.Error);
}
Is there anything we need to do besides this in order to stop the application to crash suddenly?
Note: Our application is based on MVVM pattern, concept such as service facade, unity, service orchestration, MutiThreading(Use of Background for calling service async)
P.S: Normally as per the logs, we are getting this error while caching the data.
Your CurrentDomain_UnhandledException will handle exceptions from Dispatcher, the UI thread.
BackgroundWorker is another thread, any exception occurs in this thread is not handled by the Dispatcher, and your system crashes.
You should handle the IndexOutOfRangeException inside the correct thread, the background one.
ng-HT
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.
The assembly qualified string used as a parameter below for a Uri works in XAML, but gives me the error shown when used in code.
I tried every kind of UriKind with the same result. How can I fix this?
[Test]
public void LargeImageSource_IsKnown()
{
var uri = new Uri(
"pack://application:,,,/" +
"MyAssembly.Core.Presentation.Wpf;component/" +
"Images/Delete.png", UriKind.RelativeOrAbsolute);
Assert.That(
_pickerActivityCollectionVm.DeleteActivityCommand.LargeImageSource,
Is.EqualTo(uri));
}
System.UriFormatException : Invalid URI: Invalid port specified.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
UPDATE
Based on Thomas' superb answer and my own comments about readability, I wound up using the following in my BaseTestFixture class. Hope this helps someone else.
protected virtual void OnFixtureSetUp() {
// logging, other one time setup stuff...
const string scheme = "pack";
if (!UriParser.IsKnownScheme(scheme)) {
Assert.That(PackUriHelper.UriSchemePack, Is.EqualTo(scheme));
}
}
That's because you're executing this code while the pack:// scheme is not yet registered. This scheme is registered when you create the Application object. You can add this code in the setup of your test fixture:
[SetUp]
public void Setup()
{
if (!UriParser.IsKnownScheme("pack"))
new System.Windows.Application();
}
EDIT: actually it seems the pack:// scheme is registered in the type initializer of the PackUriHelper class (which happens to be used by the Application class). So actually you don't need to create an instance of Application, you only need to access a static member of PackUriHelper to ensure the type initializer has run:
[SetUp]
public void Setup()
{
string s = System.IO.Packaging.PackUriHelper.UriSchemePack;
}
It appears that accessing PackUriHelper.UriSchemePack only registers the pack scheme, not the application scheme, which I needed to use the pack://application:,,,/ syntax in my unit tests. I therefore had to use the new Application() approach, which worked fine for registering both schemes.
If you're seeing this error in a Windows Store / WinRT project:
I wasn't able to use the "pack://" syntax at all when trying to load a resource in my C# app. What worked was ms-appx:// syntax of this kind:
ms-appx://[project folder]/[resource path]
For example, I wanted to load a resource dictionary named "styles.xaml" from a folder "core". This URI ended up working for me:
dictionary.Source = new System.Uri("ms-appx:///core/styles.xaml");
Even though the question specified WPF, the problem seemed extremely similar but ended up having a completely different solution, which took a while to find, and existing answers didn't help at all.
Again, this solution does not apply to WPF
gentlemens.
I have following definition in the Silverlight project, MainPage.xaml:
<UserControl
xmlns:model="clr-namespace:Engine.Silverlight.Web.Views;assembly=Engine.Login.Model"
d:DataContext="{d:DesignInstance Type=model:DesignTimeModel, IsDesignTimeCreatable=True}">...
And class in the Engine.Login.Model project, which used for design-time data binding (everything works fine for pre-initialized properties, but):
public class DesignTimeModel : INotifyPropertyChanged
{
public DesignTimeModel()
{
var d = Deployment.Current.Dispatcher;
d.BeginInvoke(
() =>
{
CacheClient c = new CacheClient();
c.GetResourcesCompleted +=(s,e)=>
{
d.BeginInvoke(
() => this.Resources = e.Result);
};
c.GetResourcesAsync();
}
);
Unfortunately, I got a System.ObjectDisposedException after WCF request completed (I tried to debug using different instance of VS by attaching to 1st VS instance process, but it does not help - same error, no additional info):
System.ObjectDisposedException
Cannot access a disposed object.
Object name: 'Dispatcher'.
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
I assume the Dispatcher behavior different in the design mode.
Can you help me how to resolve the problem to get design-time data using WCF in VS2010 XAML designer?
First, I belive that making a WCF call in a design time class isn't really a best practice! You should instead put some static dummy data.
For your problem, try using Deployment.Current.Dispatcher directly instead of pointing a variable to it.
I'm looking for a way to persist Silverlight objects to a user's PC, then re-hydrate them so the user can finish editing them.
Serialising with DataContractSerializer and persisting to IsolatedStorageFile works fine. However, deserialising causes a problem. Here's the code that causes the failure:
private string _FirstNames = string.Empty;
public string FirstNames
{
get { return _FirstNames; }
set
{
new PersonNameValidator().Validate(value); //<-- BOOM 8(
Set(ref _FirstNames, value, () => this.FirstNames);
}
}
The deserialiser calls the property setter, which in turn throws an exception and aborts the deserialisation.
I've tried explicitly applying DataContract/DataMember/IgnoreDataMember attributes, but then it doesn't play nicely with private fields:
System.Security.SecurityException
occurred Message="The data contract
type
'Trident.Model.Journey.JourneyApplication'
cannot be serialized because the
member '_TravellerSavingsAmount' is
not public. Making the member public
will fix this error. Alternatively,
you can make it internal, and use the
InternalsVisibleToAttribute attribute
on your assembly in order to enable
serialization of internal members -
see documentation for more details. Be
aware that doing so has certain
security implications."
How can I bypass the property setters during deserialisation?
I'd like to keep my classes focused on the domain, and not too polluted with infrastructure concerns.
A couple of ideas:
serialize a property that is used only for serialization thereby bypassing any validation
serialize a parent class and use a derived class for validation