Convention based binding in Ninject 3.0 - conventions

I'm trying to setup Ninject on my new project and I want to scan assembilies using convetions so that
IFoo
will automatically resolve to
IBar
All the samples and documentation describes using this approach
kernel.Scan(...)
while the Ninject 3 Kernel seems to use .Load instead. If I'm using Load for scanning then how do I configure scanning with conventions?
Edit
I was able to get it working using: https://github.com/ninject/ninject.extensions.conventions/wiki/What-is-configuration-by-convention
However, now I can't get my modules to load. I'm using the code below and getting the error below.
IKernel kernel = new StandardKernel();
kernel.Bind(x => x
.FromAssembliesMatching("Crt.*.dll")
.SelectAllTypes()
.BindAllInterfaces()
);
kernel.Load("*.dll");
return kernel;
Error:
Ninject.ActivationException was unhandled
Message=Error activating ITrainingEngine
More than one matching bindings are available.
Activation path:
1) Request for ITrainingEngine
Suggestions:
1) Ensure that you have defined a binding for ITrainingEngine only once.
Source=Ninject
StackTrace:
at Ninject.KernelBase.Resolve(IRequest request) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 380
at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 263
at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 37
at Crt.BlackBox.Train.Program.Run() in C:\code\Crimson\CRT\readmission\src\Crt.BlackBox\Crt.BlackBox.Train\Program.cs:line 54
at Crt.BlackBox.Train.Program.Main(String[] args) in C:\code\Crimson\CRT\readmission\src\Crt.BlackBox\Crt.BlackBox.Train\Program.cs:line 24
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
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:

Use SelectAllClasses instead of SelectAllTypes

Related

Upgrade to Prism 8 is causing navigation errors

Environment
Xamarin Forms: 5.0.0.1709-pre4 (but also fails with 4.8.0.1687)
VS2019 16.8.3
XCode: 12.2
Prism NuGets
Prism.DryIoc.Extensions 8.0.48
Prism.Forms 8.0.0.1909
Prism.PluginPopups 8.0.31-beta
Shiny.Prism 8.0.48
Inner Exception from INavigationResult: DryIoc.ContainerException -> InvalidOperationException
code: Error.UnableToResolveFromRegisteredServices;
message: Unable to resolve Resolution root IRMobile.PageModels.LandingPageModel with passed arguments
[Constant(Prism.Navigation.ErrorReportingNavigationService,
typeof(Prism.Navigation.ErrorReportingNavigationService))]
from container with scope {Name=null}
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=317, ImplType=IRMobile.PageModels.LandingPageModel,
Reuse=TransientReuse, HasCondition})
Stack Trace from InnerException:
at DryIoc.Container.TryThrowUnableToResolve (DryIoc.Request request) [0x00058] in /_/src/DryIoc/Container.cs:1077
at DryIoc.Container.DryIoc.IContainer.ResolveFactory (DryIoc.Request request) [0x00072] in /_/src/DryIoc/Container.cs:1059
at DryIoc.Container.ResolveAndCacheKeyed (System.Int32 serviceTypeHash, System.Type serviceType, System.Object serviceKey, DryIoc.IfUnresolved ifUnresolved, System.Object scopeName, System.Type requiredServiceType, DryIoc.Request preResolveParent, System.Object[] args) [0x000c5] in /_/src/DryIoc/Container.cs:471
at DryIoc.Container.DryIoc.IResolver.Resolve (System.Type serviceType, System.Object serviceKey, DryIoc.IfUnresolved ifUnresolved, System.Type requiredServiceType, DryIoc.Request preResolveParent, System.Object[] args) [0x00042] in /_/src/DryIoc/Container.cs:430
at DryIoc.Resolver.Resolve (DryIoc.IResolver resolver, System.Type serviceType, System.Object[] args, DryIoc.IfUnresolved ifUnresolved, System.Type requiredServiceType, System.Object serviceKey) [0x00000] in /_/src/DryIoc/Container.cs:7809
at Prism.DryIoc.DryIocContainerExtension.Resolve (System.Type type, System.ValueTuple`2[System.Type,System.Object][] parameters) [0x0001c] in /_/external/Prism/src/Containers/Prism.DryIoc.Shared/DryIocContainerExtension.cs:294
App.xaml.cs
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
// for RgPopups
containerRegistry.RegisterPopupNavigationService();
containerRegistry.RegisterPopupDialogService();
// Essentials
containerRegistry.Register<ISecureStorage, SecureStorageImplementation>();
containerRegistry.RegisterSingleton<IAppInfo, AppInfoImplementation>();
// page stuff
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<IconNavigationPage>();
containerRegistry.RegisterSingleton<IPageBehaviorFactory, CustomPageBehaviorFactory>();
...
// Page and model registrations
containerRegistry.RegisterForNavigation<LoginPage, LoginPageModel>();
containerRegistry.RegisterForNavigation<LandingPage, LandingPageModel>();
}
I get this exeption when trying to navigate to a root master/detail page from a LoginPage
await NavigationService.NavigateAsync("/MainPage/NavigationPage/LandingPage")
and the constructor for the LandingPage is
public LandingPageModel(INavigationService navigationService, IMapper mapper, IDialogs dialogs, IPushManager pushManager) : base(navigationService, mapper)
I am fairly new to Prism so I'm sure I am missing something, a registration or maybe a NuGet package, but I'm not sure what it would be. I commented out the Registrations for Popup as I was getting the same error, but referring to Prism.Plugin.Popups.PopupPageNavigationService
As always, thanks for any help!
It looks like you are attempting to navigate to a page called LandingPage, but you haven't told the container what LandingPage is.
Every time you want to create a new view and navigate to it, you need to register it for Navigation inside your App.Xaml.cs file;
containerRegistry.RegisterForNavigation<LandingPage, LandingPageViewModel>();
This line registers the view and its corresponding ViewModel inside the container. Once the container knows about the view, the NavigationService can resolve the view you wish to navigate to using the literal name of the view LandingPage.
Now you can call
await NavigationService.NavigateAsync("LandingPage");
//or
await NavigationService.NavigateAsync("/MainPage/NavigationPage/LandingPage")
NOTE
Prism navigation has a couple of neat tricks built into it. It is Uri based, so every time you navigate to another view, passing the name of the view in the NavigateAsync method will stack the view on top of the others. This means that if you start at the URI NavigationPage/PageA, if you then say NavigateAsync("PageB") you will end up at NavigationPage/PageA/PageB.
Additionally, including the / character at the very beginning of the NavigateAsync argument completely resets the stack. So if you navigate to /PageC from NavigationPage/PageA/PageB, this resets the stack to just PageC

ReSharper 2018.1.2 NUnit TestCaseSource (.NET Core / VS2017)

I have seen all of the following questions:
NUnit .NET Core running through Resharper
Running NUnit Tests in .NET Core with ReSharper
NUnit TestCaseSource
Despite following all of their advice and having the following lines in all of my
test projects:
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.10.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.7.2" />
I am still getting the following errors in the Unit Test Explorer window of ReSharper (version 2018.1.2):
2018.06.23 11:22:21.292 ERROR Transition failed: Transition from state <HandShake> on event <remote::.ProtocolVersion>. Cause: System.InvalidOperationException: Test-cases are missing for the selected tests. Rebuild the project and try again. at JetBrains.ReSharper.UnitTestFramework.DotNetCore.DotNetVsTest.DotNetVsTestExecution.SendGetProcessStartInfo() at Appccelerate.StateMachine.Machine.ActionHolders.ArgumentLessActionHolder.Execute(Object argument) at Appccelerate.StateMachine.Machine.States.State`2.ExecuteEntryAction(IActionHolder actionHolder, ITransitionContext`2 context)
--- EXCEPTION #1/1 [LoggerException]
Message = “
Transition failed: Transition from state <HandShake> on event <remote::.ProtocolVersion>.
Cause: System.InvalidOperationException: Test-cases are missing for the selected tests. Rebuild the project and try again.
at JetBrains.ReSharper.UnitTestFramework.DotNetCore.DotNetVsTest.DotNetVsTestExecution.SendGetProcessStartInfo()
at Appccelerate.StateMachine.Machine.ActionHolders.ArgumentLessActionHolder.Execute(Object argument)
at Appccelerate.StateMachine.Machine.States.State`2.ExecuteEntryAction(IActionHolder actionHolder, ITransitionContext`2 context)
”
ExceptionPath = Root
ClassName = JetBrains.Util.LoggerException
HResult = COR_E_APPLICATION=80131600
StackTraceString = “
at JetBrains.ReSharper.UnitTestFramework.DotNetCore.DotNetVsTest.DotNetVsTestProtocol.<.ctor>b__22_14(Object sender, TransitionExceptionEventArgs`2 args)
at Appccelerate.StateMachine.Machine.StateMachine`2.RaiseEvent[T](EventHandler`1 eventHandler, T arguments, ITransitionContext`2 context, Boolean raiseEventOnException)
at Appccelerate.StateMachine.Machine.StateMachine`2.OnExceptionThrown(ITransitionContext`2 context, Exception exception)
at Appccelerate.StateMachine.Machine.Contexts.TransitionContext`2.OnExceptionThrown(Exception exception)
at Appccelerate.StateMachine.Machine.States.State`2.HandleException(Exception exception, ITransitionContext`2 context)
at Appccelerate.StateMachine.Machine.States.State`2.HandleEntryActionException(ITransitionContext`2 context, Exception exception)
at Appccelerate.StateMachine.Machine.States.State`2.ExecuteEntryAction(IActionHolder actionHolder, ITransitionContext`2 context)
at Appccelerate.StateMachine.Machine.States.State`2.ExecuteEntryActions(ITransitionContext`2 context)
at Appccelerate.StateMachine.Machine.States.State`2.Entry(ITransitionContext`2 context)
at Appccelerate.StateMachine.Machine.States.State`2.EnterShallow(ITransitionContext`2 context)
at Appccelerate.StateMachine.Machine.States.State`2.EnterHistoryNone(ITransitionContext`2 context)
at Appccelerate.StateMachine.Machine.States.State`2.EnterByHistory(ITransitionContext`2 context)
at Appccelerate.StateMachine.Machine.Transitions.Transition`2.Fire(ITransitionContext`2 context)
at Appccelerate.StateMachine.Machine.States.State`2.Fire(ITransitionContext`2 context)
at Appccelerate.StateMachine.Machine.StateMachine`2.Fire(TEvent eventId, Object eventArgument)
at Appccelerate.StateMachine.ActiveStateMachine`2.ProcessEventQueue(CancellationToken cancellationToken)
at Appccelerate.StateMachine.ActiveStateMachine`2.<Start>b__32_0()
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
at System.Threading.Tasks.Task.ExecutionContextCallback(Object obj)
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.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
at System.Threading.Tasks.Task.ExecuteEntry(Boolean bPreventDoubleExecution)
at System.Threading.Tasks.ThreadPoolTaskScheduler.LongRunningThreadWork(Object obj)
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(Object obj)
”
2018.06.23 11:22:21.315 ERROR System.InvalidOperationException: Test-cases are missing for the selected tests. Rebuild the project and try again.
at JetBrains.ReSharper.UnitTestFramework.DotNetCore.DotNetVsTest.DotNetVsTestExecution.SendGetProcessStartInfo()
at Appccelerate.StateMachine.Machine.ActionHolders.ArgumentLessActionHolder.Execute(Object argument)
at Appccelerate.StateMachine.Machine.States.State`2.ExecuteEntryAction(IActionHolder actionHolder, ITransitionContext`2 context)
2018.06.23 11:22:21.316 WARN Element UnitTests.Tests.RegressionTests was left pending after its run completion.
2018.06.23 11:22:21.316 WARN Element UnitTests.Tests.RegressionTests.TestAllRegressions was left pending after its run completion.
These are the newest versions of each of these packages, but I have also tried matching NUnit's version to the TestAdapter's version (3.10.0). The most baffling part of this is that Visual Studio's Test Explorer has no problem running the tests! I would very much like to use ReSharper's explorer to easily run their profiling and coverage tools on my tests.
Moreover, at some point in time ReSharper's test explorer used to work, but I'm not aware of the particular version combination that led to it. This setup still works for basic [Test] style tests and only fails for [TestCaseSource] tests.
ETA: ReSharper is also not running namespace-level setup and tear-down fixtures. Maybe this is part of the problem?
How do I fix this?
This was a bug. JetBrains fixed it in ReSharper 2018.2 EAP 5. It's still finicky, but when it works, it works.

No http handler was found for request type 'GET' in dotnetnuke

Dnn data base and files of dotnetnuke moved to new host but when starting it show error:
The page cannot be displayed because an internal server error has occurred.
i have checked log file of dnn in \Portals\_default\Logs it shows error :
2016-10-16 19:09:25,763 [WIN-MA182KN2LA7][Thread:7][ERROR] DotNetNuke.Entities.Urls.UrlRewriterUtils - System.Web.HttpException (0x80004005): Error executing child request for ~/Default.aspx. ---> System.Web.HttpException (0x80004005): No http handler was found for request type 'GET'
at System.Web.HttpApplication.MapIntegratedHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig, Boolean convertNativeStaticFileModule)
at System.Web.HttpServerUtility.Execute(String path, TextWriter writer, Boolean preserveForm)
at System.Web.HttpServerUtility.Execute(String path, TextWriter writer, Boolean preserveForm)
at System.Web.HttpServerUtility.Transfer(String path, Boolean preserveForm)
at DotNetNuke.Entities.Urls.AdvancedUrlRewriter.Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, Boolean transfer, Boolean showDebug)
at DotNetNuke.Entities.Urls.AdvancedUrlRewriter.ProcessRequest(HttpContext context, Uri requestUri, Boolean useFriendlyUrls, UrlAction result, FriendlyUrlSettings settings, Boolean allowSettingsChange, Guid parentTraceId)
i have checked url rewitemodule in iis . it has been installed . Domain name is correct to
Handling *.aspx is not defined in iis. go into
IIS manager --> Default Website --> handler Mapping
Check if you have a mapping for aspx... ideally you should see 2 mappings for .aspx...
you can also use the command line to get the info by the following:
C:\Windows\System32\inetsrv>appcmd list config "Default Web Site" -section:handlers >"give output txt file name"

Null buffer error

I've just noticed that when running an application I periodically get an error message.
Server Error in '/' Application.
Buffer cannot be null.
Parameter name: buffer
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Buffer cannot be null.
Parameter name: buffer
Stack trace:
[ArgumentNullException: Buffer cannot be null.
Parameter name: buffer]
System.IO.MemoryStream..ctor(Byte[] buffer, Boolean writable) +12627669
MemcachedProviders.Session.Common.Deserialize(HttpContext context, Byte[] serializedItems, Int32 timeout) +47
MemcachedProviders.Session.Db.SQLDbOperations.GetItem(String strSessionId, String strApplicationName, Int32 iTime, HttpContext context, Boolean lockRecord, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags) +1221
MemcachedProviders.Session.SessionStateProvider.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions) +1069
System.Web.SessionState.SessionStateModule.GetSessionStateItem() +178
System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state) +299
[HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown.]
System.Web.SessionState.SessionStateModule.EndAcquireState(IAsyncResult ar) +11513726
System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +107
Our application uses Enyim memcached and MemcachedProviders and runs in a load balanced environment.
The application does alot of managing of PDF reports and compiling of responses then generating a final report pdf. So we use streams quite a bit.
This problem only appears to affect our management application as we also expose a webservice and I never get the error when looking at the service definition and WSDL.
From looking at the session table in the DB I can see that they are being created but, many of them have null in the SessionItems field and the locked flag set to 1.
The data time stamps seem to correlate to the null buffer error occurances.
Is this a case of a buffer set incorrectly or maxing out?

Why am I getting "Invalid Internal state" reflection exception with Castle DynamicProxy?

We added DynamicProxy to our ASP.NET web app a couple of weeks ago. The code ran fine in dev and QA, but when we pushed to production, we got the following exception (top of stack trace only):
[ArgumentNullException: Invalid internal state.]
System.Reflection.Emit.TypeBuilder._InternalSetMethodIL(Int32 methodHandle, Boolean isInitLocals, Byte[] body, Byte[] LocalSig, Int32 sigLength, Int32 maxStackSize, Int32 numExceptions, __ExceptionInstance[] exceptions, Int32[] tokenFixups, Int32[] rvaFixups, Module module) +0
System.Reflection.Emit.TypeBuilder.InternalSetMethodIL(Int32 methodHandle, Boolean isInitLocals, Byte[] body, Byte[] LocalSig, Int32 sigLength, Int32 maxStackSize, Int32 numExceptions, __ExceptionInstance[] exceptions, Int32[] tokenFixups, Int32[] rvaFixups, Module module) +56
System.Reflection.Emit.TypeBuilder.CreateTypeNoLock() +1033
System.Reflection.Emit.TypeBuilder.CreateType() +99
Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.CreateType(TypeBuilder type) +72
Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.BuildType() +96
Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateType(String name, Type[] interfaces, INamingScope namingScope) +854
Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options) +834
Castle.DynamicProxy.DefaultProxyBuilder.CreateClassProxyType(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) +133
Castle.DynamicProxy.ProxyGenerator.CreateClassProxyType(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) +52
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors) +308
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors) +48
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors) +44
It worked fine when we first pushed the code, and an IIS reset fixed it, so I'm assuming it's thread related, but I couldn't find anything on the interwebs regarding best practices for thread-safety proxy generation. Suggestions?
UPDATE: After reading some more on the issue, especially here, I realized one potential issue -- namely that I had not overwritten Equals/GetHashCode for the implementation of IProxyGenerationHook I had written, which would prevent DynamicProxy from caching it's types. As I can find next to nothing on the exception I saw in general let alone related to DP, I'm gonna assume that it was the lack of caching of types caused by my omission that was the root cause of the problem, though I'd love a confirmation.
For the record, my object creation is pretty vanilla:
private T CreateProxy(MyArgs args)
{
var options = new ProxyGenerationOptions(new MyMethodSelector());
options.AddMixinInstance(new MyMixin());
return Generator.CreateClassProxy(
TargetType,
options,
new[] { new MyInterceptor(args) }) as T;
}
actually DynamicProxy is thread safe so it is quite unlikely it is concurrency related.
First of all, which version of DynamicProxy are you using?
Are you able to reproduce the issue in isolation, outside of IIS?
This issue was reported two years ago, but it was fixed. Please make sure you have the latest version.

Resources