Read Config From Another Project - Log4Net ASP.NET Core 3.1 - asp.net-core

I am trying to write a class library that uses log4net that looks something like this:
public class Logging
{
private ILog log4netLogger = null;
public Logging(Type type)
{
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead("log4net.config"));
var repo = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
log4netLogger = LogManager.GetLogger(type);
}
public void Debug(string message)
{
log4netLogger(message);
}
public void Info(string message)
{
log4netLogger(message);
}
}
However, the xml configuration is in my test console app in C:\....\TestLogging\TestLog4Net\bin\Debug\netcoreapp3.1. I actually started with this console app to test log4net but I have moved all my code from the main method of Program.cs to the Logging.cs constructor, but I think the LogManager will not be able to find this now.
Is this at all possible?

I think it is possible. To use the log4net in the class library, you have to install the log4net package in the class library, then, you could add the class library reference in the console application and use the class library method. But, as you said, the log4net.config file should be in the console application netcoreapp3.1 folder, otherwise, the class library will not find the log4net.config file:

Related

Use Ninject in both main and referenced projects

I have MVC4 website project and WCF project, both using Ninject.
I want to use class from WCF project in website project. I add reference to project and get both NinjectWebCommon.Start() executing (with "The static container already has a kernel associated with it!" error).
Is there way to make what I want?
Solved this using this startup in referenced project
public class Global : NinjectHttpApplication
{
protected override IKernel CreateKernel()
{
return new StandardKernel(new ServiceModule());
}
}

ASP.NET MVC4 StructureMap ExceptionCode202

I'm in the process of converting an ASP.NET MVC3 (LinqToSQL, EntityFramework) project to MVC4. I've created a fresh MVC4 project in VS2012, added packages, copied my Views, Controllers, etc.
Most things seem to work fine except when I try to access a controller that makes use of a Respository, as follows:
public class CustomerController : Controller
{
private ICustomerRepository _cr;
public CustomerController()
{
this._cr = new CustomerRepository(TTDataProvider.DB);
}
public CustomerController(ICustomerRepository customerRepository)
{
this._cr = customerRepository;
}
if I'm in VS2012 and debugging, what I'll get is an exception: "Activation error occured while trying to get instance of type CustomerController, key """. The exception is of type Microsoft.Practices.ServiceLocation.Activation and the Inner Exception is: "StructureMap Exception Code: 202\nNo Default Instance defined for PluginFamily TTLW.Models.TTLWDataContext, TTLW, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"}.
My IoC code is:
using StructureMap;
using FluentSecurity;
using System.Diagnostics;
namespace TTLW {
public static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.TheCallingAssembly();
scan.WithDefaultConventions();
scan.AddAllTypesOf<IPolicyViolationHandler>();
});
});
return ObjectFactory.Container;
}
}
}
And here's StructureMapMVC.cs
using System.Web.Http;
using System.Web.Mvc;
using StructureMap;
using TTLW.DependencyResolution;
[assembly: WebActivator.PreApplicationStartMethod(typeof(TTLW.App_Start.StructuremapMvc), "Start")]
namespace TTLW.App_Start {
public static class StructuremapMvc {
public static void Start() {
IContainer container = IoC.Initialize();
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = DependencyResolver.Current.ToServiceResolver();
}
}
}
As I say, this was all working without problems in my MVC3 application (although I was of course using the MVC3 version of StructureMap).
Once I hit the exception, if I just choose to continue then everything works (i.e. the controller functions); this is confirmed by choosing "Start Without Debugging" instead of "Debug". When I do that there is no exception thrown and things work as designed.
I've searched and come across posts from Phil Haack, Brett Allred and others (in fact I've already incorporated Allred's code in the last line of StructureMapMVC) but haven't found a solution. I can't consider the project converted as long as this exception is staring me in the face.
I've included all the code and messages I think are reasonable and would appreciate any insights. If you need to see more just let me know.
Thanks in advance.

EJB Injection failure on deploy

I've got a problem exxh EJB's.
First of all, my setup: I am using GlassFish & JEE6. I have got a REST-Service packaged as a WAR and a bean packaged as an EJB-Jar. They are not inside an EAR.
The EJB should be used from the REST-WAR via #EJB, but when I try to deploy the WAR, GlassFish shows this error:
Error occurred during deployment:
Exception while deploying the app [exx-upload-1.0] : Cannot resolve reference Local ejb-ref name=com.ex.exx.model.FileUpload/ocr,Local 3.x interface =com.ex.exx.api.IOCRService,ejb-link=null,lookup=,mappedName=,jndi-name=,refType=Session. Please see server.log for more details.
(The EJB was deployed before without any erros).
I have no clue why. Here is the EJB Code:
Interface:
#Local
public interface IOCRService {
public String performOCRonImage(BufferedImage input);
}
and Implementation:
#Stateless
#LocalBean
public class OCRScanner implements IOCRService {
private Logger logger = Logger.getLogger(this.getClass().getName());
private final static String NOT_RECOGNIZED = "Can not regocnize text";
/**
* Default constructor.
*/
public OCRScanner() {
logger.log(Level.INFO, "### OCR SCANNER BUILD" + this);
}
public String performOCRonImage(BufferedImage input) {
logger.log(Level.INFO, "### OCR SCANNER CALLED" + this);
}
...
And here is the important part in the WAR:
public class FileUpload {
private final File PROPERTIES_FILE = new File(
"fileUploadProperties.properties");
private final String PARAMETER_NAME = "file";
private final Logger logger = Logger.getLogger(this.getClass().getName());
#EJB
private IOCRService ocr;
public Response uploadFile(...) {
// do some stuff
logger.log(Level.INFO, "### EJB" + ocr.toString())
}
Anny suggestions? I can not find my failure here.
Solved this, by replaceing #Local with #Remote.
This works, however, I am not satisfied as I do not understand why.
Basically, given the specs (eg. explained in the tutorial), an application can only access other application's EJB, if they are decorated with #Remote.
Thus, you have 3 options:
decorate your EJB with #Remote (what you have done),
package both together inside an ear (as they would reside in the
same application then). But if you intent to deploy them in seperate
applications or even seperate servers, use 1.)
use CDI with #Inject, but this will still only discover the EJB if
either in the same application, or decorated as #Remote if not.
HTH,
Alex
You should not use #EJB if the target is not an EJB. I guess this is your case because you are trying to inject into a class in your WAR.
Instead use:
#Inject
private IOCRService ocr;
Basically, #Inject is better in most cases, because:
it is more typesafe,
it supports #Alternatives
it is aware of the scope of the injected object.
Another solution it's to add #Stateless(name=""), this worked form

Cannot access RavenDB Management Studio

Try:
I created a new project in VS2012
I installed via the NuGet package RavenDB Embedded -Pre
I installed Ninject.MVC3
Added a module for ninject RavenDB:
Public class RavenDBNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IDocumentStore>().ToMethod(context =>
{
NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8080);
var documentStore = new EmbeddableDocumentStore { Url="http://localhost:8080/", DataDirectory="~/App_Data", UseEmbeddedHttpServer = true };
return documentStore.Initialize();
}).InSingletonScope();
Bind<IDocumentSession>().ToMethod(context => context.Kernel.Get<IDocumentStore>().OpenSession()).InRequestScope();
}
}
In my class "NinjectWebCommon" ...
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new RavenDBNinjectModule());
}
When running the application, the following url was generated ("http://localhost:1423")
Verify that the file "Raven.Studio.xap" was the root of my application
I tried accessing "http://localhost:8080" but the following screen is displayed:
What am I doing wrong?
As it turned out, the issue is that documentStore.Initialize never get called, because that no one did ask Ninject to resolve IDocumentStore.
You are setting the Url property, which means that you aren't running in embedded mode, but in server mode.
Remove the Url property, and everything will work for you.
I found the problem!
Since he had used IDocumentSession in no time, the ninject had not created the instance of IDocumentStore and thus not run the Initialize method

How to share fluent configuration in a Castle Windsor IOC container

I am trying to create an IOC container in Castle Windsor that's configuration is shared across assemblies.
(What follows is an example of how this works in Unity. What I want to do is to make it work the same way using Castle Windsor)
I have the following project configuration...
TestCompany.Services.Host
(Web project hosting a number of .svc files)
PrintService.svc
Web.Config
Unity.Config
TestCompany.Services.PrintService
IPrintService.cs
PrintService.cs
The actual implementation of my "PrintService" is not implemented inside my Services.Host but in the TestCompany.Services.PrintService assembly.
As part of my shared project code (not shown) I have a container helper which is responsible for loading the unity configuration...
public static IUnityContainer GetContainer()
{
// Checks for existance of container (_container == null) ommitted.
var section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
section.Configure(_container, name);
...
...
}
This method loads the unity configuration section from the Unity.Config and uses it to configure the container.
The advantage of this method is that one Unity.Config loaded inside (I presume) the AppDomain can service a number of assemblies. Simply calling GetContainer() from any of the assemblies consumed by my service host will return a container populated with the same type resolution's etc.
I really want to use the fluent configuration in Castle Windsor but I dont see how without this "shared" configuration file that can be acheived. PrintService and any future services will all need to resolve the same dependencies and I dont want to have to repeat my fluent configuration between these services.
Ideally I need some sort of container configured in the service host app that can "flow" into all of the assemblies that it makes use of.
Thanks.
I think I may not be understanding your question but I think I understand your scenario and here is how I do something similar, if it helps at all...
My Philosophy:
Each part of the application should be in charge of registering what
it knows about and nothing more, so there is no need for a single
central configuration file and things that are shared between
components are registered in one place and their interfaces are
available everywhere via a common library.
So let's take an example...
First of all, let us just say (for the purposes of my example) that IPrintService is something that you want to register an implementation of once and use throughout the application and that we have some other component that needs to be implemented by some external module from the main application. We, therefore, create an assembly called Common like so:
Common
public interface IPrintService
{
void Print();
}
public interface IMyService
{
void DoSomething();
}
Now let us think about the main part of the application (maybe it is an ASP .NET application, maybe justa console application, does not really matter). Here we construct the container and ask it to find all the possible components. We can do that like so:
Main Application
// Could be the Global.asax code behind but for simplicity this is
// just a console application
class Program
{
private static readonly IWindsorContainer Mycontainer
= BootstrapContainer();
// Allow access to the raw container - this is probably a bad idea but
// in the rare case that you need it you can get it from here
public static IWindsorContainer Container { get { return Mycontainer; } }
private static IWindsorContainer BootstrapContainer()
{
// Here we will just install every IWindsorInstaller found in any
// assembly in the same folder as the application (so no need for
// references or anything).
var c = new WindsorContainer();
string folder = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
c.Install(FromAssembly.InDirectory(new AssemblyFilter(folder)));
return c;
}
}
// Here is the print service implementation
public class MyPrintService : IPrintService
{
public void Print()
{
// Print!
}
}
// This is the installer for the main module - here we are saying exactly
// what is implementing the interface
public class MainApplicationInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container,
IConfigurationStore store)
{
container
.Register(Component
.For<IPrintService>()
.ImplementedBy<MyPrintService>());
}
}
So now we have a common library with our shared inetrfaces and a main application that will register an implementation for our shared interface and also load up any other modules in the system.
The only thing, therefore, left to do is to consume that print service and use it. We can do this anywhere that is using the container so let's create a third assembly that references only Common (we will call it test module.
Test Module
// This installer installs just the things inside this module since that
// is all it knows about but those things can use things that are
// registered in the container by anybody.
public class TestModuleInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container,
IConfigurationStore store)
{
container
.Register(Component
.For<IMyService>()
.ImplementedBy<MyServiceThatDoesSomething>());
}
}
public class MyServiceThatDoesSomething : IMyService
{
private readonly IPrintService _printService;
public MyServiceThatDoesSomething(IPrintService printService)
{
_printService = printService;
}
public void DoSomething()
{
// Use the print service!
_printService.Print();
}
}
Finally compile everything and copy the test module to the same folder as the main application and then from the main you can do this:
Container.Resolve<IMyService>().DoSomething();
And then the magic happens! Well, some code runs and you find that the print service is called by the class from the module even though it knows nothing about it.
Anyway, maybe that helps a little bit, maybe not, good luck!