Microsoft Unity XML configuration for Interception - unity-container

I've been trying to configure interception for Unity (I want to log to log4net before and after object method calls).
I've used this example:
http://www.codeproject.com/KB/architecture/UnityAOPNHibernate.aspx
and its similar to this answer:
Microsoft Unity - code to xml
but I get "Unrecognized element 'extensionConfig'." - on the line where it does GetSection("unity") below.
IUnityContainer unityContainer = new UnityContainer();
var configurationSection =
(UnityConfigurationSection)ConfigurationManager.GetSection("unity")
Please help

You need to add a section extention for this to work
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
...
Refer page 60 of Unity20.PDF for the documentation

Related

Setting Bugsnag configuration options in code

In the documentation it says that I can do the following in code to further configure my integration:
Each key provides an in code example and a config file example.
configuration.ReleaseStage = "development";
What I am trying to do is:
public static void Register(HttpConfiguration config)
{
var configuration = Bugsnag.ConfigurationSection.Configuration.Settings;
configuration.ReleaseStage = ConfigurationManager.AppSettings["Environment"];
config.UseBugsnag(configuration);
}
However, the configuration properties are read-only (don't have setters).
The alternative is to add the configurations to the Web.config:
<bugsnag apiKey="your-api-key" releaseStage="development">
The problem is that I am reading my environment from the AppSettings and therefore cannot do it this way.
Is it possible to do the configuration in code and if so, how?
UPDATE: Since posting the question I have found the issue on GitHub.
From the GitHub issue it seems as if this isn't possible so I used the work around suggested by one of the project's contributors.
The only work around I can suggest right now is to use the core Bugsnag nuget package...
I removed all the 'old' code, uninstalled all the NuGet packages except for the base Bugsnag and added the following code to the OnException override method where I had been logging exceptions up until now.
var configuration = new Configuration("API_KEY")
{
ReleaseStage = myReleaseStage
};
var client = new Bugsnag.Client(configuration);
client.Notify(new System.Exception("Error!"));
This worked and errors are now logged along with the environment in which they occurred. My next step will be to refactor this work around so that client is available globally but for now this solves my in code problem.
From Bugsnag's latest Go documentation, you can programmatically set the release stage. In your example, it would look like this:
configuration.ReleaseStage = ConfigurationManager.AppSettings["Environment"];

How to get appsettings from project root to IDesignTimeDbContextFactory implementation in ASP.NET Core 2.0 and EF Core 2.0

I am building an application in ASP.NET Core 2.0 and I am having problems with EntityFramework Migrations.
I have my DbContext in a separate project (SolutionName\ProjectNamePrefix.Data) and therefore I created an implementation for the IDesignTimeDbContextFactory interface.
I wanted to use different connection strings for different environments and I need appsettings.json for that.
So after a quick search I found that I can create a new IConfigurationRoot object inside the CreateDbContext function as shown here:
https://codingblast.com/entityframework-core-idesigntimedbcontextfactory/
I added that and then for testing, tried to run dotnet ef migrations list -c MyContext from the Data project root folder.
Then I got the following error:
The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\dev\*SolutionName*\*ProjectNamePrefix*.Data\bin\Debug\netcoreapp2.0\appsettings.json'.
So, basically, I tried 3 options for getting the correct root path:
Directory.GetCurrentDirectory();
env.ContentRootPath; (IHostingEnvironment object, I found a way to get it here: https://github.com/aspnet/Home/issues/2194)
AppDomain.CurrentDomain.BaseDirectory;
and all of them returned the same ..\bin\debug\netcoreapp2.0\ path. When I run the Data project from VS, then the two first options give me the correct project root folder.
Is there a way to get the correct project content root folder?
Because when I added --verbose to the EF command, it logged out a row:
Using content root 'C:\dev\FitsMeIdentity\FitsMeIdentity.Data\'.
So I understand that EF somehow knows the project root but all the options mentioned above return the path for the already built application.
The only option I found that works is that I change Copy output to root folder to Copy always but found from here: https://www.benday.com/2017/02/17/ef-core-migrations-without-hard-coding-a-connection-string-using-idbcontextfactory/ that it's not a good idea.
At first I even thought about creating a Constructor for the IDesignTimeDbContextFactory implementation which gets IOptions as a parameter but that didn't work, had the same problem as explained here:
Injecting Env Conn String into .NET Core 2.0 w/EF Core DbContext in different class lib than Startup prj & implementing IDesignTimeDbContextFactory
A little late, but here is the solution for those who hate hard-coding connections strings:
internal class MigrationDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false)
.Build();
string connectionString = configuration.GetConnectionString("DefaultConnection");
DbContextOptionsBuilder<AppDbContext> optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
optionsBuilder.UseMySql(connectionString,
ServerVersion.AutoDetect(connectionString),
mySqlOptions =>
mySqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null));
return new AppDbContext(optionsBuilder.Options);
}
}
No. You can't do this, and more to the point: you're not supposed to do this. The whole entire point of IDesignTimeDbContextFactory is that it's a way to get a DbContext instance from in a context where there is no ASP.NET Core framework to work with, i.e. from a class library. If you're running migrations from an ASP.NET Core project, you don't need it, and if you're not, none of the configuration stuff is available.
Additionally, it's only to be used for development, hence the "DesignTime" part of the name. As a result, there's no need for stuff like switching between connection strings for different environments. Just hard-code the connection string as the docs detail.

can't register objects using unity 2.0

I created a web service recently and am using unity to inject my object dependencies. My composition root is the Application_Start in the web services and am using the web.config to do my object to interface mappings. Everything was working fine, however after i loaded my project into tfs i keep getting an error stating that it cant resolve one of the interfaces. I removed the code to register my objects from the web.config and regsistered them in code instead to test and it all works fine. Any ideas what the problem is. Any ideas how i can troubleshoot this problem.
Before TFs :-
UnityContainer uContainer = new UnityContainer();
UnityConfigurationSection Section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
Section.Configure(uContainer, "CentralRepositoryContainer");
Application["uContainer"] = uContainer;
Amended code which works fine :-
UnityContainer uContainer = new UnityContainer();
uContainer.RegisterType<ICentralRepositoryLifeTimehelper, CentralRepositoryLifeTimeHelper>();
uContainer.RegisterType<IJobsHandler, JobsHandler>();
Application["uContainer"] = uContainer;
I don't know the problem, but to troubleshoot print out all the Unity containers registrations and see what's missing/changed.
Use the code sample from Retrieving Container Registration Information

eventlog not working in an asp.net application

from an ASP.Net 3.5 web application, I'm trying to log messages to the Windows EventLog.
I first tried with the EntLib Logginh block, but when this failed I tried with the EventLog class directly. It failed too. They do not throw any exception... the just don't write the message. EntLib did write the message to a file, but not to the Windows EventLog.
Here is my code:
public static void LogMessage(string title, string message){
//EventLog log = new EventLog();
//log.Source = LOG_SOURCE;
//log.WriteEntry(message, EventLogEntryType.Error);
//EventLog.WriteEntry(LOG_SOURCE, message);
LogWriter writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
writer.Write(message);
}
I create the log & source in an installer class. Let me know if I should place that code here. The log is created correctly, since I can see it in the EventViewer. The source is created correctly, since I can see it in the "EventLog\MyLog" folder at the regedit.
I've been reading and there is an article stating following line could help:
EventLogPermission perm = new EventLogPermission(EventLogPermissionAccess.Administer, ".");
perm.PermitOnly();
but it didn't.
If it helps, my code structure is as follows:
Class library project (here is the LogMessage method)
Class Library project (here are the methods which catch exceptions and call LogMessage)
ASP Net web application project (web pages. This layer calls layer #2. Here is my installer class too)
Web setup project (this has custom actions pointing to web setup project output)
Could you please help to figure out what's happening???
Thanks
I found the following resource: "http://www.netframeworkdev.com/net-base-class-library/trouble-writing-to-eventlog-16723.shtml", so it seems it is not possibly to create custom logs from ASP... still investigating
Try giving the Network Service account the appropriate permissions

simple webservice code?

i write a simple webservice code in asp.net when i build the service and run the service it is working fine. when i try to access the webservice it is giving some problem , problem means i am not getting that method (webservice method). After completing writing the webserivce i take a asp.net page (.aspx) and in solution explorer i add a webservices and it is added successfully. but when i adding namespace it is not getting the service name ( i not able to add the namespace of websercice
I am not exactly sure what could be the problem but you should only need to do the following to use the web service:
// Look at what you named your web reference, in my example it is
// called MyWebService. Check your solution explorer for the actual name.
// This is the alias you should be using.
MyWebService.YourWebServiceName ws = new MyWebService.YourWebServiceName();
var result = ws.MyMethod(someparameter);

Resources