Nancy.Json.JsonSettings in Nancy v2 - nancy

I'm upgrading my project from Nancy 1.4.5 -> 2.0
And I have errors:
public class AppBootstrapper : AutofacNancyBootstrapper
{
private readonly ILifetimeScope _scope;
public AppBootstrapper(ILifetimeScope scope)
{
_scope = scope;
}
protected override ILifetimeScope GetApplicationContainer()
{
return _scope;
}
protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
{
JsonSettings.MaxJsonLength = int.MaxValue;
JsonSettings.RetainCasing = true;
base.ApplicationStartup(container, pipelines);
}
}
}
Error CS0103 The name 'JsonSettings' does not exist in the current context
How can I resolve this issue?

I added method to AppBootstrapper class:
public class AppBootstrapper : DefaultNancyBootstrapper
{
public override void Configure(INancyEnvironment environment)
{
environment.Json(retainCasing: true);
}
... other methods
}
And added maxJsonLength to web.config:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483647"/>
</webServices>
</scripting>
</system.web.extensions>

Related

Proper way to handle prism navigation exception

I am using Prism Wpf 8.1.97, and DryIoc container.
In my scenario i have to navigate between two views, so I implemented the INavigationAware Interface provided by Prism Framework in my viewModels.
I call the IRegionManager RequestNavigate method to perform the navigation from the VMA to VMB.
Unfortunately, I forgot to register a IService dependency that is needed in the VMB Ctor, so when I perform the navigation process I get the exception in the navigation callback.
The IService interface
public interface IService
{
}
ViewModel A:
public class ViewAViewModel : BindableBase, INavigationAware
{
private readonly IRegionManager regionManager;
public ViewAViewModel(IRegionManager regionManager)
{
this.regionManager = regionManager;
}
public void OnNavigatedTo(NavigationContext navigationContext)
{
regionManager.TryRequestNavigate("ContentRegion", "ViewB", new NavigationParameters());
}
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
}
}
ViewModelB:
public class ViewBViewModel : BindableBase, INavigationAware
{
public ViewBViewModel(IService service)
{
}
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
public void OnNavigatedFrom(NavigationContext navigationContext)
{
}
public void OnNavigatedTo(NavigationContext navigationContext)
{
}
}
I created an extension method to keep it simple..
public static class IRegionManager_Extensions
{
public static void TryRequestNavigate(this IRegionManager regionManager, string regionName, string target, NavigationParameters navigationParameters)
{
regionManager.RequestNavigate(regionName, target, NavigationResult =>
{
if (NavigationResult.Result == false)
{
MessageBox.Show(NavigationResult.Error.InnerException.Message, "Navigation Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
}, navigationParameters);
}
}
Unfortunately what I get from the InnerException.Message is
ContainerException: code: Error.UnableToResolveFromRegisteredServices;
message: Unable to resolve Resolution root
Module1.ViewModels.ViewBViewModel from container without scope with
Rules with {TrackingDisposableTransients,
UseDynamicRegistrationsAsFallbackOnly, FuncAndLazyWithoutRegistration,
SelectLastRegisteredFactory} and without
{ThrowOnRegisteringDisposableTransient,
UseFastExpressionCompilerIfPlatformSupported} with
FactorySelector=SelectLastRegisteredFactory with
Made={FactoryMethod=ConstructorWithResolvableArguments} with normal
and dynamic registrations: (DefaultDynamicKey(0), {FactoryID=178,
ImplType=Module1.ViewModels.ViewBViewModel, Reuse=TransientReuse,
HasCondition})
without no reference to "IService"
I need to show that the navigation failed because IService implementation is not found in the container.
Is there a way to get the missing service Interface name from the exception?
Service name in the exception is null
Thanks.

Navigation between lazy loaded modules with Prism and WPF

Hello I'm trying to setup an architecture where only one module gets booted when the app is launched. Then I'd like to lazy load other modules based on the user's actions.
To achieve this in my app.xaml.cs I have one module loaded at bootstrap time (MainModule), and an other has InitializationMode = InitializationMode.OnDemand
protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
{
Type BlipModuleType = typeof(BlipModule);
moduleCatalog.AddModule(new ModuleInfo()
{
ModuleName = BlipModuleType.Name,
ModuleType = BlipModuleType.AssemblyQualifiedName,
InitializationMode = InitializationMode.OnDemand
});
moduleCatalog.AddModule<MainModule>();
}
then my main module, which displays the view correctly, has a single view registered to the only region available:
public class MainModule : IModule
{
private readonly IRegionManager _regionManager;
public MainModule(IRegionManager regionManager)
{
_regionManager = regionManager;
}
public void OnInitialized(IContainerProvider containerProvider)
{
_regionManager.RegisterViewWithRegion(RegionNames.ContentRegion, typeof(ViewA));
}
public void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
The lazy loaded module has the same structure, registering a different view (which works properly if i decide to use it as my main module)
public class BlipModule : IModule
{
private readonly IRegionManager _regionManager;
public BlipModule(IRegionManager regionManager)
{
_regionManager = regionManager;
}
public void OnInitialized(IContainerProvider containerProvider)
{
_regionManager.RegisterViewWithRegion(RegionNames.ContentRegion, typeof(ViewB));
}
public void RegisterTypes(IContainerRegistry containerRegistry)
{
}
}
finally I have a Command in the viewmodel of my MainModule ViewA, that is supposed to load the new module and navigate to it.
public class ViewAViewModel : BindableBase
{
const string BlipModuleName = "BlipModule";
public ReactiveCommand ChangeRoute { get; set; } = new ReactiveCommand();
public ViewAViewModel(IRegionManager regionManager, IModuleManager moduleManager)
{
ChangeRoute.Subscribe(res =>
{
moduleManager.LoadModule(BlipModuleName);
});
moduleManager.LoadModuleCompleted += (s, e) =>
{
if (e.ModuleInfo.ModuleName == BlipModuleName)
{
regionManager.RequestNavigate(RegionNames.ContentRegion, new Uri(BlipModuleName, UriKind.Relative));
}
};
}
}
The viewB of the BlipModule is actually loaded (I get a hit if I set a breakpoint in the view's constructor), but instead of the view I get a white page with "System.Object" inside of it.
Any idea? thanks!
You want to RegisterForNavigation instead of RegisterViewWithRegion.

Provide custom rootpath to Nancy when using OWIN

I have a sample application that shows how to host Nancy on node.js.
To do that I need to change the rootpath. I ended up with something like that:
public class Startup
{
public static void Configuration(IAppBuilder app)
{
string rootpath = app.Properties["node.rootpath"] as string;
app.UseNancy(options => options.Bootstrapper = new NodeBootstrapper(rootpath));
}
}
public class NodeRootPathProvider : IRootPathProvider
{
private string rootpath;
public NodeRootPathProvider(string rootpath)
{
this.rootpath = rootpath;
}
public string GetRootPath()
{
return this.rootpath;
}
}
public class NodeBootstrapper : DefaultNancyBootstrapper
{
private string rootpath;
public NodeBootstrapper(string rootpath)
: base()
{
this.rootpath = rootpath;
}
protected override IRootPathProvider RootPathProvider
{
get { return new NodeRootPathProvider(this.rootpath); }
}
}
Is there a way to simplfy this?

module dependencies in prism wpf

i am trying to code something similar to the project 'Modularity with unity'.
i built 2 modules: Module A (loaded via code) and Module D (loaded from directory).
both are loaded successfully.
but when i try to set dependency it's not working.
i can't really figure out where the dependency is mentioned in this project.
(i set the dependency as attribute in ModuleA class, moduleD is copied after build)
this is my implementation:
Bootstrapper.cs
protected override IModuleCatalog CreateModuleCatalog()
{
return new AggregateModuleCatalog();
}
protected override void ConfigureModuleCatalog()
{
base.ConfigureModuleCatalog();
Type moduleAType = typeof(ModuleAModule);
ModuleCatalog.AddModule(new ModuleInfo()
{
ModuleName = ModuleNames.ModuleA,
ModuleType = moduleAType.AssemblyQualifiedName
});
DirectoryModuleCatalog directoryCatalog = new DirectoryModuleCatalog() { ModulePath = #".\Modules" };
((AggregateModuleCatalog)ModuleCatalog).AddCatalog(directoryCatalog);
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
this.RegisterTypeIfMissing(typeof(IModuleTracker), typeof(ModuleTracker), true);
}
ModuleA.cs
[Module(ModuleName = ModuleNames.ModuleA)]
[ModuleDependency(ModuleNames.ModuleD)]
public class ModuleAModule : IModule
{
private ILoggerFacade _logger;
private IModuleTracker _moduleTracker;
public ModuleAModule(ILoggerFacade logger, IModuleTracker moduleTracker)
{
_logger = logger;
_moduleTracker = moduleTracker;
_moduleTracker.ModuleConstructed("ModuleA");
}
public void Initialize()
{
_logger.Log("ModuleA demonstrates logging during Initialize().", Category.Info, Priority.Medium);
_moduleTracker.ModuleInitialized("ModuleA");
}
}
ModuleD.cs
[Module(ModuleName = ModuleNames.ModuleD)]
public class ModuleDModule : IModule
{
private ILoggerFacade _logger;
private IModuleTracker _moduleTracker;
public ModuleDModule(ILoggerFacade logger, IModuleTracker moduleTracker)
{
_logger = logger;
_moduleTracker = moduleTracker;
_moduleTracker.ModuleConstructed("ModuleD");
}
public void Initialize()
{
_moduleTracker.ModuleInitialized("ModuleD");
}
}
perhaps that has something to do with the order in which your modules get loaded? As far as I see Module A gets loaded before ModuleD to which is has a dependency.
Don't know if that does help you but that was my first thought..
Which error message do you get?

MEF problem with import

models from shell-view-model with abstract factory pattern. I need inject in view-models classes from external assembly. If I use abstract factory pattern on creation view-models. Problem is imported classes in view-models are null.
Shell-view-models look like this:
public interface IViewModelFactory
{
ILogOnViewModel CreateLogOnViewModel(IShellViewModel shellViewModel);
IMessengerViewModel CreateMessengerViewModel(IShellViewModel shellViewModel);
}
[Export(typeof(IViewModelFactory))]
public class DefaulFactoryViewModel:IViewModelFactory
{
#region Implementation of IViewModelFactory
public ILogOnViewModel CreateLogOnViewModel(IShellViewModel shellViewModel)
{
return new LogOnViewModel(shellViewModel);
}
public IMessengerViewModel CreateMessengerViewModel(IShellViewModel shellViewModel)
{
return new MessengerViewModel(shellViewModel);
}
#endregion
}
public interface IShellViewModel
{
void ShowLogOnView();
void ShowMessengerView();
}
[Export(typeof(IShellViewModel))]
public class ShellViewModel : Conductor<IScreen>, IShellViewModel
{
private readonly IViewModelFactory _factory;
[ImportingConstructor]
public ShellViewModel(IViewModelFactory factory)
{
_factory = factory;
ShowLogOnView();
}
public void ShowLogOnView()
{
var model = _factory.CreateLogOnViewModel(this);
// var model = IoC.Get<LogOnViewModel>();
ActivateItem(model);
}
public void ShowMessengerView()
{
var model = _factory.CreateMessengerViewModel(this);
ActivateItem(model);
}
}
Some view-model.:
public class LogOnViewModel : Screen,ILogOnViewModel
{
[Import]//inject class from external assembly
private IPokecConnection _pokecConn;
private readonly IShellViewModel _shellViewModel=null;
private User _user=null;
public LogOnViewModel(IShellViewModel shellViewModel)
{
_shellViewModel = shellViewModel;
_user = new User();
}
}
variable _pokecConn are null becasuse I use abstract factory on creation new view-models.
if I use in shell-view model this:
var model = IoC.Get<LogOnViewModel>();
instead this:
var model = _factory.CreateLogOnViewModel(this);
and add Export attribute on view-models classes it works good, but I would like use abstract factory, and inject in view-model only classes from extrenal assembly.
It exist solution on this problem, or I must create view-models from IoC and export all class? Thanl for advance.
EDITED :
MEF BOOTSTRAPER CLASS:
public class MefBootStrapper : Bootstrapper<IShellViewModel>
{
#region Fields
private CompositionContainer _container;
#endregion
#region Overrides
protected override void Configure()
{ // configure container
#if SILVERLIGHT
_container = CompositionHost.Initialize(
new AggregateCatalog(AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>()));
#else
var catalog =
new AggregateCatalog(
AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());
//add external DLL
catalog.Catalogs.Add(
new AssemblyCatalog(string.Format(
CultureInfo.InvariantCulture, "{0}{1}", System.IO.Directory.GetCurrentDirectory(), #"\Pokec_Toolkit.dll")));
_container = new CompositionContainer(catalog);
#endif
var batch = new CompositionBatch();
batch.AddExportedValue<IWindowManager>(new WindowManager());
batch.AddExportedValue<IEventAggregator>(new EventAggregator());
batch.AddExportedValue(_container);
_container.Compose(batch);
_container.SatisfyImportsOnce(this);
}
protected override object GetInstance(Type serviceType, string key)
{
string contract = string.IsNullOrEmpty(key) ? AttributedModelServices.GetContractName(serviceType) : key;
var exports = _container.GetExportedValues<object>(contract);
if (exports.Count() > 0)
return exports.First();
throw new Exception(string.Format("Could not locate any instances of contract {0}.", contract));
}
protected override IEnumerable<object> GetAllInstances(Type serviceType)
{
return _container.GetExportedValues<object>(AttributedModelServices.GetContractName(serviceType));
}
protected override void BuildUp(object instance)
{
_container.SatisfyImportsOnce(instance);
}
#endregion
}
Did you forget the attribute ImportingConstructor for the LogOnViewModel constructor?
EDIT: Import property always null (MEF import issue)

Resources