CodeCampServer don't input any logging from NHibernate? - nhibernate

Are you ever succeed input NHibernate logging using CodeCampServer architecture?
I read this and I did everything that I can. Maybe there is know problem in this architecture.
I using Infrastructure.NHibernate.DataAccess.Bases.Logger.EnsureInitialized();
to initialize log4net. here the code:
public class DependencyRegistrar
{
private static bool _dependenciesRegistered;
private static void RegisterDependencies()
{
ObjectFactory.Initialize(x => x.Scan(y =>
{
y.AssemblyContainingType<DependencyRegistry>();
y.AssemblyContainingType<NaakRegistry>();
y.LookForRegistries();
y.AddAllTypesOf<IRequiresConfigurationOnStartup>();
}));
new InitiailizeDefaultFactories().Configure();
}
private static readonly object sync = new object();
internal void ConfigureOnStartup()
{
Infrastructure.NHibernate.DataAccess.Bases.Logger.EnsureInitialized();
RegisterDependencies();
var dependenciesToInitialized = ObjectFactory.GetAllInstances<IRequiresConfigurationOnStartup>();
foreach (var dependency in dependenciesToInitialized)
{
dependency.Configure();
}
}
public static T Resolve<T>()
{
return ObjectFactory.GetInstance<T>();
}
public static object Resolve(Type modelType)
{
return ObjectFactory.GetInstance(modelType);
}
public static bool Registered(Type type)
{
EnsureDependenciesRegistered();
return ObjectFactory.GetInstance(type) != null;
}
public static void EnsureDependenciesRegistered()
{
if (!_dependenciesRegistered)
{
lock (sync)
{
if (!_dependenciesRegistered)
{
RegisterDependencies();
_dependenciesRegistered = true;
}
}
}
}
}
And I see the logging files, I can't delete them when the app run, so I know they are generated. in addition, when I log for test, the log are input. For example, this code do input log.
Bases.Logger.Debug(this, "Debug test!")
So, do CodeCampServer have a architecture problem with log4net?

The post looks correct to me.
Are you sure you added the necessary assembly level attribute?
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
If this won't work maybe you should try:
log4net.Config.XmlConfigurator.Configure();
for example in your Application_Start of Global.asax.
If this won't work please post your example code.

Accidentally found solution by replacing the reference forlog4net.dll to the on that come with NHibernate bins, instead the own log4net.
Wired, but I have logs... :)

Related

Autofac: ITenantIdentificationStrategy with RouteValues

I'm having issues making multitenancy work. I've tried to follow the sample here and can't see what my implementation is doing differently.
The tenants are identified by a routing parameter in the address field. This seems to work without issues (calling TryIdentifyTenant returns the correct one). I am using ASP.NET Core 3.1, together with Autofac.AspNetCore-Multitenant v3.0.1 and Autofac.Extensions.DependencyInjection v6.0.0.
I have made a simplification of the code (which is tested and still doesn't work). Two tenants are configured, "terminal1" and "terminal2". The output should differ depending on the tenant. However, it always returns the base implementation. In the example below, inputing "https://localhost/app/terminal1" returns "base : terminal1" and "https://localhost/app/terminal2" returns "base : terminal2". It should return "userhandler1 : terminal1" and "userhandler2 : terminal2".
HomeController:
public class HomeController : Controller
{
private readonly IUserHandler userHandler;
private readonly TerminalResolverStrategy terminalResolverStrategy;
public HomeController(IUserHandler userHandler, TerminalResolverStrategy terminalResolverStrategy)
{
this.userHandler = userHandler;
this.terminalResolverStrategy = terminalResolverStrategy;
}
public string Index()
{
terminalResolverStrategy.TryIdentifyTenant(out object tenant);
return userHandler.ControllingVncUser + " : " + (string)tenant;
}
}
UserHandler:
public interface IUserHandler
{
public string ControllingVncUser { get; set; }
}
public class UserHandler : IUserHandler
{
public UserHandler()
{
ControllingVncUser = "base";
}
public string ControllingVncUser { get; set; }
}
public class UserHandler1 : IUserHandler
{
public UserHandler1()
{
ControllingVncUser = "userhandler1";
}
public string ControllingVncUser { get; set; }
}
public class UserHandler2 : IUserHandler
{
public UserHandler2()
{
ControllingVncUser = "userhandler2";
}
public string ControllingVncUser { get; set; }
}
Startup:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddControllersWithViews();
services.AddAutofacMultitenantRequestServices();
}
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<TerminalResolverStrategy>();
builder.RegisterType<UserHandler>().As<IUserHandler>();
}
public static MultitenantContainer ConfigureMultitenantContainer(IContainer container)
{
var strategy = new TerminalResolverStrategy(
container.Resolve<IOptions<TerminalAppSettings>>(),
container.Resolve<IHttpContextAccessor>());
var mtc = new MultitenantContainer(strategy, container);
mtc.ConfigureTenant("terminal1", b => b.RegisterType<UserHandler1>().As<IUserHandler>());
mtc.ConfigureTenant("terminal2", b => b.RegisterType<UserHandler2>().As<IUserHandler>());
return mtc;
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
loggerFactory.AddLog4Net();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{terminal}/{controller=Home}/{action=Index}/{id?}");
});
}
}
Program:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacMultitenantServiceProviderFactory(Startup.ConfigureMultitenantContainer))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
ITenantIdentificationStrategy:
public class TerminalResolverStrategy : ITenantIdentificationStrategy
{
public IHttpContextAccessor Accessor { get; private set; }
private readonly TerminalAppSettings settings;
public TerminalResolverStrategy(
IOptions<TerminalAppSettings> options,
IHttpContextAccessor httpContextAccessor
)
{
Accessor = httpContextAccessor;
settings = options.Value;
}
public bool TryIdentifyTenant(out object terminal)
{
HttpContext httpCtx = Accessor.HttpContext;//
terminal = null;
try
{
if (httpCtx != null &&
httpCtx.Request != null &&
httpCtx.Request.RouteValues != null &&
httpCtx.Request.RouteValues.ContainsKey("terminal"))
{
string requestedTerminal = httpCtx.Request.RouteValues["terminal"].ToString();
bool terminalExists = settings.Terminals.ContainsKey(requestedTerminal);
if (terminalExists)
{
terminal = requestedTerminal;
}
}
}
catch (Exception) {}
return terminal != null;
}
}
}
What am i doing wrong? Thanks in advance.
"Multitenancy doesn't seem to work at all" is a somewhat ambiguous statement that's hard to address. Unfortunately, I don't personally have the time to download all of your example code and try to repro the whole thing and debug into it and see exactly what's wrong. Perhaps someone else does. However, I can offer some tips as to places I'd look and things I'd try to see what's up.
Tenant ID strategy set up twice. I see in Startup.ConfigureContainer that there's a builder.RegisterType<TerminalResolverStrategy>(); line - that's going to register your strategy type as instance-per-dependency, so every time it's needed it'll be resolved fresh. I also see in Startup.ConfigureMultitenantContainer that you're manually instantiating the strategy that gets used by the multitenant container. There's a non-zero possibility that something is getting messed up there. I would pick one way to get that done - either register the strategy or manually create it - and I'd make sure that thing is a stateless singleton. (It's not registered in the example.)
Route pattern possibly questionable. I see the route pattern you have registered looks like this: {terminal}/{controller=Home}/{action=Index}/{id?}. I also see your URLs look like this: https://localhost/app/terminal1 Have you stepped into your tenant ID strategy to make sure the route parsing mechanism works right? That is, app isn't being picked up as the terminal value? Route parsing/handling can be tricky.
Possibly bad settings. The tenant ID strategy only successfully identifies a tenant if there are options that specify that the specific terminal value exists. I don't see where any of those options are configured, which means in this repo there are no tenants defined. Your strategy won't identify anything without that.
If it was me, I'd probably start with a breakpoint in that tenant ID strategy and see what's getting resolved and what's not. It seems somewhat complex from an outside perspective and that's where I'd begin. If that is working, then I'd probably also look at cleaning up the registrations so the ID strategy isn't registered twice. Finally, I get the impression that this isn't all the code in the app; I'd probably look at making a super minimal reproduction that's about the size you actually have posted here. I'd then focus on making that minimal repro work; then once it works, I'd figure out what the difference is between the repro and my larger app.
Unfortunately, that's about all I can offer you. As I mentioned, with the current environment and my current workload, I won't be able to actually sit down and reproduce the whole thing with your code. I know the integration works because I have production apps using it; and there are a lot of tests (unit and integration) to validate it works; so the part that isn't working is likely in your code somewhere... and those are the places I'd start.
So after having identified the tenant identification as the problem, it seems like RouteValues isn't resolved with the HttpContext until later in the request chain. Thus, no tenant gets resolved. It seems to me like a bug in .NET Core. The problem got bypassed by using the request path instead:
public class TerminalResolverStrategy : ITenantIdentificationStrategy
{
private readonly TerminalAppSettings settings;
private readonly IHttpContextAccessor httpContextAccessor;
public TerminalResolverStrategy(
IOptions<TerminalAppSettings> options,
IHttpContextAccessor httpContextAccessor
)
{
this.httpContextAccessor = httpContextAccessor;
settings = options.Value;
}
public bool TryIdentifyTenant(out object terminal)
{
var httpCtx = httpContextAccessor.HttpContext;
terminal = null;
try
{
if (httpCtx != null)
{
string thisPath = httpCtx.Request.Path.Value;
var allTerminals = settings.Terminals.GetEnumerator();
while (allTerminals.MoveNext())
{
if (thisPath.Contains(allTerminals.Current.Key)) {
terminal = allTerminals.Current.Key;
return true;
}
}
}
}
catch (Exception) { }
return false;
}
}

unexpected async await behavior in mstest unit test

I'm having newbie problems testing an async method. I've read a few other posts, including How to correct write test with async methods?, and I think I'm doing things correctly, but I'm clearly missing something.
Here's the code I'm trying to test:
/// <summary>
/// Temporary method used to simulate the time required to generate a report.
/// </summary>
public virtual async Task GenerateTestReportAsync()
{
++ActiveTaskCounter;
await Task.Delay(2000);
--ActiveTaskCounter;
}
And here's the test (yes, I could/should improve it by storing the ActiveTaskCounter values in a list, but that's beside the point):
[TestMethod]
public async Task GenerateTestReportAsyncUpdatesActiveTaskCounter()
var bayViewModel = CreateBayViewModel();
var invocationCount = 0;
bayViewModel.PropertyChanged += (sender, args) =>
{
if (args.PropertyName == "ActiveTaskCounter")
{
++invocationCount;
}
};
await bayViewModel.GenerateTestReportAsync();
//Thread.Sleep(2100); // TODO: Why is this needed?
Assert.AreEqual(2, invocationCount);
Assert.AreEqual(0, bayViewModel.ActiveTaskCounter);
}
The test always passes with the Thread.Sleep uncommented. It always fails with the Thread.Sleep commented, as shown above. Why is this? I assumed the code below the "await bayViewModel.GenerateTestReportAsync()" wouldn't even execute until GenerateTestReportAsync was really finished.
BTW, I'm using:
Microsoft Visual Studio Ultimate 2012
Version 11.0.51106.01 Update 1
Microsoft .NET Framework
Version 4.5.50709
Thanks for any help you can provide! This has me stumped :-|
EDIT: Here's a minimal repro of the view model class...
using System.ComponentModel;
using System.Threading.Tasks;
public class BayViewModel : INotifyPropertyChanged
{
public BayViewModel()
{
PropertyChanged = (sender, args) => { };
}
public event PropertyChangedEventHandler PropertyChanged;
private int _activeTaskCounter;
public int ActiveTaskCounter
{
get
{
return _activeTaskCounter;
}
set
{
_activeTaskCounter = value;
PropertyChanged(this, new PropertyChangedEventArgs("ActiveTaskCounter"));
}
}
public virtual async Task GenerateTestReportAsync()
{
++ActiveTaskCounter;
await Task.Delay(2000);
--ActiveTaskCounter;
}
}

Instantiate using Windsor's factory

Below's code is working fine, and successfully create an instance for class DummyComponnent.
But the problem arises when i had changed the factory method name CreatDummyComponnent()
to GetDummyComponnent() or anything else except Creat as the beginning of method name, say AnyThingComponent throws an exception. is there any specify naming rule for factory methods ?
using System;
using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
namespace AsFactoryImplementation
{
public interface IDummyComponnentFactory
{
IDummyComponnent CreatDummyComponnent();
// void Relese(IDummyComponnent factory);
}
public interface IDummyComponnent
{
void Show();
}
public class DummyComponnent:IDummyComponnent
{
public DummyComponnent()
{
Console.WriteLine("we are working here");
}
public void Show()
{
Console.WriteLine("just testing this for better performance");
}
}
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<IDummyComponnent>().ImplementedBy<DummyComponnent>().Named("FirstConnection"),
Component.For<IDummyComponnentFactory>().AsFactory());
var val = container.Resolve<IDummyComponnentFactory>();
var iDummy = val.CreatDummyComponnent();
iDummy.Show();
Console.WriteLine("OK its done ");
Console.ReadLine();
}
}
}
You should be able to use anything for starting the method names on the Factory, except for starting with Get.
If you start with Get it will try to resolve the component by name instead of by interface.
So what would work in your example is:
var iDummy = val.GetFirstConnection();
Good luck,
Marwijn.

Ninject does not inject dependency

having problem with my Ninject construct. May be somebody can show me where I am doing it wrong..
ok.. here is Module I have:
public class WebPageModule:NinjectModule
{
public override void Load()
{
Bind<TranscriptPageMediaWidgetViewModelForWebPage>().ToSelf().InSingletonScope();
Bind<TranscriptPageTranscriptWidgetViewModelForWebPage>().ToSelf().InSingletonScope();
Bind<WebPageTranscriptProvider>().ToSelf().InSingletonScope();
Bind<ITranscriptProvider>().To<WebPageTranscriptProvider>().WhenInjectedInto<TranscriptPageTranscriptWidgetViewModelForWebPage>();
//Bind<ITranscriptProvider>().To<WebPageTranscriptProvider>();
Bind<ITranscriptRendererWidget>().To<TranscriptPageTranscriptWidgetViewModelForWebPage>();
Bind<IMediaRendererWidget>().To<TranscriptPageMediaWidgetViewModelForWebPage>();
}
}
Then in NinjectWebCommons.cs I have:
private static IKernel CreateKernel()
{
var kernel = new StandardKernel(new WebPageModule(),new TweeterModule(), new BookmarkModule());
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Settings.AllowNullInjection = true;//http://stackoverflow.com/questions/10517962/using-default-parameter-values-with-ninject-3-0
RegisterServices(kernel);
return kernel;
}
then I use the property injection:
https://github.com/ninject/ninject/wiki/Injection-Patterns
in my "public class TranscriptPageTranscriptWidgetViewModelForWebPage : ITranscriptRendererWidget"
here it is:
[Inject]
public ITranscriptProvider TranscriptProvider
{
get { return _transcriptProvider; }
set { _transcriptProvider = value; }
}
but, when I am going into the constructor and trying to use _transcriptProvider it is NULL:
public TranscriptPageTranscriptWidgetViewModelForWebPage(string dataEndpoint, string focusCue)
{
InitParentInterfaceProperties();
Transcript = _transcriptProvider.GetTranscript(new Uri(dataEndpoint));
FocusCue = focusCue.Replace("*", "").ToLower();
}
Any ideas what I am doing wrong? thanks!
Al
Looks like you're trying to access the property within the constructor.
.NET's object creation semantics are such that this simply cannot be made to work (which is one of lots of good reasons to try very hard to achieve things with constructor injection unless you really are dealing with an optional dependency)

Can't get Ninject.Extensions.Interception working

I've been trying for ages to figure this our. when i try to bind my class with an interceptor i'm getting the following exception on the line
Kernel.Bind<MyClass>().ToSelf().Intercept().With<ILoggerAspect>();
Error loading Ninject component IAdviceFactory. No such component has been registered in the kernel's component container
I've tried with and without LoadExtensions, With about with using a Module to set up my bindings and my last attempt looks like this
internal class AppConfiguration
{
internal AppConfiguration( )
{
var settings = new NinjectSettings() { LoadExtensions = false };
Kernel = new StandardKernel(settings);
Load();
}
internal StandardKernel Kernel { get; set; }
public static AppConfiguration Instance
{
get { return _instance ?? (_instance = new AppConfiguration()); }
}
private static AppConfiguration _instance;
private void Load()
{
Kernel.Bind<ILoggerAspect>().To<Log4NetAspect>().InSingletonScope();
Kernel.Bind<MyClass>().ToSelf().Intercept().With<ILoggerAspect>();
}
internal static StandardKernel Resolver()
{
return Instance.Kernel;
}
}
My Logger Attribute looks like this
public class LogAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Context.Kernel.Get<ILoggerAspect>();
}
}
And my interceptor like this
public class Log4NetAspect : SimpleInterceptor, ILoggerAspect
{
protected override void BeforeInvoke(IInvocation invocation)
{
Debug.WriteLine("Running " + invocation.ReturnValue);
base.BeforeInvoke(invocation);
}
public new void Intercept(IInvocation invocation)
{
try
{
base.Intercept(invocation);
}
catch (Exception e)
{
Debug.WriteLine("Exception: " + e.Message);
}
}
protected override void AfterInvoke(IInvocation invocation)
{
Debug.WriteLine("After Method");
base.AfterInvoke(invocation);
}
}
Most likely you didn't deploy Ninject.Extensions.Interception.DynamicProxy or Ninject.Extensions.Interception.Linfu alongside your application [and Ninject.Extensions.Interception]. You have to pick exactly one of them.
With the code as you have it right now (LoadExtensions=false) it will fail to pick up the specific interception library - you should remove that and the normal extensions loading should wire the extension into the Kernel on creation for the interception bits to pick it up.
In addition to Remo Gloor's answer which pointed me toward adding the nuget package for Ninject.Extensions.Interception.DynamicProxy, I kept getting the same exception as the OP, until I manually loaded a DynamicProxyModule - the FuncModule is manually loaded as well, to work around a similar error involving the factory extension:
_kernel = new StandardKernel(
new NinjectSettings{LoadExtensions = true},
new FuncModule(),
new DynamicProxyModule()); // <~ this is what fixed it