I'm trying to figure out how to configure the enterprise library 5.0 Data Access Application Block.
When running my unittest, I get the following error:
Microsoft.Practices.ServiceLocation.ActivationException was caught
Message=Activation error occured while trying to get instance of type Database, key "PokerAdviserProvider"
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
Message=Resolution of the dependency failed, type = "Microsoft.Practices.EnterpriseLibrary.Data.Database", name = "PokerAdviserProvider".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type Database cannot be constructed. You must configure the container to supply this value.
The line of code where I get this:
var db = DatabaseFactory.CreateDatabase("PokerAdviserProvider");
App.config:
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
</configSections>
<dataConfiguration defaultDatabase="PokerAdviserProvider" />
<connectionStrings>
<add name="PokerAdviserProvider" connectionString="server=(localhost);Initial Catalog=PokerAdviser;uid=abc;pwd=xyz"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I've been googling around a bit and found some answers that these settings should also be put in the app.Config of my unittest-project, but that didn't make a difference.
I'm a bit stuck here, so any help is highly appreciated.
Edit:
I referenced the correct dll's (the ones from Program Files, not from the source code), so that isn't the problemneither.
I finally fixed this problem:
Error: Activation error occured while trying to get instance of type Database, key "<database name>"
Inner Exception: Resolution of the dependency failed, type = Microsoft.Practices.EnterpriseLibrary.Data.Database
I was running VS 2010 on windows 7, Enlib 5.0. The following worked for me. Wanted to spread the word around
Make sure you have proper reference to Microsoft.Practices.Unity.dll
Get the latest service pack for VS 2010
Finally figured it out. I use the DAAB in a class-library of my webservice and thought I had to create an app.config in that library. Should have know that this could not work. My mind was probably far far away when doing this...
I did the configuration in the web.config of the webservice and all runs smoothly now.
Refer to these two good posts post1 & post2 about Enterprise Library Configuration
Related
Running on Windows Server 2012 R2 Standard is a C# Windows Service (.Net Framework 4.7.2) using Entity Framework that I wrote which reads data from a file and passes the data to a local SQLExpress (2016) stored procedure to insert the data into the DB.
While testing on my Windows 10 machine it works fine, but after moving the executable and exe.config to the Windows Server and updating the config with the correct DB information in the connection string, the Event Viewer shows the following Windows Application Error:
Source: .NET Runtime Event 1026
Application: Print_Mail-DBAuger.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
at Print_Mail_DBAuger.Program.StartParseAndInsert(System.String, System.Diagnostics.EventLog)
at Print_Mail_DBAuger.FetchService.OnChanged(System.Object, System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.OnCreated(System.IO.FileSystemEventArgs)
at System.IO.FileSystemWatcher.NotifyFileSystemEventArgs(Int32, System.String)
at System.IO.FileSystemWatcher.CompletionStatusChanged(UInt32, UInt32, System.Threading.NativeOverlapped*)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
This seems to be preventing the stored procedure from being called, so no data is being passed to the DB.
I have narrowed the issue down to the instantiation of the Entity Data Model object:
PrintMailEntities dataEntities = new PrintMailEntities();
This line calls auto-generated code created by the Entity Framework:
public partial class PrintMailEntities : DbContext
{
public PrintMailEntities()
: base("name=PrintMailEntities")
{
}
// Several more auto-generated methods...
}
And the super class constructor (again, part of the Entity Framework, not my code):
public class DbContext : IDisposable, IObjectContextAdapter
{
//
// Summary:
// Constructs a new context instance using the given string as the name or connection
// string for the database to which a connection will be made. See the class remarks
// for how this is used to create a connection.
//
// Parameters:
// nameOrConnectionString:
// Either the database name or a connection string.
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public DbContext(string nameOrConnectionString);
// Other overrloaded constructors not used...
}
Everything in the program prior to this line works as desired (I used several application event logs to track what was happening since I don't have Visual Studio on the Windows Server to debug with.) The file I am trying to read from is not the issue, I can read that information fine.
I have also tried surrounding the instantiation with a try/catch to catch the FileNotFoundException, but the catch is never fired. I have also mirrored the database permissions of the Windows Server DB to match that of my local machines DB, and running both with admin privileges.
Here is the connection string in the Windows Server exe.config:
<connectionStrings>
<add name="PrintMailEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=machineName\HPWJA;initial catalog=PrintMail;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Again, this works fine on Windows 10 with the connection string pointed to a DB that mirrors the Windows Server DB. There are no build errors on my machine, and there are no SQL Server Logs on the Windows Server stating that anything wrong is happening on the DB side.
EDIT
Thanks to RB I now have more details about this "file" that couldn't be found. Here is the updated event log.
Error: Could not load file or assembly 'EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.
at Print_Mail_DBAuger.Program.StartParseAndInsert(String inputFile, EventLog programEventLog)
at Print_Mail_DBAuger.FetchService.OnChanged(Object sender, FileSystemEventArgs e)
EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 was missing.
The error seems to be referencing a section element in app.config
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
The server does not have internet, so maybe it's trying to pull the nuget package from online?
The issue was that I was missing the EntityFramework.dll found in the Release directory of the build output. Adding both EntityFramework.dll and EntityFramework.SqlServer.dll solved this issue. Thanks RB for helping me find this.
I tried to implement a single sign-on app following the tutorial here
http://geoffwebbercross.blogspot.com/2014/05/adding-azure-ad-single-sign-on-to.html
I added an active directory in azure and added a user for this tenant. Then I built a small app in VS2013. I used organizational accounts and typed in the domain name, logged in and created the project. While creating the project, there poped up a dialogue box said
Request_BadRequest: Invalid value found for property 'identifierUris' fo resource 'Application'
And I closed that. I tried to run the project on my local machine. It will have the information like this.
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Detailed Error Information:
Module
IIS Web Core
Notification
Unknown
Handler
Not yet determined
Error Code
0x80070032
Config Error
The configuration section 'system.identityModel' cannot be read because it is missing a section declaration.
Config File
Requested URL
http:
Physical Path
Logon Method
Not yet determined
Logon User
Not yet determined
Request Tracing Directory
D:\My Documents\IISExpress\TraceLogFiles\
Config Source:
34: </system.web>
35: <system.identityModel>
36: <identityConfiguration>
More Information:
This error occurs when there is a problem reading the configuration file for the Web server or Web application. In some cases, the event logs may contain more information about what caused this error.
If you see the text "There is a duplicate 'system.web.extensions/scripting/scriptResourceHandler' section defined", this error is because you are running a .NET Framework 3.5-based application in .NET Framework 4. If you are running WebMatrix, to resolve this problem, go to the Settings node to set the .NET Framework version to ".NET 2". You can also remove the extra sections from the web.config file.
View more information »
Any ideas of how to solve this issue?
I'm not sure what the root cause was (why you got the error while creating the project), but the following should resolve the error you're seeing when running the app.
In the the <configSections> section of your web.config you need to have the system.identityModel section defined. The entries should look something like this:
<configSections>
<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</configSections>
I'm trying to configure a console application with the following logging assemblies:
Common.Logging.dll (2.1.0.0)
Common.Logging.Log4Net1211.dll (2.1.0.0)
log4net.dll (1.2.11.0)
If the logger gets configured programmatically then everything works fine:
NameValueCollection properties = new NameValueCollection(); properties["showDateTime"] = "true";
Common.Logging.LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter(properties);
But if I try to launch it using the following configuration file, it blows up:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
<arg key="configType" value="FILE-WATCH"/>
<arg key="configFile" value="~/Log4NET.xml"/>
</factoryAdapter>
</logging>
</common>
</configuration>
These are the relevant error messages:
{"Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'."}
{"Failed obtaining configuration for Common.Logging from configuration section 'common/logging'."}
It seems to being unable to parse my configuration file, does anyone know what the correct format should be or is it something else that's wrong? I created my configuration file using the official documentation.
I was having this (or related) issue as well and after half a day of error hunting and debugging I narrowed it down to a configuration problem.
The exception was the same as the OP and the inner exception a few level inside of it was failing to find Common.Logging.Log4Net (FileNotFoundException).
It seems that for the Common.Logging.Log4Net1211 NuGet package, they have renamed the assemblyname to be Common.Logging.Log4Net1211 instead of simply Common.Logging.Log4Net. This means in your app.config you need to refer to this new assembly name:
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net1211">
Here's my entire common/logging section of app.config for reference:
<common>
<logging>
<!-- Notice that it's Log4net1211 -->
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net1211">
<arg key="configType" value="FILE-WATCH" />
<arg key="configFile" value="~/Log4Net-MAIN.config" />
</factoryAdapter>
</logging>
</common>
There are two problems with your application (the one I downloaded):
Your configSections in app.config looks like this:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
Notice that the log4net-section is declared twice? Remove the first one.
After removing the first log4net-section, I get the following:
Could not load file or assembly 'log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
I downloaded log4net 1.2.11.0 from the log4net website, unzipped it, unblocked the dll and replaced the log4net in your example and it seems to work.
I'm using
Common.Logging v3.3.1.0
with
Common.Logging.Log4Net1213 v3.3.1.0
in ASP.NET Web API v5, which throws exception
"parent configuration sections are not allowed"
Exception is thrown from Common.Logging.ConfigurationSectionHandler.Create method
In order to make this work, I had to grammatically configure the adapter
var properties = new Common.Logging.Configuration.NameValueCollection();
properties["configType"] = "INLINE";
Common.Logging.LogManager.Adapter = new Log4NetLoggerFactoryAdapter(properties);
I still have to figure out why IIS/Express calls the Create method twice, which is causing the exception to be thrown inside the if condition, but at least the pressure is off for now.
I got it working by installing a missing package
Install-Package Common.Logging.Log4Net1211
Although this is an old question, I had this issue a few weeks and none of the current answers seemed to remedy it. It seemed my configuration was correct as I had many other applications using near identical configuration with no issue. After quite a bit of debugging and running through stacktraces, I finally found the issue.
Notice that in IIS, I have the API application hosted under another application. In this case both the CAMP application and the API application under it are both using Common.Logging. Because of this, both web.config files get loaded, Common.Logging reads CAMP's configuration, then it sees that API has configuration and tries to read that as well, sees the Common.Logging section and throws up because it already read that from the CAMP application.
In the end the solution was to move the API out from under the CAMP application in IIS. A bit of an obsucre edge case, but perhaps someone else might face this issue some day.
Can you try with Common.Logging.dll version 2.1.1.0 instead.
You can download and compare the source of the two versions yourself, but as far as I can see the only difference between 2.1.0.0 and 2.1.1.0 is a change relating to reading the configuration settings in order to workaround a Framework 4.0 bug. The description of the bug (see http://support.microsoft.com/kb/2580188) refers to running from a network share which I am not running from a network, yet a test app using 2.1.0.0 generates the same error as you are getting whereas 2.1.1.0 doesn't.
If you are using another library that expects version 2.1.0.0 of common.logging.dll, then you should be able to using an assembly redirect to use 2.1.1.0 instead.
PS
Not sure whether it is relevant, but I left the name of the dll as Common.Logging.Log4Net121.dll and modified the app.config instead
I found that it was due to the Common.Logging.Log4Net1211 NuGet package retrieveing an older version of Common.Logging. Check for NuGet updates to Common.Logging and if you find one download it and try again.
If your log4net is 2.0.6 or above, it may be convenient to use Common.Logging.Log4Net.Universal package.
I have been looking into refactoring some old code into a new WCF service, based on net 4.0 and have into a little difficulty with what should be a simple exercise!
The scenario;
WCF Service hosted over HTTP, implementing our ServiceContract, which connects to a local Sql Server.
When attempting to run a simple NUnit test against the Service Call, I get the following error;
* HelpManager.Tests.GetPage.GetPageById Fault
Exception:
System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]:
Activation error occured while trying to get instance of type
Database, key "HelpManagement" (Fault Detail is equal to An
ExceptionDetail, likely created by
IncludeExceptionDetailInFaults=true, whose value is:
Microsoft.Practices.ServiceLocation.ActivationException: Activation
error occured while trying to get instance of type Database, key
"HelpManagement" ---->
Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the
dependency failed, type =
"Microsoft.Practices.EnterpriseLibrary.Data.Database", name =
"HelpManagement". Exception occurred while: while resolving. Exception
is: InvalidOperationException - The type Database cannot be
constructed. You must configure the container to supply this value.
----------------------------------------------- At the time of the
exception, the container was:
Resolving
Microsoft.Practices.EnterpriseLibrary.Data.Database,HelpManagement
----> System.InvalidOperationException: The type Database cannot be
constructed. You must configure the container to supply this value.
at
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimiti...).
Our (pretty standard) WCF web.config for this, looks like;
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/>
</configSections>
<dataConfiguration defaultDatabase="HelpManagement"/>
<connectionStrings>
<add name="HelpManagement" connectionString="server=(local);database=ieq;uid=;pwd=" providerName="System.Data.SqlClient"/>
</connectionStrings>
and an example of the code used to call it;
private const string DB_HelpManagement = "HelpManagement";
var db = DatabaseFactory.CreateDatabase(DB_HelpManagement);
Google et al have been no fun. I have checked versions etc and they all appear to be referencing the same 5.0.14 from GAC, so unsure as to what the problem is.
Thanks in advance
I wonder about Microsoft.Practices.ObjectBuilder.dll and Microsoft.Practices.EnterpriseLibrary.Common -- are they referenced in the WCF project?
It sounds like it might be your configuration. Did you specify the dataConfiguration defaultDatabase value in your config file (e.g. web.config)?
Building a simple asp.net web app just to test things out (will obviously refactor before anything gets built for a production site), and I'm trying to connect to a mysql database using the latest version of the Enterprise Library, and am running into an error:
"The type MySqlClientFactory does not contain the ConfigurationElementTypeAttribute."
I've gone through several different forms of trying to set up the configuration, and based on everything i've found, distilled it down to this:
in my web.config i've got this:
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<dataConfiguration defaultDatabase="MyDB">
<providerMappings>
<add name="MySql.Data.MySqlClient" databaseType="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data,Version=6.3.6,Culture=neutral,PublicKeyToken=c5687fc88969c44d"/>
</providerMappings>
</dataConfiguration>
<connectionStrings>
<add name="MyDB" connectionString="Server=localhost;Database=MyDB;Uid=root;Pwd=****;"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
and in my default.aspx page I've got this:
protected void Page_Load(object sender, EventArgs e)
{
string sql = "select * from users";
Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("MyDB");
var reader = db.ExecuteReader(CommandType.Text, sql);
while (reader.NextResult())
{
Response.Write(reader["userName"] + "<br />");
}
}
so, very simple... but again, the error i'm getting is:
"The type MySqlClientFactory does not contain the ConfigurationElementTypeAttribute."
and I can't find any reference to that... the MSDN doesn't say much about that attribute, and what it does say I can't seem to relate to what i'm doing... any help would be appreciated.
Thank you!
EntLib doesn't support MySql out of the box. EntLibContrib has a proper MySql Data Provider. The one released, however, targets EntLib4.1. I can see a porting effort to v5.0 is under way but the Data Access block doesn’t appear to be done yet. You may need to port yourself.
The factory you are using doesn't seem to be EntLib-enabled. You can find a good treatment of the ConfigurationElementTypeAttribute as well as other guidance on how to extend EntLib in the Enterprise Library Extensibility Hands-on Labs.