Ninject + Web ApI 2: Error activating IFilterProvider using binding from IFilterProvider to DefaultFilterProvider - ninject

I originally had used some custom code I found to handle the dependency resolution in Web API and it worked fine. The issue I ran into was that I wanted to bind a filter to my controller scopes just like you can with MVC. For example, Kernel.BindFilter. The new Ninject.We.WebApi package has the binding extension I want but as soon as I add it to my project I get the following error. I'm not changing any of my code, just referencing a DLL.
Error activating IFilterProvider using binding from IFilterProvider to
DefaultFilterProvider A cyclical dependency was detected between the
constructors of two services.
Activation path: 3) Injection of dependency IFilterProvider into
parameter defaultFilterProviders of constructor of type
DefaultFilterProviders 2) Injection of dependency
DefaultFilterProviders into parameter filterProviders of constructor
of type DefaultFilterProvider 1) Request for IFilterProvider
Suggestions: 1) Ensure that you have not declared a dependency for
IFilterProvider on any implementations of the service. 2) Consider
combining the services into a single one to remove the cycle. 3) Use
property injection instead of constructor injection, and implement
IInitializable if you need initialization logic to be run after
property values have been injected.
at Ninject.Activation.Context.Resolve() at
Ninject.KernelBase.<>c__DisplayClass15.b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectListIterator2.MoveNext() at
System.Linq.Enumerable.<CastIterator>d__b11.MoveNext() at
System.Linq.Enumerable.d__142.MoveNext() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at
Ninject.Web.WebApi.Filter.DefaultFilterProvider.GetFilters(HttpConfiguration
configuration, HttpActionDescriptor actionDescriptor) at
System.Web.Http.Controllers.HttpActionDescriptor.b__0(IFilterProvider
fp) at
System.Linq.Enumerable.d__142.MoveNext() at
System.Linq.Buffer1..ctor(IEnumerable1 source) at
System.Linq.OrderedEnumerable1.d__0.MoveNext() at
System.Linq.Buffer1..ctor(IEnumerable1 source) at
System.Linq.Enumerable.d__a01.MoveNext() at
System.Web.Http.Controllers.HttpActionDescriptor.<RemoveDuplicates>d__3.MoveNext()
at System.Linq.Buffer1..ctor(IEnumerable1 source) at
System.Linq.Enumerable.<ReverseIterator>d__a01.MoveNext() at
System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at
System.Web.Http.Controllers.HttpActionDescriptor.InitializeFilterPipeline()
at System.Lazy1.CreateValue()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Lazy`1.get_Value() at
System.Web.Http.Controllers.HttpActionDescriptor.GetFilterPipeline()
at
System.Web.Http.Controllers.HttpActionDescriptor.GetFilterGrouping()
at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext
controllerContext, CancellationToken cancellationToken) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage
request, CancellationToken cancellationToken) at
System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()

In case anyone else is looking for a potential solution for cyclical dependency for the IFilterProvider, I had to explicitly bind DefaultFilterProviders like this
k.Bind<DefaultFilterProviders>().ToConstant(new DefaultFilterProviders(GlobalConfiguration.Configuration.Services.GetFilterProviders()));
or this
k.Bind<DefaultFilterProviders>().ToSelf().WithConstructorArgument(GlobalConfiguration.Configuration.Services.GetFilterProviders());
If anyone else knows a better way I would love to hear it.

I figured it out. I added the Nuget package Ninject.Web.WebApi.WebHost.

Related

NullPointerException when running CXF JAX-RS 2.0 client "target" method in Liberty Profile under a Thread

I have some JAX-RS 2.0 clients running ok in Liberty Profile 8.5.5.6. They are all working ok sequentially, but I want to execute some of them in a Thread so they run concurrently. When I try to get a "target" inside a FutureTask with:
WebTarget myResource = client.target(apiURLBase + ...);
I get NullPointerExcepton in this com.ibm.ws... class:
Caused by: java.lang.NullPointerException
at com.ibm.ws.jaxrs20.client.bus.LibertyJAXRSClientBusFactory.getClientScopeBus(LibertyJAXRSClientBusFactory.java:89)
at com.ibm.ws.jaxrs20.client.JAXRSClientImpl.target(JAXRSClientImpl.java:109)
at org.apache.cxf.jaxrs.client.spec.ClientImpl.target(ClientImpl.java:100)
at com.servengine.watson.naturallanguageclassifier.NaturalLanguageClassifierRESTClient.classify(NaturalLanguageClassifierRESTClient.java:161)
at com.servengine.watson.naturallanguageclassifier.NaturalLanguageClassifierRESTClient$Proxy$_$$_WeldClientProxy.classify(Unknown Source)
at com.skios.eliza.nlq.NaturalLanguageQueryFlowView$1.call(NaturalLanguageQueryFlowView.java:66)
at com.skios.eliza.nlq.NaturalLanguageQueryFlowView$1.call(NaturalLanguageQueryFlowView.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
CXF cannot be used out of "main" Thread? What am I missing?
Thanks for any help.
If you want to use the client API in a forked new thread, you need to make sure the new thread is a container managed one. In your case, you can enable concurrent-1.0 feature. Then use:
#Resource(name="java:comp/DefaultManagedExecutorServcie")
ManagedExecutorService executor;
Task task = new Task();
Future<String> result = executor.submit(task);
In Your Task class, you can do the same thing with what you done before: WebTarget myResource = client.target(apiURLBase + ...);

Access Denied Error for a method in web service

I have a webservice that works perfectly from localhost but when I hosted it on the testing server I get an error on one of the methods. I am using wsHttp Binding. everything else works fine on the client side except for this method. This is the error that I am getting
client error:
System.ServiceModel.Security.SecurityAccessDeniedException: Access is denied.
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Server error:
namespace.Service Error: 10001 : Error occurred in methodname().
System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.
at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly)
at System.Diagnostics.EventLog.SourceExists(String source, String machineName)
at System.Diagnostics.EventLog.VerifyAndCreateSource(String sourceName, String currentMachineName)
at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Byte[] data, Object[] values)
at System.Diagnostics.EventLog.WriteEvent(EventInstance instance, Object[] values)
at System.Diagnostics.EventLogTraceListener.TraceEvent(TraceEventCache eventCache, String source, TraceEventType severity, Int32 id, String format, Object[] args)
at System.Diagnostics.TraceSource.TraceEvent(TraceEventType eventType, Int32 id, String format, Object[] args)
at AutoWatch.Entity.WcfService.TrackingService.UpdateIncidentStatusHistory(Int64 incidentId, String status, String username, String comment, Boolean SuspectFaultyUnit) in C:\..servicename.cs:line 566
at AutoWatch.Entity.WcfService.TrackingService.GetNewIncidentMessage(String username) in C:\..servicename.cs:line 444
The Zone of the assembly that failed was:
MyComputer
I added in the error I am getting on the server.
Is it possible I am getting this error because the service cannot write to the event log?
Please help.
Ensure that account running your process where the service is hosted has access rights to the database. For example in case of IIS the account running the application pool where the service is hosted must have login to database server and it must have permissions to do all necessary operations in your database.
Edit:
The server stack trace looks quite straightforward. You have a problem with writing to Windows Event Log! It cannot find source you requested and it doesn't have permission to create it.
I got the same error when I tried to use the following statement in a Web Method of a WCF Service:
string myTypeName = typeof(ErrorHandlerBehavior).AssemblyQualifiedName;
where ErrorHandlerBehavior derives from BehaviorExtensionElement.
The line works well when I test the service on my localhost. On the web, the call of the containing method raises the Exception "Access is denied".
In this case, I guess that the cause was that my IP does not allow the creation of a BehaviourExtensionElement in a Partially Trusted environment (my service is in a shared hosting environment).
Finally, I succeded following the first mechanism described at https://learn.microsoft.com/en-us/dotnet/framework/wcf/extending/configuring-and-extending-the-runtime-with-behaviors about Service Behaviors:
"Using an attribute on the service class. When a ServiceHost is constructed, the ServiceHost implementation uses reflection to discover the set of attributes on the type of the service. If any of those attributes are implementations of IServiceBehavior, they are added to the behaviors collection on ServiceDescription. This allows those behaviors to participate in the construction of the service run time."
I just modified the derivation (no other modification required):
public class ErrorServiceBehavior : Attribute, IServiceBehavior
{ ... }
and use the class as Attribute of my service:
[ErrorServiceBehavior()]
public partial class MyService : IMyService
{...}
No other modification required. Check the original sample at How do I create a global exception handler for a WCF Services?.

Raven.Server.exe exception

I've never used RavenDb it looks interesting but I'm falling at the first hurdle.
I've downloaded, unzipped and I run C:\RavenDB\Server\Raven.Server.exe
and it flashes up and disappears.
I tried running from a dos prompt and I got this exception:
C:\RavenDB\Server>Raven.Server.exe
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the
requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.Assembly.GetTypes()
at System.ComponentModel.Composition.Hosting.AssemblyCatalog.get_InnerCatalog
()
at System.ComponentModel.Composition.Hosting.AssemblyCatalog.GetExports(Impor
tDefinition definition)
at System.ComponentModel.Composition.Hosting.AggregateCatalog.GetExports(Impo
rtDefinition definition)
at System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExports
Core(ImportDefinition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ExportProvider.GetExports(Import
Definition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.AggregateExportProvider.GetExpor
tsCore(ImportDefinition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ExportProvider.TryGetExportsCore
(ImportDefinition definition, AtomicComposition atomicComposition, IEnumerable`1
& exports)
at System.ComponentModel.Composition.Hosting.CompositionContainer.GetExportsC
ore(ImportDefinition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ExportProvider.GetExports(Import
Definition definition, AtomicComposition atomicComposition)
at System.ComponentModel.Composition.Hosting.ImportEngine.TryGetExports(Expor
tProvider provider, ComposablePart part, ImportDefinition definition, AtomicComp
osition atomicComposition)
at System.ComponentModel.Composition.Hosting.ImportEngine.TrySatisfyImportSub
set(PartManager partManager, IEnumerable`1 imports, AtomicComposition atomicComp
osition)
at System.ComponentModel.Composition.Hosting.ImportEngine.TrySatisfyImportsSt
ateMachine(PartManager partManager, ComposablePart part)
at System.ComponentModel.Composition.Hosting.ImportEngine.TrySatisfyImports(P
artManager partManager, ComposablePart part, Boolean shouldTrackImports)
at System.ComponentModel.Composition.Hosting.ImportEngine.SatisfyImportsOnce(
ComposablePart part)
at System.ComponentModel.Composition.AttributedModelServices.SatisfyImportsOn
ce(ICompositionService compositionService, Object attributedPart)
at Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configura
tion)
at Raven.Server.RavenDbServer..ctor(RavenConfiguration settings)
at Raven.Server.Program.RunServer(RavenConfiguration ravenConfiguration)
at Raven.Server.Program.RunInDebugMode(Nullable`1 anonymousUserAccessMode, Ra
venConfiguration ravenConfiguration)
at Raven.Server.Program.InteractiveRun(String[] args)
at Raven.Server.Program.Main(String[] args)
- - - -
System.TypeLoadException: Method 'WriteJson' in type 'JsonToJsonConverter' from
assembly 'Raven.Http, Version=1.0.0.0, Culture=neutral, PublicKeyToken=37f41c7f9
9471593' does not have an implementation.
C:\RavenDB\Server>
I'm a total nub when it comes to this software.
Any ideas ?
Thanks
It seems to be an issue with version 206 I've gone back to 193 and it works fine.

Ninject Intermittent exception thrown related to OnePerRequestModule

I just upgraded an existing implementation of Ninject from 1.5 to 2.0. I'm now seeing an intermittent exception getting thrown when many requests are happening in a short period of time.
Here's the exception that is being thrown.
Type: System.ArgumentException
Message: An item with the same key has already been added.
Source: Ninject
Stack Trace: at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at Ninject.Components.ComponentContainer.CreateNewInstance(Type component, Type implementation)
at Ninject.Components.ComponentContainer.ResolveInstance(Type component, Type implementation)
at Ninject.Components.ComponentContainer.Get(Type component)
at Ninject.Components.ComponentContainer.<CreateNewInstance>b__6(ParameterInfo parameter)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Components.ComponentContainer.CreateNewInstance(Type component, Type implementation)
at Ninject.Components.ComponentContainer.ResolveInstance(Type component, Type implementation)
at Ninject.Components.ComponentContainer.Get(Type component)
at Ninject.Components.ComponentContainer.GetT
at Ninject.KernelBase.CreateContext(IRequest request, IBinding binding)
at Ninject.KernelBase.<>c__DisplayClassa.<Resolve>b__6(IBinding binding)
at System.Linq.Enumerable.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__aa`1.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters)
at NameOfConsumingSite.Application_BeginRequest(Object sender, EventArgs e)...
The exception does not get thrown if I remove the OnePerRequestModule item from httpModules in web.config, but that is adding a ton of overhead.
I thank anyone in advance if they can help!
There was a multithreading problem. Try to use the 2.2 RC1 found at https://github.com/ninject . Please tell me if this problem still occurs with this version to make sure we have no further issue we have to fix before release.

NHibernate.MappingException - Trouble Shooting Checklist (no persister for)

Here's a starter list:
if hbm is hand generated, is it an embedded resource?
if using FNH, does it pass a PerssistenceSpecification test?
if not using FNH, can you save and then load the persisted class?
use Ayende's "sanity checks"
I'm sure many of you have gotten this one at one point or another. But have you ever gotten it when you knew your mapping was set up correctly?
I started getting this exception after I started using a new repository design, but only in one scenario! PersistenceSpecification tests pass, as do all repository methods (using SQLite).
The scenario that leads to the exception is when legacy projects from a different db are converted to green field system. The legacy system is from a different database and has it's own session factory, which should be irrelevant because the error comes after previously unconverted Projects are retrieved and in memory.
As the routine tries to save these unconverted Projects into the new database, the exception is thrown, full stack trace below.
Any ideas on how to build up the trouble shooting check list and solves this problem?
Cheers,
Berryl
=== the Exception trace =====
failed: NHibernate.MappingException : No persister for: Smack.ConstructionAdmin.Domain.Model.Projects.Project
at NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
at NHibernate.Impl.SessionImpl.GetEntityPersister(String entityName, Object obj)
at NHibernate.Engine.ForeignKeys.IsTransient(String entityName, Object entity, Nullable`1 assumed, ISessionImplementor session)
at NHibernate.Event.Default.AbstractSaveEventListener.GetEntityState(Object entity, String entityName, EntityEntry entry, ISessionImplementor source)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.FireSaveOrUpdate(SaveOrUpdateEvent event)
at NHibernate.Impl.SessionImpl.SaveOrUpdate(Object obj)
NHibernate\Repository\FabioNHibRepository.cs(46,0): at Smack.Core.Data.NHibernate.Repository.FabioNHibRepository`1.Add(T item)
LegacyConversion\LegacyBatchUpdater.cs(20,0): at Smack.ConstructionAdmin.Data.LegacyConversion.LegacyBatchUpdater.ConvertOpenLegacyProjects(ILegacyProjectDao legacyProjectDao, IProjectRepository greenProjectRepository)
Data\Brownfield\ProjectBatchUpdate_SQLiteTests.cs(19,0): at Smack.ConstructionAdmin.Tests.Data.Brownfield.ProjectBatchUpdate_SQLiteTests.Test()
The problem here turned out to be that I was inadvertently binding the same session context to both the legacy and greenfield db session factories, first to the greenfield and then the legacy.