Error launching Kentico 13 CMS on clean machine - kentico

I'm trying to run Kentico 13 CMS from source on a fresh machine but I'm getting this stack trace. The site does not render the login prompt when I launch it with F5 from Visual Studio 2019.
I've restored a known good database to my local machine and confirmed that the site compiles successfully.
System.NullReferenceException: Object reference not set to an instance of an object.
at CMS.Membership.Internal.VirtualContextAuthenticationConfiguration.get_Audience()
at CMS.Membership.Internal.SecurityTokenManager`1..ctor(T tokenConfiguration, IJwtTokenService tokenService, IDateTimeNowService dateTimeNowService, IEventLogService eventLogService, IUserInfoProvider userInfoProvider)
at CMS.Membership.Internal.SecurityTokenManager`1..ctor(T tokenConfiguration)
at Kentico.Content.Web.Mvc.VirtualContextPrincipalRetriever..ctor()
at Kentico.Content.Web.Mvc.VirtualContextRequestPrincipalRetriever..ctor()
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitIEnumerable(IEnumerableCallSite enumerableCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, String authenticationScheme)
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Kentico.Content.Web.Mvc.ContentOutputMiddleware.InvokeAsync(HttpContext context)
at Kentico.Web.Mvc.KenticoRequestLocalizationMiddleware.InvokeAsync(HttpContext context)
at Kentico.Content.Web.Mvc.PageRedirectionContextMiddleware.InvokeAsync(HttpContext context)
at Kentico.Web.Mvc.KenticoRequestEventsMiddleware.InvokeAsync(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

The issue was an incorrect database connection string. I needed to confirm that the name of the database was correct, that the username and password were correct, and that the SQL Server instance had username/password authentication configured correctly (not just Windows auth).

Related

Blazor Server Authentication not working after publishing to Azure

I am creating a Blazor Server app and Implemented Authentication using Identity Server.
Everything was working fine until I published it to Azure. Everything is working except Login & Register which return
"Sorry, there's nothing at this address."
When I click Login Azure log stream shows this exception
An unhandled exception has occurred while executing the request.
System.InvalidProgramException: Common Language Runtime detected an invalid program.
at ResolveService(ILEmitResolverBuilderRuntimeContext , ServiceProviderEngineScope )
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelActivatorProvider.<>c__DisplayClass1_0.<CreateActivator>b__0(PageContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageModelFactoryProvider.<>c__DisplayClass3_0.<CreateModelFactory>b__0(PageContext pageContext)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.CreateInstance()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
and Register:
An unhandled exception has occurred while executing the request.
System.Security.SecurityException: Invalid assembly public key. (0x8013141E)
at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
at System.Reflection.RuntimePropertyInfo.get_Signature()
at System.Reflection.RuntimePropertyInfo.get_PropertyType()
at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultPageApplicationModelProvider.CreateModel(PageActionDescriptor actionDescriptor, TypeInfo pageTypeInfo)
at Microsoft.AspNetCore.Mvc.ApplicationModels.DefaultPageApplicationModelProvider.OnProvidersExecuting(PageApplicationModelProviderContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.DefaultPageLoader.LoadAsyncCore(PageActionDescriptor actionDescriptor)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageLoaderMatcherPolicy.ApplyAsyncAwaited(CandidateSet candidates, Task`1 actionDescriptorTask, Int32 index)
at Microsoft.AspNetCore.Routing.Matching.DfaMatcher.SelectEndpointWithPoliciesAsync(HttpContext httpContext, IEndpointSelectorPolicy[] policies, CandidateSet candidateSet)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatch|8_1(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task matchTask)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
and my startup page is:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IDisplayMessage, DisplayMessage>();
services.AddServices();
services.AddScoped<IAuthenticationStateService, AuthenticationStateServiceServerSide>();
services.AddAuthentication();
services.AddDbContextPool<MainDbContext>(options => options
.UseLoggerFactory(MyLoggerFactory)
.EnableSensitiveDataLogging()
.UseMySql(Configuration.GetConnectionString(db), mySqlOptions => mySqlOptions
.ServerVersion(new Version(8, 0, 19), ServerType.MySql)));
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
})
.AddSignInManager<ApplicationSignInManager>()
.AddEntityFrameworkStores<MainDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
var assemlies = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(a => a.FullName.StartsWith("LaWeb")).Select((item) => Assembly.Load(item)).ToList();
assemlies.Add(Assembly.GetExecutingAssembly());
services.AddAutoMapper(assemlies);
}
// 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();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
It works perfectly when runnning from visual studio or when publishing localy to a folder and then running using cmd...

Azure API Management returning "Setting 'config.db.connection' could not be found."

We have exposed some Azure Functions through Azure API Management. The functions work when called directly and the endpoints in Api Management also used to work. Now when we call the api management endpoints they return
[ConfigurationErrorsException: Setting 'config.db.connection' could not be found.]
Microsoft.Azure.ApiManagement.Infra.Configuration.SettingsProviderExtensions.GetSetting(ISettingsProvider provider, String name) in e:\Checkin package\AAPT\APIM\Infra\Infra\src\Infra\Configuration\SettingsProviderExtensions.cs:19
Microsoft.WindowsAzure.ApiManagement.Proxy.Api.Settings.get_SqlConnectionString() in D:\Checkin-Master\AAPT\APIManagement\Proxy\Api\Service\Settings.cs:43
Microsoft.Azure.ApiManagement.Gateway.IoC.Modules.c.b__0_0(IComponentContext c) in D:\Checkin-Master\AAPT\APIManagement\Proxy\Gateway.IoC\Modules\SqlConfigurationModule.cs:38
Autofac.c__DisplayClass10`1.b__f(IComponentContext c, IEnumerable`1 p) +10
Autofac.Builder.c__DisplayClass1`1.b__0(IComponentContext c, IEnumerable`1 p) +14
Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +32
Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +48
Autofac.Core.Resolving.InstanceLookup.b__0() +8
Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func`1 creator) +120
Autofac.Core.Resolving.InstanceLookup.Execute() +132
Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +133
Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +24
Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) +74
Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters) +54
Autofac.ResolutionExtensions.Resolve(IComponentContext context, IEnumerable`1 parameters) +118
Microsoft.Azure.ApiManagement.Gateway.IoC.Modules.c.b__0_4(IComponentContext c) in D:\Checkin-Master\AAPT\APIManagement\Proxy\Gateway.IoC\Modules\ConfigurationModule.cs:116
Autofac.c__DisplayClass10`1.b__f(IComponentContext c, IEnumerable`1 p) +10
Autofac.Builder.c__DisplayClass1`1.b__0(IComponentContext c, IEnumerable`1 p) +14
Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +32
Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +48
Autofac.Core.Resolving.InstanceLookup.b__0() +8
Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func`1 creator) +120
Autofac.Core.Resolving.InstanceLookup.Execute() +132
Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +133
Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +24
Autofac.Core.Activators.Reflection.c__DisplayClass2.b__0() +25
Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() +94
Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +174
Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +48
Autofac.Core.Resolving.InstanceLookup.b__0() +8
Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func`1 creator) +120
Autofac.Core.Resolving.InstanceLookup.Execute() +132
Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +133
Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) +44
[DependencyResolutionException: An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Setting 'config.db.connection' could not be found. (See inner exception for details.)]
Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) +112
Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +109
Autofac.Core.Container.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +14
Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) +74
Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters) +54
Autofac.ResolutionExtensions.Resolve(IComponentContext context, IEnumerable`1 parameters) +118
Autofac.ResolutionExtensions.Resolve(IComponentContext context) +75
Microsoft.Azure.ApiManagement.Gateway.Host.SystemWeb.GatewayStartup.Configuration(IAppBuilder app) in D:\Checkin-Master\AAPT\APIManagement\Proxy\Gateway.Host.SystemWeb\GatewayStartup.cs:75
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +160
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +101
Owin.Loader.c__DisplayClass12.b__b(IAppBuilder builder) +66
Owin.Loader.c__DisplayClass1.b__0(IAppBuilder builder) +123
Microsoft.Owin.Host.SystemWeb.c__DisplayClass2.b__0(IAppBuilder builder) +71
Microsoft.Owin.Host.SystemWeb.OwinAppContext.Initialize(Action`1 startup) +462
Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build(Action`1 startup) +40
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.InitializeBlueprint() +70
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(HttpApplication context) +106
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +523
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +176
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +220
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +303
[HttpException (0x80004005): Exception has been thrown by the target of an invocation.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +658
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +89
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +189
Where is this db.connection setting that is missing?
I guess you were using consumption sku. Apim had a bug in upgrade. This should not be happening anymore.

Cannot choose between multiple constructors with equal length 1 on type 'System.String'

I am getting the following error when trying to resolve a type:
Cannot choose between multiple constructors with equal length 1 on type 'System.String'. Select the constructor explicitly, with the UsingConstructor() configuration method, when the component is registered.
The type has 1 constructor that takes an IRepository and an ILog so I don't really know where the System.String is coming in to the picture. I'm perplexed. Does anyone have any idea what the problem is?
Here is the stack trace:
at Autofac.Core.Activators.Reflection.MostParametersConstructorSelector.SelectConstructorBinding(ConstructorParameterBinding[] constructorBindings)
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Activators.Reflection.AutowiringParameter.<>c_DisplayClass2.b_0()
at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Activators.Reflection.AutowiringParameter.<>c_DisplayClass2.b_0()
at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable1 parameters, Object& instance)
at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable1 parameters)
at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType, IEnumerable1 parameters)
at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType)
at SomeCompany.ComponentModel.Composition.AutofacIocContainer.Resolve(Type type) in c:\SomeCompany.Core\ComponentModel\Composition\AutofacIocContainer.cs:line 17
at SomeCompany.Commands.CommandFactory.Create(String name) in c:\SomeCompany.Core\Commands\CommandFactory.cs:line 28
at SomeCompany.Web.Controllers.CommandsController.Post(String id, String request) in c:\SomeCompany.Web\Controllers\CommandsController.cs:line 49
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func1 func, CancellationToken cancellationToken)
This has nothing to do with multiple constuctors on your own code!
Autofac automatically creates objects for the constructor of your subject when you don't set them explicitly yourself.
However, when your constructor has a String parameter, it can not create a string, as String does not have a parameterless constructor! [1]
You need to set all strings on the constructor of your subject explicitly. You can also use NamedParameters and give Strings an explicit value.
Good luck!
[1] http://msdn.microsoft.com/en-us/library/system.string%28v=vs.110%29.aspx
If you have a database-definition file (.dbml), check for modifications to the code that you didn't make. In my case, the following method
public JudicialDataContext(string connectionString) : base(connectionString, mappingSource)
{
OnCreated();
}
was changed to this:
public JudicialDataContext(string connection) : base(connection, mappingSource)
{
OnCreated();
}
I have no idea why it did this, or what it is trying to accomplish by doing this, or why this change would even be necessary. But discarding the change and recompiling overcame this error.

nhibernate CurrentSessionContext.Hasbind giving object reference not set

Hi i m using WebApi Mvc4 framework .net 4.0
I create a sessionFactory as follows:
public void ConfigureNHibernate(IKernel container)
{
var sessionFactory = FluentNHibernate
.Cfg.Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2008.ConnectionString(
c => c.FromConnectionStringWithKey("ApikeysDb")))
.CurrentSessionContext("web")
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<CTP.ApiNext.Data.SqlServer.SqlCommandFactory>())
.BuildSessionFactory();
// Add the ISessionFactory instance to the container
container.Bind<ISessionFactory>().ToConstant(sessionFactory);
// Configure a resolver method to be used for creating ISession objects
container.Bind<ISession>().ToMethod(CreateSession);
container.Bind<ICurrentSessionContextAdapter>().To<CurrentSessionContextAdapter>();
}
and below when I am binding my ISession object to the HTTP context, I am getting error "Object reference not set"
public ISession CreateSession(IContext context)
{
var sessionFactory = context.Kernel.Get<ISessionFactory>();
if (!CurrentSessionContext.HasBind(sessionFactory))
{
// Open new ISession and bind it to the current session context
var session = sessionFactory.OpenSession();
CurrentSessionContext.Bind(session);
}
return sessionFactory.GetCurrentSession();
}
The error is at at line: CurrentSessionContext.HasBind(sessionFactory)
The error details are:
[NullReferenceException: Object reference not set to an instance of an object.]
lambda_method(Closure , Object ) +73
NHibernate.Context.ReflectiveHttpContext.get_HttpContextCurrentItems() +84
NHibernate.Context.WebSessionContext.GetMap() +52
NHibernate.Context.MapBasedSessionContext.get_Session() +70
NHibernate.Context.CurrentSessionContext.HasBind(ISessionFactory factory) +71
CTP.ApiNext.Web.Api.App_Start.NinjectConfigurator.CreateSession(IContext context) in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectConfigurator.cs:91
Ninject.Activation.Providers.CallbackProvider`1.CreateInstance(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\CallbackProvider.cs:45
Ninject.Activation.Provider`1.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Provider.cs:38
Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4077101
Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:197
Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:165
Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:114
Ninject.Activation.Providers.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
System.Linq.WhereSelectArrayIterator`2.MoveNext() +66
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +216
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +77
Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4077101
Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:197
Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent) in c:\Projects\Ninject\ninject\src\Ninject\Planning\Targets\Target.cs:165
Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:114
Ninject.Activation.Providers.<>c__DisplayClass4.<Create>b__2(ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
System.Linq.WhereSelectArrayIterator`2.MoveNext() +66
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +216
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +77
Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:96
Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:157
Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:386
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.<CastIterator>d__b1`1.MoveNext() +85
System.Linq.Enumerable.Single(IEnumerable`1 source) +191
Ninject.ResolutionExtensions.Get(IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:37
CTP.ApiNext.Web.Api.App_Start.NinjectWebCommon.RegisterServices(IKernel kernel) in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectWebCommon.cs:61
CTP.ApiNext.Web.Api.App_Start.NinjectWebCommon.CreateKernel() in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectWebCommon.cs:48
Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs:50
CTP.ApiNext.Web.Api.App_Start.NinjectWebCommon.Start() in C:\Projects\UNILEVER\WHITELABEL\_api-next\ctp-api-next\src\CTP.ApiNext.Web.Api\App_Start\NinjectWebCommon.cs:27
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +108
System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +19
WebActivator.BaseActivationMethodAttribute.InvokeMethod() +236
WebActivator.ActivationManager.RunActivationMethods() +534
WebActivator.ActivationManager.RunPreStartMethods() +41
WebActivator.ActivationManager.Run() +64
[InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +550
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +90
System.Web.Compilation.BuildManager.ExecutePreAppStart() +135
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516
[HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Exception has been thrown by the target of an invocation..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873912
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +456
I read so many posts, but no avail.
I have a MessageHandler (invoked by ninject), which invokes ISession, when I comment it out, the problem goes away. Why?
GlobalConfiguration.Configuration.MessageHandlers.Add(kernel.Get());
Your Factory and Session interfaces are not bound correctly. You have to set the scope as part of the Binding (InSingletonScope for the Factory as you only ever need one of these, and InThreadScope for the Session). This is so Ninject knows when to inject an existing reference or create a new instance of each type.
Try modifying your configuration to the following:
public void ConfigureNHibernate(IKernel container)
{
var sessionFactory = FluentNHibernate
.Cfg.Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2008.ConnectionString(
c => c.FromConnectionStringWithKey("ApikeysDb")))
.CurrentSessionContext("web")
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<CTP.ApiNext.Data.SqlServer.SqlCommandFactory>());
// Bind the ISession Factory - Singleton as only ever need one of these
container.Bind<ISessionFactory>().ToMethod(x =>configuration.BuildSessionFactory()).InSingletonScope();
// Bind the ISession
container.Bind<ISession>().ToMethod(c => c.Kernel.Get<ISessionFactory>().OpenSession()).InThreadScope();
}
To test the above you can immediately try to instantiate a Factory:
var sessionFactory = Kernel.Get<ISessionFactory>();

web api internal error 500

I am using the laatest version of web api.
I am returning a IQuerable value and i am getting this error:
iisexpress.exe Error: 0 : Operation=QueryableAttribute.ActionExecuted, Status=200 (OK), Exception=System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateStructuralTypeBody(EdmStructuredType type, IStructuralTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateEntityTypeBody(EdmEntityType type, IEntityTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateEdmTypeBody(IStructuralTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.<GetEdmTypes>d__0.MoveNext()
at System.Linq.Enumerable.<OfTypeIterator>d__aa`1.MoveNext()
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at System.Linq.Enumerable.ToDictionary[TSource,TKey](IEnumerable`1 source, Func`2 keySelector)
at System.Web.Http.OData.Builder.EdmModelHelperMethods.BuildEdmModel(String containerNamespace, String containerName, IEnumerable`1 entityTypeConfigurations, IEnumerable`1 entitySetConfigurations)
at System.Web.Http.OData.Builder.ODataModelBuilder.GetEdmModel()
at System.Web.Http.OData.Builder.ODataConventionModelBuilder.GetEdmModel()
at System.Web.Http.HttpActionDescriptorExtensions.<>c__DisplayClass1.<GetEdmModel>b__0(Object _)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Web.Http.HttpActionDescriptorExtensions.GetEdmModel(HttpActionDescriptor actionDescriptor, Type entityClrType)
at System.Web.Http.QueryableAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
at System.Web.Http.Tracing.Tracers.ActionFilterAttributeTracer.<>c__DisplayClass4.<OnActionExecuted>b__1()
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Action execute, Action`1 endTrace, Action`1 errorTrace)
iisexpress.exe Error: 0 : Operation=InteractionDataController.ExecuteAsync, Exception=System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateStructuralTypeBody(EdmStructuredType type, IStructuralTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateEntityTypeBody(EdmEntityType type, IEntityTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateEdmTypeBody(IStructuralTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.<GetEdmTypes>d__0.MoveNext()
at System.Linq.Enumerable.<OfTypeIterator>d__aa`1.MoveNext()
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at System.Linq.Enumerable.ToDictionary[TSource,TKey](IEnumerable`1 source, Func`2 keySelector)
at System.Web.Http.OData.Builder.EdmModelHelperMethods.BuildEdmModel(String containerNamespace, String containerName, IEnumerable`1 entityTypeConfigurations, IEnumerable`1 entitySetConfigurations)
at System.Web.Http.OData.Builder.ODataModelBuilder.GetEdmModel()
at System.Web.Http.OData.Builder.ODataConventionModelBuilder.GetEdmModel()
at System.Web.Http.HttpActionDescriptorExtensions.<>c__DisplayClass1.<GetEdmModel>b__0(Object _)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Web.Http.HttpActionDescriptorExtensions.GetEdmModel(HttpActionDescriptor actionDescriptor, Type entityClrType)
at System.Web.Http.QueryableAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
at System.Web.Http.Tracing.Tracers.ActionFilterAttributeTracer.<>c__DisplayClass4.<OnActionExecuted>b__1()
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Action execute, Action`1 endTrace, Action`1 errorTrace)
at System.Web.Http.Tracing.Tracers.ActionFilterAttributeTracer.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
at System.Web.Http.Filters.ActionFilterAttribute.CallOnActionExecuted(HttpActionContext actionContext, HttpResponseMessage response, Exception exception)
at System.Web.Http.Filters.ActionFilterAttribute.<>c__DisplayClass2.<System.Web.Http.Filters.IActionFilter.ExecuteActionFilterAsync>b__0(HttpResponseMessage response)
at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass41`2.<Then>b__40(Task`1 t)
at System.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)
Can someone explain me what the problem is ?
I was getting this same error. I traced it down to when ODataModelBuilder calls GetEdmModel(). I'm using ODataConventionModelBuilder and I'm declaring EntitySets to create my model. In my case, I have a parent class with a child collection. I tried different types of collections, IList, List, ICollection, IEnumerable, and I continued to get this error. I know this isn't the best solution, but I declare the child collection as object. I assign the collection as IEnumerable using Linq. I'll keep looking into this, but at least I can continue with my project. I'll have to keep researching the ODataConventionModelBuilder. I hope this at least points you in the right direction.
-Jason
This seems to be a known issue in WebApi.OData package (0.1.0-alpha-120815). See http://aspnetwebstack.codeplex.com/discussions/394626

Resources