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

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).

Related

System.InvalidProgramException: Common Language Runtime detected an invalid program

I have a .net 6 solution that has two Service Fabric stateless services. The first one "ServiceA" is a web service that receives incoming API requests and then it creates a proxy to second one "ServiceB" that is deployed in the same cluster. The problem is, the when the proxy is created and I try to access the method that ServiceB implements, I get this exception:
"message": "System.AggregateException: One or more errors occurred. (Common Language Runtime detected an invalid program.)
---> System.InvalidProgramException: Common Language Runtime detected an invalid program.
at ServiceB.Contracts.Infrastructure.IServiceB_.service.disp.IServiceBMethodDispatcher.OnDispatchAsync(Int32 , Object , IServiceRemotingRequestMessageBody , IServiceRemotingMessageBodyFactory , CancellationToken )
at Microsoft.ServiceFabric.Services.Remoting.V2.Builder.MethodDispatcherBase.DispatchAsync(Object objectImplementation, Int32 methodId, IServiceRemotingRequestMessageBody requestBody, IServiceRemotingMessageBodyFactory remotingMessageBodyFactory, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.V2.Runtime.ServiceRemotingMessageDispatcher.OnDispatch(IServiceRemotingRequestMessageHeader requestMessageHeaders, IServiceRemotingRequestMessageBody requestBody, CancellationToken cancellationToken)
--- End of stack trace from previous location ---
at Microsoft.ServiceFabric.Services.Remoting.V2.Runtime.ServiceRemotingMessageDispatcher.OnDispatch(IServiceRemotingRequestMessageHeader requestMessageHeaders, IServiceRemotingRequestMessageBody requestBody, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.V2.Runtime.ServiceRemotingMessageDispatcher.<>c__DisplayClass8_1.<HandleRequestResponseAsync>
b__0(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.Runtime.ServiceRemotingCancellationHelper.DispatchRequest[T](Int32 interfaceId, Int32 methodId, String callContext, Func`2 dispatchFunc)
at Microsoft.ServiceFabric.Services.Remoting.V2.Runtime.ServiceRemotingMessageDispatcher.HandleRequestResponseAsync(IServiceRemotingRequestContext requestContext, IServiceRemotingRequestMessage requestMessage)\r\n at Microsoft.ServiceFabric.Services.Remoting.V2.FabricTransport.Runtime.FabricTransportMessageHandler.RequestResponseAsync(FabricTransportRequestContext requestContext, FabricTransportMessage fabricTransportMessage)
--- End of inner exception stack trace ---
at Microsoft.ServiceFabric.Services.Communication.Client.ServicePartitionClient`1.InvokeWithRetryAsync[TResult](Func`2 func, CancellationToken cancellationToken, Type[] doNotRetryExceptionTypes)\r\n at Microsoft.ServiceFabric.Services.Remoting.V2.Client.ServiceRemotingPartitionClient.InvokeAsync(IServiceRemotingRequestMessage remotingRequestMessage, String methodName, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.Builder.ProxyBase.InvokeAsyncV2(Int32 interfaceId, Int32 methodId, String methodName, IServiceRemotingRequestMessageBody requestMsgBodyValue, CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Remoting.Builder.ProxyBase.ContinueWithResultV2[TRetval](Int32 interfaceId, Int32 methodId, Task`1 task)\r\n at MyApp.WebService.Proxies.ServiceBProxy.IsSomeStuffInProgressAsync() in C:\\dev\\repos\my-sf-app\\MyApp.WebService\\Proxies\\ServiceBProxy.cs:line 21
at MyApp.WebService.Controllers.FileController.CheckSomeStuffState() in C:\\dev\\repos\my-sf-app\\MyApp.WebService\\Controllers\\FileController.cs:line 44
... and some other bits"
This is how the proxy is crated in ServiceA:
public class ServiceBServiceProxy : IServiceB
{
private const string ServiceBUri = "fabric:/MyApp.ServiceB/ServiceBService";
public async Task<bool> IsSomeStuffInProgressAsync()
{
var proxy = ServiceProxy.Create<IServiceB>(new Uri(ServiceBUri));
return await proxy.IsSomeStuffInProgressAsync().ConfigureAwait(false); -- error thrown at this poit
}
}
Interface that is implemented in both services ServiceA and ServiceB
public interface IServiceB : IService
{
Task<bool> IsSomeStuffInProgressAsync();
}
IService implementation is ServiceB:
internal sealed class ServiceB : StatelessService, IServiceB
{
private readonly Container _container;
public ServiceB(StatelessServiceContext context, Container container)
: base(context)
{
_container = container;
}
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return this.CreateServiceRemotingInstanceListeners();
}
public async Task<bool> IsSomeStuffInProgressAsync()
{
await using (AsyncScopedLifestyle.BeginScope(_container))
{
var someService = _container.GetService<SomeService>();
return await someService.CheckSomeStuff().ConfigureAwait(false);
}
}
}
Please note, this error is thrown in local environment and on real Test server. Any ideas are appreciated, thanks! Let me know if I need to populate this question with more details.
SF package versions match in both services.
<PackageReference Include="Microsoft.ServiceFabric.Services" Version="3.3.638" />
<PackageReference Include="Microsoft.ServiceFabric.Services.Remoting" Version="3.3.638" />
<PackageReference Include="Microsoft.ServiceFabric.AspNetCore.Kestrel" Version="3.3.638" /> - in WebService (ServiceA)
Both services are successfully deployed to SF cluster. Currently I use the remoting version 1. I did try updating it to version 2 but I go exactly same error in the end.
I tried disabling code optimization and enabling support for 32-bit apps but that didn't help as well.
Originally, the ServiceB was stateful but now I converted it to stateless. There were some net framework 4.8 class libraries but all of them were converted to .net 6 and all dependencies were updated/resolved as well. Not sure what was else needs to be done to make this work. All the code looks pretty the same as in this MS documentation https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-reliable-services-communication-remoting

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
{
//...
}

Web Service Throwing Error

I cannot figure this one out. This code has executed flawlessly for quite a while, now out of nowhere it fails. The web service it calls hasn't changed and I am kind of at a loss. The specific error is {"Configuration system failed to initialize"}
Code I'm using:
webservices.WebService ws = new webservices.WebService();
Code in the designer:
namespace NumberOneService.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.WebServiceUrl)]
[global::System.Configuration.DefaultSettingValueAttribute("http://www.webserver.services/ws_partlookup.cfc")]
public string Web_Service {
get {
return ((string)(this["Web_Service"]));
}
}
}
stack trace:
at System.Configuration.ClientConfigurationSystem.OnConfigRemoved(Object sender, InternalConfigEventArgs e)
at System.Configuration.Internal.InternalConfigRoot.RemoveConfigImpl(String configPath, BaseConfigurationRecord configRecord)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.ClientSettingsStore.ReadSettings(String sectionName, Boolean isUserScoped)
at System.Configuration.LocalFileSettingsProvider.GetPropertyValues(SettingsContext context, SettingsPropertyCollection properties)
at System.Configuration.SettingsBase.GetPropertiesFromProvider(SettingsProvider provider)
at System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)
at System.Configuration.SettingsBase.get_Item(String propertyName)
at System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)
at System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)
at NumberOneService.Properties.Settings.get_Web_Service() in Number One Service\Properties\Settings.Designer.cs:line 33
at NumberOneService.webservices.WebService..ctor() in Number One Service\Web References\webservices\Reference.cs:line 46
at NumberOneService.NumberOneService.bwExecuteProcess_DoWork(Object sender, DoWorkEventArgs e) in Number One Service.cs:line 400
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
This typically happens if you created a web service reference in a class library and then ported it over to a console app or a windows app. the web service references are stored in the settings files with a specific path.
Basically, you're missing a section declaration OR the right setting name in the config file.
please check your config files for the key which stores the url of the service. Else, paste it here and we can help further.
the exception is thrown in the web service constructor when it tries to set the Url from the config file. (host config or settings file)

Nancy using Razor view engine: Embedded views don't work

I have the following code:
public class Program : NancyModule
{
static void Main(string[] args)
{
using (var host = new NancyHost(new Uri("http://localhost:444"), new CustomConventionsBootstrapper()))
{
host.Start();
Console.ReadLine();
}
}
public Program()
{
Get["/"] = parameter =>
{
dynamic var = new ExpandoObject();
var.Test = "Lol";
return View["RazorView.cshtml", var];
};
}
}
public class CustomConventionsBootstrapper : DefaultNancyBootstrapper
{
protected override void ConfigureApplicationContainer(TinyIoCContainer container)
{
base.ConfigureApplicationContainer(container);
//This should be the assembly your views are embedded in
var assembly = Assembly.GetEntryAssembly();
ResourceViewLocationProvider.RootNamespaces.Add(assembly, "NancyTest.Views");
}
protected override NancyInternalConfiguration InternalConfiguration
{
get
{
var res = base.InternalConfiguration;
res.ViewLocationProvider = typeof(ResourceViewLocationProvider);
return res;
}
}
void OnConfigurationBuilder(NancyInternalConfiguration x)
{
x.ViewLocationProvider = typeof(ResourceViewLocationProvider);
}
}
And I have RazorView.cshtml in a folder Views in my project set as embedded resource, however each time I open the page it will give me
Nancy.RequestExecutionException: Oh noes! ---> Nancy.ViewEngines.ViewNotFoundException: Unable to locate view 'RazorView.cshtml'
Currently available view engine extensions: sshtml,html,htm,cshtml,vbhtml
Locations inspected: views/Program/RazorView.cshtml-en-GB,views/Program/RazorView.cshtml,Program/RazorView.cshtml-en-GB,Program/RazorView.cshtml,views/RazorView.cshtml-en-GB,views/RazorView.cshtml,RazorView.cshtml-en-GB,RazorView.cshtml
Root path: C:\Users\Student\documents\visual studio 2013\Projects\NancyTest\NancyTest\bin\Debug
If you were expecting raw data back, make sure you set the 'Accept'-header of the request to correct format, for example 'application/json'
bij Nancy.ViewEngines.DefaultViewFactory.GetRenderedView(String viewName, Object model, ViewLocationContext viewLocationContext)
bij Nancy.ViewEngines.DefaultViewFactory.RenderView(String viewName, Object model, ViewLocationContext viewLocationContext)
bij Nancy.Responses.Negotiation.ViewProcessor.Process(MediaRange requestedMediaRange, Object model, NancyContext context)
bij Nancy.Routing.DefaultRouteInvoker.NegotiateResponse(IEnumerable`1 compatibleHeaders, Object model, Negotiator negotiator, NancyContext context)
bij Nancy.Routing.DefaultRouteInvoker.ProcessAsNegotiator(Object routeResult, NancyContext context)
bij Nancy.Routing.DefaultRouteInvoker.InvokeRouteWithStrategy(Object result, NancyContext context)
bij Nancy.Routing.DefaultRouteInvoker.<>c__DisplayClass9.b__5(Task`1 completedTask)
--- Einde van intern uitzonderingsstackpad ---
bij Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)
It is worth noting that this only happens when using Razor views. When I use a simple html file it can find those files fine. I even tried to run old example projects found online on the current (0.22.2) Nancy version, but no luck there either. What's going on?
Thanks
Okay figured this out, but I have to say this is kinda stupid. Checked the source, this is the culprit:
ResourceAssemblyProvider.cs line 31
private static IEnumerable<Assembly> GetFilteredAssemblies()
{
return AppDomainAssemblyTypeScanner.Assemblies
.Where(x => !x.IsDynamic)
.Where(x => !x.GetName().Name.StartsWith("Nancy", StringComparison.OrdinalIgnoreCase));
}
My assembly is called 'NancyTest'. Changed to 'TestNancy', works now. I suggest finding a better way of excluding your own assemblies.
Also, when working with embedded views, one can easily forget to add the view as an embedded resource (a common gotcha that took me a while to get used to):
Right click on view-file -> properties -> Build Action -> select "Embedded Resource"

NServiceBus System.ArgumentNullException

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.

Categories