NServiceBus System.ArgumentNullException - c#

I'm new to NServiceBus (and a green developer) and I'm getting destroyed by this exception (in the NSB console, before calling the handler):
2014-02-26 14:27:10,269 [8] ERROR NServiceBus.Unicast.Transport.TransportReceiver [(null)] <(null)> -
Failed to deserialize message with ID: b0e459fa-0ada-431c-bbee-a2de00ee2a29
System.Runtime.Serialization.SerializationException: An error occurred while attempting to extract logical messages
from transport message NServiceBus.TransportMessage ---> System.ArgumentNullException: Value cannot be null.
Parameter name: path
at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionA
ccess access, AccessControlActions control, String[] pathListOrig, Boolean check
ForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.IO.FileSystemInfo.set_Attributes(FileAttributes value)
at SetIsReadOnly(Object , Object )
at NServiceBus.Serializers.XML.XmlMessageSerializer.GetObjectOfTypeFromNode(T
ype t, XmlNode node) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Core
\Serializers\XML\XmlMessageSerializer.cs:line 492
at NServiceBus.Serializers.XML.XmlMessageSerializer.GetPropertyValue(Type typ
e, XmlNode n) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Core\Serial
izers\XML\XmlMessageSerializer.cs:line 828
at NServiceBus.Serializers.XML.XmlMessageSerializer.GetObjectOfTypeFromNode(T
ype t, XmlNode node) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBus.Core
\Serializers\XML\XmlMessageSerializer.cs:line 487
at NServiceBus.Serializers.XML.XmlMessageSerializer.Process(XmlNode node, Obj
ect parent, Type nodeType) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceBu
s.Core\Serializers\XML\XmlMessageSerializer.cs:line 379
at NServiceBus.Serializers.XML.XmlMessageSerializer.Deserialize(Stream stream
, IList`1 messageTypesToDeserialize) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\
NServiceBus.Core\Serializers\XML\XmlMessageSerializer.cs:line 359
at NServiceBus.Unicast.Messages.ExtractLogicalMessagesBehavior.Extract(Transp
ortMessage physicalMessage) in c:\BuildAgent\work\31f8c64a6e8a2d7c\src\NServiceB
us.Core\Unicast\Messages\ExtractLogicalMessagesBehavior.cs:line 74
at NServiceBus.Unicast.Messages.ExtractLogicalMessagesBehavior.Invoke(Receive
PhysicalMessageContext context, Action next) in c:\BuildAgent\work\31f8c64a6e8a2
d7c\src\NServiceBus.Core\Unicast\Messages\ExtractLogicalMessagesBehavior.cs:line
52
--- End of inner exception stack trace ---
I got the MVC Example project working from the free chapters, but I couldn't get the pubsub example to work because 'Host doesn't support hosting of multiple endpoints.'
I'm working in 3 projects in my broken solution, just trying to get a simple 1-node pub and 1-node sub going:
Core (NServiceBus.Interfaces 4.4.1 from NuGet, contains Events folder with IFileUploadedEvent.cs)
FileWatcherService (NServiceBus.Host 4.4.1 from NuGet)
FileMoverService (NServiceBus.Host 4.4.1 from NuGet)
Core\Events\IFileUploadedEvent.cs:
using NServiceBus;
using ...
namespace Core.Events
{ public interface IFileUploadedEvent : IEvent
{ Guid EventId { get; set; }
string Client { get; set; }
FileInfo FileName { get; set; }
}
}
FileWatcherService has default app.config, no mappings.
FileWatcherService.EndpointConfig.cs:
namespace FileWatcherService
{ using NServiceBus;
public class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher {}
}
FileWatcherService.FileWatcher.cs:
using NServiceBus;
using Core.Events;
using ...
namespace FileWatcherService
{ public class FileWatcher : IWantToRunWhenBusStartsAndStops
{ public IBus Bus { get; set; }
public void Activate()
{ ... }
...Stalker, calls PublishFileUploaded
public void PublishFileUploaded(FileInfo fileName, string clientName)
{ Bus.Publish<IFileUploadedEvent>(evt =>
{ evt.EventId = Guid.NewGuid();
evt.Client = clientName;
evt.FileName = fileName;
});
} } }
the FileMoverService.App.config contains:
<UnicastBusConfig>
<MessageEndpointMappings>
<add Messages="Core" Endpoint="FileWatcherService" />
</MessageEndpointMappings>
</UnicastBusConfig>
In the NSB windows, I see
FileMover: Subscribing to Core.Events.IFileUploadedEvent
FileWatcher: Subscribing FileMoverService#ccc to message type Core.Events.IFileUploadedEvent
The FileMover class implements IHandleMessages, but the code never reaches that because NServiceBus throws the first error.
I tried running Init() in the EndpointConfig, but I still get the same error.
Help me Please! What am I doing wrong?

If you want to move files or other blobs using NServiceBus, look at using our "data bus" capabilities described here:
http://docs.particular.net/NServiceBus/attachments-databus-sample

Turns out you can't Deserialize a FileInfo object. So I'll have to approach the problem completely differently.

Related

Dependency injection fails to register class during startup of asp.net core web application

I am getting the following exception when program.cs calls CreateHostBuilder.Build():
System.InvalidOperationException : Unable to resolve service for type
'web_application.Models.postStatus' while attempting to activate
'web_application.Services.Updates.PostingStatusUpdater'.
Full error below, but it is being thrown at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)
I searched for ways to turn on verbose logging for that dependency injection dll or ways to debug the dependency injection framework and couldn't find answers to that. If anyone knows how to enable verbose logging at this stage of the program, please free to help too!
This is how the service is being registered in Startup.cs:
using System;
...
namespace web_application
{
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IUpdateService<postStatus>, PostingStatusUpdater>();
...
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
...
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
}
postStatus is an enum, and my first thought was maybe DI registration was failing because of something related to it.
The actual class being registered derives from a base class, which implements the generic interface.
Generic Interface:
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using web_application.Models;
namespace web_application.Services.Updates{
public interface IUpdateService<T>{
bool runPreUpdateChecks(out IList<string> allFailedChecks);
void runPostCheckHooks();
bool tryPerformUpdate(T intialState, T FinalState, Action runUpdate, out IList<string> failureReasons);
Task<(bool success, IList<string> updateFailureReasons)> tryPerformUpdateAsync(T intialState, T FinalState, Task runUpdateAsync);
}
}
The base class:
using System;
using System.Threading.Tasks;
using web_application.Models;
using System.Collections.Generic;
namespace web_application.Services.Updates{
public abstract class BaseStatusUpdater<T> : IUpdateService<T>
{
public T initStatus {get; private set;}
public T finalStatus {get; private set;}
// TODO: Add update check attributes
public List<PreUpdateCheck<T>> preUpdateChecks = new List<PreUpdateCheck<T>>();
public IList<Action> postUpdateHooks = new List<Action>();
public BaseStatusUpdater(T initStatus, T finalStatus){
this.initStatus = initStatus;
this.finalStatus = finalStatus;
}
/// <summary>
/// Runs preupdate checks and returns every check that failed (no short circuit)
/// Returns a list of failed checks on failure.
/// </summary>
public bool runPreUpdateChecks(out IList<string> allFailedChecks){
allFailedChecks = new List<string>(preUpdateChecks.Count);
var allChecksPassed = true;
foreach(var check in preUpdateChecks){
if(!check.run()){
allFailedChecks.Add(check.failureReason);
allChecksPassed = false;
}
}
return allChecksPassed;
}
/// <summary>
/// Run only actions that are one-off, and don't cascade into other
/// actions that may require custom error handling.
/// </summary>
public void runPostCheckHooks(){
foreach(var hook in postUpdateHooks){
hook();
}
}
public bool tryPerformUpdate(T intialState, T FinalState, Action runUpdate, out IList<string> updateFailureReasons){
if(!runPreUpdateChecks(out updateFailureReasons)){
return false;
}
runUpdate();
runPostCheckHooks();
return true;
}
// https://stackoverflow.com/questions/18716928/how-to-write-an-async-method-with-out-parameter
public async Task<(bool success, IList<string> updateFailureReasons)>
tryPerformUpdateAsync(T intialState, T FinalState, Task runUpdateAsync)
{
IList<string> updateFailureReasons = new List<string>(preUpdateChecks.Count);
if(!runPreUpdateChecks(out updateFailureReasons)){
return (false,updateFailureReasons);
}
await runUpdateAsync;
runPostCheckHooks();
return (true,updateFailureReasons);
}
}
}
The class being registered for IUpdateService
using System;
using web_application.Models;
using System.Collections.Generic;
namespace web_application.Services.Updates{
// Make this a singleton on injection to get this so that we don't keep constructing the things
// in the constructor every time its called? Or store the static logic somewhere else
using vpStatus = postStatus;
public class PostingStatusUpdater : BaseStatusUpdater<postStatus>
{
public PostingStatusUpdater(vpStatus vpsInitial, vpStatus vpsFinal)
: base(vpsInitial,vpsFinal)
{
Func<(bool,string)> isMovePermitted = () => {
if(UpdateLogic.permittedStatusChanges
.Contains(new UpdateLogic.statusPair(base.initStatus, vpsFinal))){
return (true,string.Empty);
}
return (false, "Cannot mark post as \"" + vpsFinal.ToString() + " since it is currently marked as "
+ "\"" + vpsInitial.ToString() + "\"");
};
var check1 = new PreUpdateCheck<vpStatus>(isMovePermitted);
base.preUpdateChecks.Add(check1);
}
}
}
There is not compile time error or warning about this, and I've been digging around to make sure this hasn't been addressed before but I can't find a question that addresses this exactly, so I thought I'd post this for help.
Thanks.
Full error:
Exception thrown: 'System.AggregateException' in
Microsoft.Extensions.DependencyInjection.dll: 'Some services are not
able to be constructed' Inner exceptions found, see $exception in variables window for more details.
Innermost exception
System.InvalidOperationException : Unable to resolve service for type
'web_application.Models.postStatus' while attempting to activate
'web_application.Services.Updates.PostingStatusUpdater'.
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type
serviceType, Type implementationType, CallSiteChain callSiteChain,
ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache
lifetime, Type serviceType, Type implementationType, CallSiteChain
callSiteChain) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor
descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.GetCallSite(ServiceDescriptor
serviceDescriptor, CallSiteChain callSiteChain) at
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.ValidateService(ServiceDescriptor
descriptor)

Specflow - TearDown failed for test fixture - System.ArgumentNullException : Value cannot be null. (Parameter 'key')

I'm working with test automation using Specflow and Selenium but by the time I try to execute my test, I face these error messages:
My question is not what is a NullReferenceException, but what (and where) is this Parameter 'key' pointed as the cause of the exception.
TearDown failed for test fixture MyProject.Features.MyFeature
System.ArgumentNullException : Value cannot be null. (Parameter 'key')
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
And:
Error Message:
OneTimeSetUp: System.ArgumentNullException : Value cannot be null. (Parameter 'key')
This is my scenario:
Scenario: Accessing the screen for the first time
Given I accessed the screen for the first time
Then the result grid should only show the phrase "Lorem ipsum"
This is my StepDefinition.cs file:
[Binding]
public class StepDefinition
{
PageObject pageObject = new PageObject();
[Given(#"I accessed the screen for the first time")]
public void GivenIAccessedTheScreenForTheFirstTime()
{
pageObject.NavigateToScreen();
}
[Then(#"the result grid should only show the phrase (.*)")]
public void ThenTheResultGridShouldOnlyShowThePhrase(string phrase)
{
Assert.True(pageObject.isPhraseDisplayed(phrase));
}
}
This is my PageObject.cs file:
public PageObject() : base(){ } //I use a BasePageObject.cs file also
public void NavigateToScreen()
{
driver.Navigate().GoToUrl(_urlHere_);
}
public bool isPhraseDisplayed(string phrase)
{
wait.Until(u => u.FindElement(_byIdOfWebElementHere_).Displayed);
IWebElement element = driver.FindElement(_byIdOfWebElementHere_);
return element.Displayed;
}
And this is the BasePageObject.cs file, which implements IDisposable interface:
protected IWebDriver driver { get; set; }
protected WebDriverWait wait { get; set; }
public BasePageObject()
{
driver = new ChromeDriver();
}
[AfterScenario]
public void Dispose()
{
driver.Close();
driver.Quit();
driver.Dispose();
}
}
Exception Stack trace:
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
TearDown failed for test fixture MyProject.Features.MyFeature
System.ArgumentNullException : Value cannot be null. (Parameter 'key')
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.FindAttributeConstructorArg(ParameterInfo parameterInfo, Dictionary`2 namedAttributeValues)
at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.<>c__DisplayClass8_0.<CreateAttribute>b__7(ParameterInfo p)
at System.Linq.Enumerable.SelectArrayIterator`2.ToArray()
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.CreateAttribute(Attribute attribute)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.ToArray()
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.GetAttributes(IEnumerable`1 customAttributes)
at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.CreateBindingSourceMethod(MethodInfo methodDefinition)
at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.BuildBindingsFromType(Type type)
at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.BuildBindingsFromAssembly(Assembly assembly)
at TechTalk.SpecFlow.TestRunnerManager.BuildBindingRegistry(IEnumerable`1 bindingAssemblies)
at TechTalk.SpecFlow.TestRunnerManager.InitializeBindingRegistry(ITestRunner testRunner)
at TechTalk.SpecFlow.TestRunnerManager.CreateTestRunner(Int32 threadId)
at TechTalk.SpecFlow.TestRunnerManager.GetTestRunnerWithoutExceptionHandling(Int32 threadId)
at TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(Int32 threadId)
at TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(Assembly testAssembly, Nullable`1 managedThreadId)
at MyProject.Features.MyFeature.FeatureSetup()
--TearDown
at MyProject.Features.MyFeature.FeatureTearDown()
X AcessandoATelaDeConsultaPelaPrimeiraVez [< 1ms]
Error Message:
OneTimeSetUp: System.ArgumentNullException : Value cannot be null. (Parameter 'key')
Results File: C:\Users\FAMG\AppData\Local\Temp\test-explorer-GvcYR7\0.trx
Total tests: 1
Failed: 1
Total time: 3,7733 Seconds
Things I think are important to point:
I am using VSCode, not Visual Studio.
The test runner I have installed on my project is NUnit.
I just ran to this exact thing.
The source of the error comes from the reflection on type: System.Runtime.CompilerServices.NullableContextAttribute.
Looks like some kind of expected constructor MethodInfo Name is NULL.
Long story short: .NET Core 2.1, 2.2 work. SpecFlow (3.0.225) doesn't seem to work with .Net Core 3.0.
Good News: Turn on include pre-release for Nuget and get the beta SpecFlow and associated packages (Nunit and friends) updating to (3.1.52-beta) the latest works.
SpecFlow 3.1 main release will probably support .Net Core 3.0.

KeyNotFoundException in GraphQL .net Entity Framework

I am using below with two DbContexts:
https://github.com/SimonCropp/GraphQL.EntityFramework
I get this error:
GraphQL.ExecutionError: Error trying to resolve project.
System.Collections.Generic.KeyNotFoundException: The given key 'Models.Master.Project' was not present in the dictionary.
at System.Collections.Generic.Dictionary2.get_Item(TKey key)
at IncludeAppender.AddIncludes[TItem,TSource](IQueryable1 query, ResolveFieldContext1 context) in C:\\projects\\graphql-entityframework\\src\\GraphQL.EntityFramework\\IncludeAppender.cs:line 20
at
GraphQL.EntityFramework.EfGraphQLService.<>c__DisplayClass21_02.<b__0>d.MoveNext() in C:\projects\graphql-entityframework\src\GraphQL.EntityFramework\EfGraphQLService_Queryable.cs:line 80
End of stack trace from previous location where exception
was thrown
at GraphQL.Instrumentation.MiddlewareResolver.Resolve(ResolveFieldContext context)
at GraphQL.Execution.ExecutionStrategy.ExecuteNodeAsync(ExecutionContext context, ExecutionNode node)
End of inner exception stack trace
When I try to add two models of two DbContexts as following in startup.cs (in following, if I remove second line, then it works perfectly. But that I need for my second DbContext).
EfGraphQLConventions.RegisterInContainer(services, ProjectDataContextBuilder.ProjectModel); //This is creating issue as of now. wasn't issue when checked with my and your.
EfGraphQLConventions.RegisterInContainer(services, MasterDataContextBuilder.MasterModel);
DataContextBuilder classes are as follows:
static class MasterDataContextBuilder
{
static MasterDataContextBuilder()
{
using (var masterDataContext = InMemoryContextBuilder.Build<ecdiscoMasterContext>())
{
MasterModel = masterDataContext.Model;
}
}
public static IModel MasterModel;
}
static class ProjectDataContextBuilder
{
static ProjectDataContextBuilder()
{
using (var projectDataContext = InMemoryContextBuilder.Build<ecdiscoProjectContext>())
{
ProjectModel = projectDataContext.Model;
}
}
public static IModel ProjectModel;
}
Note: In error. Project is model of MasterDbContext.
Another DbContext is Project. which is separate per tenant. So that is ProjectDbContext (which doesn't have Project model).
this is fixed in version 6 https://github.com/SimonCropp/GraphQL.EntityFramework/blob/master/doco/configuration.md#multiple-dbcontexts
Some extra text to get over the silly 30 char min

Service 'Abp.Quartz.IQuartzScheduleJobManager' which was not registered

I have downloaded .NET Core + Vue template for ASP.NET Boilerplate (v3.7.0).
I added:
code by referencing http://aspnetboilerplate.com/Pages/Documents/Quartz-Integration.
NuGet Abp.Quartz in xxx.Application project.
MyAbpQuartzModule.cs, MyLogJob.cs in xxx.Application project:
[DependsOn(typeof(AbpAutoMapperModule), typeof(AbpQuartzModule))]
public class MyAbpQuartzModule : AbpModule
{
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
}
}
MyAbpQuartzController.cs in xxx.Web.Host project:
public class MyAbpQuartzController : AbpController
{
private readonly IQuartzScheduleJobManager _jobManager;
public MyAbpQuartzController(IQuartzScheduleJobManager jobManager)
{
_jobManager = jobManager;
}
public async Task<ActionResult> ScheduleJobWithTask()
{
await _jobManager.ScheduleAsync<MyLogJob>(
job =>
{
job.WithIdentity("MyLogJobIdentity", "MyGroup")
.WithDescription("A job to simply write logs.");
},
trigger =>
{
trigger.StartNow()
.WithSimpleSchedule(schedule =>
{
schedule.RepeatForever()
.WithIntervalInSeconds(5)
.Build();
});
});
return Content("OK, scheduled!");
}
public ContentResult TestMyAbpQuartz(string message = "")
{
return Content("OK, scheduled!");
}
}
I debugged the xxx.Web.Host project, but it didn't work.
The http://localhost:21021/MyAbpQuartz/TestMyAbpQuartz page returned:
"This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500"
I think that QuartzScheduleJobManager didn't register successfully.
So, what should I do?
Part of error message in Web.Host/App_Data/log.txt:
ERROR 2018-06-08 19:19:04,161 [5 ] Mvc.ExceptionHandling.AbpExceptionFilter - Can't create component 'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' as it has dependencies to be satisfied.
'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' is waiting for the following dependencies:
- Service 'Abp.Quartz.IQuartzScheduleJobManager' which was not registered.
Castle.MicroKernel.Handlers.HandlerException: Can't create component 'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' as it has dependencies to be satisfied.
'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' is waiting for the following dependencies:
- Service 'Abp.Quartz.IQuartzScheduleJobManager' which was not registered.
at Castle.MicroKernel.Handlers.DefaultHandler.AssertNotWaitingForDependency()
at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)
at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)
at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments, IReleasePolicy policy)
at Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy)
at Castle.Windsor.MsDependencyInjection.ScopedWindsorServiceProvider.GetServiceInternal(Type serviceType, Boolean isOptional) in D:\Github\castle-windsor-ms-adapter\src\Castle.Windsor.MsDependencyInjection\ScopedWindsorServiceProvider.cs:line 55
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextExceptionFilterAsync>d__23.MoveNext()
INFO 2018-06-08 19:19:04,967 [5 ] ore.Mvc.Internal.ControllerActionInvoker - Executed action MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController.TestMyAbpQuartz (MyNetCoreWithVueProject.Web.Host) in 833.6801ms
ERROR 2018-06-08 19:19:05,059 [5 ] Microsoft.AspNetCore.Server.Kestrel - Connection id "0HLED66DNH26L", Request id "0HLED66DNH26L:00000004": An unhandled exception was thrown by the application.
Castle.MicroKernel.Handlers.HandlerException: Can't create component 'MyNetCoreWithVueProject.Web.Host.Controllers.MyAbpQuartzController' as it has dependencies to be satisfied.
IQuartzScheduleJobManager should be registered by AbpQuartzModule.
I see that you already have [DependsOn(typeof(AbpQuartzModule))] on MyAbpQuartzModule.
Add [DependsOn(typeof(MyAbpQuartzModule))] to *WebHostModule:
[DependsOn(
typeof(AbpProjectNameWebCoreModule),
typeof(MyAbpQuartzModule))]
public class AbpProjectNameWebHostModule : AbpModule
If you want to register a specific class that does not fit into the conventional registration rules. ASP.NET Boilerplate provides the ITransientDependency, the IPerWebRequestDependency and the ISingletonDependency interfaces as a shortcut.
public interface IQuartzScheduleJobManager
{
//...
}
public class QuartzScheduleJobManager: IQuartzScheduleJobManager, ITransientDependency
{
//...
}

Unable to find assembly FluentNHibernate when mapping Component while running Fitnesse test

I have run into a very weird issue. I have several working Fitnesse tests which insert data in a database, then test my full MVC application stack.
When I try to add 2 Component property mappings to my entity map, I get an error saying "Unable to find assembly 'FluentNHibernate ...' which seems somewhat cryptic.
All of this is being run through Fitnesse, so this could be an issue with how Fitnesse loads dependencies... I have no idea of knowing for sure though. The only thing I know is that this code runs fine until I add the 2 "Component" mappings. On top of that, those mappings run fine when this code is run through the normal web application (so I know the "Component" mapping and SessionFactory class works outside of Tests project).
Does anyone have any ideas why I would get the error message I'm getting? Please let me know if there is any other code I need to post. Any help is greatly appreciated!
DLL Versions:
NHibernate - 3.3.1.4000
FluentNHibernate - 1.3.0.733
Fitnesse - v20111026
fitSharp - 2.2.4498.25493
Here is my entity:
// namespace Reporting.Domain
public class Holdings
{
public virtual int HoldingsId { get; set; }
public virtual DateTime AsOfDate { get; set; }
public virtual string Portfolio { get; set; }
// need to add these next 2 properties!
public virtual Balances PriorPeriod { get; set; }
public virtual Balances CurrentPeriod { get; set; }
}
my mapping file:
// namespace Reporting.Infrastructure
public sealed class HoldingsMap : ClassMap<Holdings>
{
public HoldingsMap()
{
Id(x => x.HoldingsId).GeneratedBy.Identity();
Map(x => x.AsOfDate).Not.Nullable();
Map(x => x.Portfolio).Not.Nullable();
// adding these lines eventually leads to the error
Component(x=> x.PriorPeriod).ColumnPrefix("Prior");
Component(x=> x.CurrentPeriod).ColumnPrefix("Current");
}
}
my SessionFactory (the error happens when BuildSessionFactory is called):
// namespace Reporting.Infrastructure
public class SessionFactory
{
public ISessionFactory CreateSession(Action<Configuration> configurationFunction)
{
return CreateConfiguration().ExposeConfiguration(c => {}).BuildSessionFactory();
}
private FluentConfiguration CreateConfiguration()
{
var connectionString = "...";
var msSqlConfiguration = MsSqlConfiguration.MsSql2008.ConnectionString(connectionString);
var database = Fluently.Configure().Database(msSqlConfiguration);
return database.Mappings(m => m.FluentMappings.AddFromAssemblyOf<SessionFactory>().Conventions.Add(ForeignKey.EndsWith("Id")));
}
}
I get this stack trace:
__EXCEPTION__:System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
---> FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
---> System.Runtime.Serialization.SerializationException: Unable to find assembly 'FluentNHibernate, Version=1.3.0.733, Culture=neutral, PublicKeyToken=8aa435e3cb308880'.
at System.Runtime.Serialization.Formatters.Binary.BinaryAssemblyInfo.GetAssembly()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.GetType(BinaryAssemblyInfo assemblyInfo, String name)
at System.Runtime.Serialization.Formatters.Binary.ObjectMap..ctor(String objectName, String[] memberNames, BinaryTypeEnum[] binaryTypeEnumA, Object[] typeInformationA, Int32[] memberAssemIds, ObjectReader objectReader, Int32 objectId, BinaryAssemblyInfo assemblyInfo, SizedArray assemIdToAssemblyTable)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.ReadObjectWithMapTyped(BinaryObjectWithMapTyped record)
at System.Runtime.Serialization.Formatters.Binary.__BinaryParser.Run()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, IMethodCallMessage methodCallMessage)
at FluentNHibernate.Utils.Extensions.DeepClone[T](T obj)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at FluentNHibernate.Visitors.ComponentReferenceResolutionVisitor.ProcessComponent(ReferenceComponentMapping mapping)
at FluentNHibernate.MappingModel.ClassBased.ReferenceComponentMapping.AcceptVisitor(IMappingModelVisitor visitor)
at FluentNHibernate.MappingModel.MappedMembers.AcceptVisitor(IMappingModelVisitor visitor)
at FluentNHibernate.MappingModel.ClassBased.ClassMappingBase.AcceptVisitor(IMappingModelVisitor visitor)
at FluentNHibernate.MappingModel.HibernateMapping.AcceptVisitor(IMappingModelVisitor visitor)
at FluentNHibernate.Utils.CollectionExtensions.Each[T](IEnumerable`1 enumerable, Action`1 each)
at FluentNHibernate.PersistenceModel.ApplyVisitors(IEnumerable`1 mappings)
at FluentNHibernate.PersistenceModel.BuildMappings()
at FluentNHibernate.PersistenceModel.Configure(Configuration cfg)
at FluentNHibernate.Cfg.MappingConfiguration.Apply(Configuration cfg)
at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
--- End of inner exception stack trace ---
at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()
--- End of inner exception stack trace ---
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()
at Reporting.Infrastructure.SessionFactory.CreateSession() in Reporting.Infrastructure\SessionFactory.cs:line 32
at Reporting.FitnesseTests.Database.Setup() in Reporting.FitnesseTests\Database.cs:line 23
--- End of inner exception stack trace ---
at fitSharp.Machine.Model.TypedValue.ThrowExceptionIfNotValid()
at fitSharp.Slim.Operators.ExecuteCall.ExecuteOperation(Tree`1 parameters)
at fitSharp.Slim.Operators.InvokeInstructionBase.Invoke(TypedValue instance, MemberName memberName, Tree`1 parameters)
FWIW, this is how I use the session factory from my Fitnesse Tests project:
// namespace Reporting.FitnesseTests
public class Database
{
public static ISession Session { get; private set; }
public static void Setup()
{
Session = new SessionFactory().CreateSession().OpenSession();
}
}
and my Fitnesse Classpath is:
!path ..\Reporting.FitnesseTests\bin\Debug\Reporting.FitnesseTests.dll
Try putting the DLLs that the test is looking for in the same folder as the fitsharp Runner.exe. One problem that I ran into is that .NET run-time dependencies that are defined in app.config are resolved from the directory in which the process is executed from which in this case is probably the directory where fitsharp resides. There is a apparently a way to use the fitsharp suite configuration file to change this behavior but I haven't been able to get it working successfully (http://fitsharp.github.com/FitSharp/SuiteConfigurationFile.html).

Categories