IdentityServer4 dotnet7 produce exception - c#

when using Automaper 10.1.1, with identityserver4 and .net 7, identityserver4 is the last free version of IdentityServer and doesn't work with a higher version of AutoMapper where this issue is resolved in this link: Issue.
Automapper 10 + identity server 4 + dotnet 7
simply when I hit /.well-known/openid-configuration I got this exception
ArgumentException: GenericArguments[0], 'System.Char', on 'T MaxFloat[T](System.Collections.Generic.IEnumerable`1[T])' violates the constraint of type 'T'.
System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
System.Reflection.RuntimeMethodInfo.MakeGenericMethod(Type[] methodInstantiation)
AutoMapper.TypeDetails+<>c__DisplayClass28_1.<BuildPublicNoArgExtensionMethods>b__10(MethodInfo extensionMethod)
System.Linq.Enumerable+WhereSelectArrayIterator<TSource, TResult>.MoveNext()
System.Linq.Enumerable+ConcatIterator<TSource>.MoveNext()
System.Linq.Enumerable.SelectManyIterator<TSource, TCollection, TResult>(IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)+MoveNext()
System.Linq.Enumerable+WhereSelectEnumerableIterator<TSource, TResult>.MoveNext()
System.Collections.Generic.HashSet<T>.UnionWith(IEnumerable<T> other)
System.Linq.Enumerable+UnionIterator<TSource>.FillSet()
System.Linq.Enumerable+UnionIterator<TSource>.ToArray()
AutoMapper.TypeDetails.BuildPublicNoArgExtensionMethods(IEnumerable<MethodInfo> sourceExtensionMethodSearch)
AutoMapper.TypeDetails..ctor(Type type, ProfileMap config)
AutoMapper.ProfileMap.TypeDetailsFactory(Type type)
AutoMapper.Internal.LockingConcurrentDictionary<TKey, TValue>+<>c__DisplayClass2_1.<.ctor>b__1()
System.Lazy<T>.ViaFactory(LazyThreadSafetyMode mode)
System.Lazy<T>.ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor)
System.Lazy<T>.CreateValue()
AutoMapper.Internal.LockingConcurrentDictionary<TKey, TValue>.GetOrAdd(TKey key)
AutoMapper.ProfileMap.CreateTypeDetails(Type type)
AutoMapper.TypeMapFactory.CreateTypeMap(Type sourceType, Type destinationType, ProfileMap options, bool isReverseMap)
AutoMapper.ProfileMap.BuildTypeMap(IConfigurationProvider configurationProvider, ITypeMapConfiguration config)
AutoMapper.ProfileMap.Register(IConfigurationProvider configurationProvider)
AutoMapper.MapperConfiguration.Seal()
AutoMapper.MapperConfiguration..ctor(MapperConfigurationExpression configurationExpression)
AutoMapper.MapperConfiguration..ctor(Action<IMapperConfigurationExpression> configure)
IdentityServer4.EntityFramework.Mappers.IdentityResourceMappers..cctor()
// Put your source/destination types here
I tryed all Higher versions and I get another exception because identity server 4 requires AutoMapper version>=10 and <11, in this case I got this exception:
System.MissingMethodException: Method not found: '!2 AutoMapper.IMappingExpressionBase`3.ConstructUsing(System.Linq.Expressions.Expression`1<System.Func`2<!0,!1>>)'.
at IdentityServer4.EntityFramework.Mappers.ClientMapperProfile..ctor()
at System.RuntimeType.CreateInstanceOfT()

I also saw this problem yesterday - spent a lot of time looking for a solution but couldnt.
I decided to downgrade .net to 6.0 then it worked - though, the requirements of IS4.EF.Storage mention support to .net 7.0
Maybe you should look at Duende.IdentityServer
This is new company by creators of IS4. Probably the issue has been resolved there. Switching from IS4 to Duende shouldnt be difficult due to their similarity

Related

C# Docusign API Launcher error ArgumentException: The 'ClientId' option must be provided. (Parameter 'ClientId')

I am receiving this error after filling in the config details (such as integration key and client secret) into the appsettings.example.json file. I downloaded Code-Examples-CSharp from the Docusign Github and was able to run the ISSExpresss in VS2019 and it takes me to http://localhost:8080/ and then I am receiving this error below. I don't think I am missing any other config areas, but I'm new to Docusign APIs so please let me know if I am.
An unhandled exception occurred while processing the request.
ArgumentException: The 'ClientId' option must be provided. (Parameter 'ClientId')
Microsoft.AspNetCore.Authentication.OAuth.OAuthOptions.Validate()
ArgumentException: The 'ClientId' option must be provided. (Parameter 'ClientId')
Microsoft.AspNetCore.Authentication.OAuth.OAuthOptions.Validate()
Microsoft.AspNetCore.Authentication.RemoteAuthenticationOptions.Validate(string scheme)
Microsoft.AspNetCore.Authentication.AuthenticationBuilder+<>c__DisplayClass4_0<TOptions, THandler>.b__1(TOptions o)
Microsoft.Extensions.Options.ValidateOptions.Validate(string name, TOptions options)
Microsoft.Extensions.Options.OptionsFactory.Create(string name)
Microsoft.Extensions.Options.OptionsMonitor+<>c__DisplayClass11_0.b__0()
System.Lazy.ViaFactory(LazyThreadSafetyMode mode)
System.Lazy.ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor)
System.Lazy.CreateValue()
System.Lazy.get_Value()
Microsoft.Extensions.Options.OptionsCache.GetOrAdd(string name, Func createOptions)
Microsoft.Extensions.Options.OptionsMonitor.Get(string name)
Microsoft.AspNetCore.Authentication.AuthenticationHandler.InitializeAsync(AuthenticationScheme scheme, HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, string authenticationScheme)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
You need to copy appsettings.example.json into appsettings.json and then update all the fields in it before you run this. You have to obtain an integration key from the DocuSign developer account which you can create for free.

How to make NHibernate 5.2.7 not have runtime exceptions with ASP.NET Core 3.1?

On a new project my team and I are working on, I'm exploring if NHibernate 5.2.7 / FluentNHibernate 2.1.2 are compatible with ASP.NET Core 3.1. I did some research on NHibernate 5.2.3, a slightly earlier version, and in that SO thread, they noted that NHibernate at this point should be .NET Core compatible.
With that being said, that does not appear to be the case.
Below is how we use NHibernate. We create sessions using this DataContext object (in a using block, of course, because ISessions are IDisposable!) and then use QueryOver to fetch or set data to our database.
However, when we attempt any DB operations, we get the following exception on the _sessionFactory.OpenSession() call:
Could not load type 'System.Runtime.Remoting.Messaging.CallContext' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
Inner exception: null
Stack trace: at NHibernate.Impl.SessionIdLoggingContext.get_SessionId()
at NHibernate.Impl.SessionIdLoggingContext..ctor(Guid id)
at NHibernate.Impl.AbstractSessionImpl.BeginContext()
at NHibernate.Impl.AbstractSessionImpl..ctor(ISessionFactoryImplementor factory, ISessionCreationOptions options)
at NHibernate.Impl.SessionImpl..ctor(SessionFactoryImpl factory, ISessionCreationOptions options)
at NHibernate.Impl.SessionFactoryImpl.SessionBuilderImpl`1.OpenSession()
at NHibernate.Impl.SessionFactoryImpl.OpenSession()
at MyRadProject.Core.DataContext.GetSession() in C:\MyRadProject.Core\DataContext.cs:line 18
at MyRadProject.Core.Repositories.UserRepository.GetUsers(Boolean includeInactive) in C:\MyRadProject.Core\Repositories\UserRepository.cs:line 23
at MyRadProject.Web.Controllers.CommonController.GetUsers() in C:\MyRadProject.Web\Controllers\CommonController.cs:line 21
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Logged|12_1>d.MoveNext()
As far as my team can tell, this exception previously occurred in earlier versions of .NET Core due to certain namespaces or classes that weren't provided for in the .NET Core (e.g. System.Configuration.ConfigurationManager) To the shared credit of .NET Core and NHibernate these issues seem to be much mitigated.
I double-checked that mscorlib was referenced in the library project that our data-access code exists in ("MyAwesomeProject.Core"). In Visual Studio 2019, I didn't see such a reference; when I attempted to manually reference mscorlib, I got a message, "mscorlib is automatically referenced by the build process."
All of this leads to my question:
Assuming that the SO thread above is accurate in stating that NHibernate 5.1.1+ is .NET Core-compatible, what else do I need to do to make it such that NHibernate 5.2.7 does not generate a runtime exception when I attempt any database operation?
DataContext.cs
public class DataContext
{
private static ISessionFactory _sessionFactory;
private static bool _startupComplete;
private static readonly object _locker = new object();
public static ISession GetSession()
{
EnsureStartup();
ISession session = _sessionFactory.OpenSession(); // EXCEPTION occurs here!
session.BeginTransaction();
return session;
}
public static void EnsureStartup()
{
if (!_startupComplete)
{
lock (_locker)
{
if (!_startupComplete)
{
PerformStartup();
_startupComplete = true;
}
}
}
}
private static void PerformStartup()
{
InitializeSessionFactory();
}
private static void InitializeSessionFactory()
{
Configuration configuration = BuildConfiguration();
_sessionFactory = configuration.BuildSessionFactory();
}
public static Configuration BuildConfiguration()
{
var configuration = new Configuration().Configure();
return Fluently.Configure(configuration)
.Mappings(cfg => cfg.FluentMappings.AddFromAssembly(typeof(DataContext).Assembly))
.BuildConfiguration();
}
// There are other methods below this point that aren't pertinent to the question.
}
It seems you are using Full .NET Framework version of the library as CallContext class is not used in .NET Core/.NET Standard version of NHibernate (AsyncLocal is used instead):
https://github.com/nhibernate/nhibernate-core/blob/c0f50429722b4e061a0c6b40b720db17d33fc85e/src/NHibernate/Impl/SessionIdLoggingContext.cs#L60-L65
So to fix your issue try to use .NET Core or .NET Standard version of the library.

Health check for AddDbContextCheck by TContextService and TContextImplementation

I'm setup my DBContext by TContextService and TContextImplementation options.
Something like this:
services.AddDbContext<IMyDbContext, MyDbContext>(options => options.UseNpgsql(myDatabaseConnectionString));
I try to enable health check from Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore
When I try to use this code
services.AddHealthChecks().AddDbContextCheck<MyDbContext>()
I got from health end point response that
InvalidOperationException: Unable to resolve service for type 'MyDbContext' while attempting to activate 'Microsoft.Extensions.Diagnostics.HealthChecks.DbContextHealthCheck`1[MyDbContext]'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities+ConstructorMatcher.CreateInstance(IServiceProvider provider)
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, object[] parameters)
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider)
Do you know any method to use two options TContextService and TContextImplementation for health check by Entity Framework?
You seem to have hit a case where the two cannot work together. I think you have two options:
First is to register the DbContext directly and then just resolve the interface from this registration.
services.AddDbContext<MyDbContext>(options => options.UseNpgsql(myDatabaseConnectionString));
services.AddTransient<IMyDbContext>(c=>c.GetRequiredService<MyDbContext>());
Another option is to implement the health check functionality yourself. Which is not exactly hard.
See : EntityFrameworkCoreHealthChecksBuilderExtensions.cs and DbContextHealthCheck.cs

Aspect Oriented Programming with StructureMap.DynamicInterception

I implemented a console app that uses DynamicInterception on structure map, I follow the example on the page StructureMap DynamicInterception.
Now I'm trying to pass the code to a asp.net MVC site but I get the following error
Decorator Interceptor failed during object construction. See the inner exception:
1.) DynamicProxyInterceptor of ITSector.Site.Core.Controllers.HomeController with interception
behaviors: ITSector.Library.Aspect.LoggerInterceptor
2.) ITSector.Site.Core.Controllers.HomeController
3.) Instance of ITSector.Site.Core.Controllers.HomeController
4.) Container.GetInstance(ITSector.Site.Core.Controllers.HomeController)
The inner exception is:
Specified type is not an interface
Parameter name: interfaceToProxy
With the stacktrace:
at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, Object target, ProxyGenerationOptions options, IInterceptor[] interceptors)
at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithTarget[TInterface](TInterface target, IInterceptor[] interceptors)
at lambda_method(Closure , IBuildSession , IContext )
I use the Structure.MVC5.Update nuget as the Dependency Resolver.
Can anyone give me any hint on how to implement it to intercept calls on controller methods.
Thanks.
StructureMap is expecting an interface in the For<T>() method, but you're passing it HomeController, which is a concrete class.
You have a couple of options to get it working. You can attach your LoggerInteceptor to all controllers with For<IController>(). If you only want to attach the logger to some of your controllers, you can create a new interface specifically for the logged controllers, like For<ILoggedController>(), and ensure the desired controllers inherit from ILoggedController.

FluentNHibernate.MissingConstructorException when building the SessionFactory

I'm trying to fluently configure a SessionFactory to access an Oracle9i database, using ODP.Net, and I'm getting this MissingConstructorException. I've got the actual fluent mappings sorted out ok, but I'm not sure what else it is that I've done wrong.
Here is the exception:
BasicConnectionTests.AssertThatWeCanConnectToADatabase :
FailedFluentNHibernate.MissingConstructorException: 'FluentNHibernate.Automapping.IAutoClasslike, FluentNHibernate, Version=1.1.0.685, Culture=neutral, PublicKeyToken=8aa435e3cb308880' is missing a parameterless constructor.
at FluentNHibernate.Utils.Extensions.InstantiateUsingParameterlessConstructor(Type type)
at FluentNHibernate.PersistenceModel.Add(Type type)
at FluentNHibernate.Utils.CollectionExtensions.Each<T>(IEnumerable`1 enumerable, Action`1 each)
at FluentNHibernate.PersistenceModel.AddMappingsFromSource(ITypeSource source)
at FluentNHibernate.Cfg.FluentMappingsContainer.Apply(Configuration cfg)
at FluentNHibernate.Cfg.MappingConfiguration.Apply(Configuration cfg)
at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
at FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration()
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()
FluentNHibernate.Cfg.FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory()
at MyAwesomeApp.sessionFactories.Oracle9SessionFactoryWrapper.Configure(String userName, String passWord, String dataBase) in Oracle9SessionFactoryWrapper.cs: line 26
at MyAwesomeApp.Tests.oracle.BasicConnectionTests.AssertThatWeCanConnectToADatabase() in BasicConnectionTests.cs: line 17
Here is the fluent mapping:
public ISessionFactory Configure(string userName, string passWord, string dataBase)
{
var config = Fluently.Configure();
config.Database(
OracleDataClientConfiguration.Oracle9
.ConnectionString(cs => cs.Username(userName).Password(passWord).Instance(dataBase))
.Driver("NHibernate.Driver.OracleDataClientDriver")
#if DEBUG
.ShowSql()
#endif
);
config.Mappings(
m => m.FluentMappings.AddFromAssembly(Assembly.GetCallingAssembly()));
return config.BuildSessionFactory();
}
If anyone can point out where I'm going wrong, I'd be most grateful.
As James Gregory pointed in his comment on my question, I was doing something really stupid when informing Fluent were my mappings were.
When the code was exercised from the context of a unit test, m => m.FluentMappings.AddFromAssembly(Assembly.GetCallingAssembly()) tried to tell Fluent to look in the unit test assembly for the mappings - which is going to fail, miserably.
The answer is to use m => m.FluentMappings.AddFromAssemblyOf<Foo>(), where Foo is a type in the assembly were the mappings are.

Categories

Resources