MySQL 6 connection with Enterprise Library Data 5 - c#

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.

Related

Exception Thrown: 'System.IO.FileNotFoundException' in C# Windows Service When Entity Data Model Object Instantiated

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.

The provider did not return a ProviderManifestToken string Entity Framework

An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
Inner Exception: {"The provider did not return a ProviderManifestToken string."}
I've searched other threads as there are many with similar errors, but I cannot seem to find a solution.
I am using VS2012 Professional and SQL Server 2012. I am able to connect to the server using Server explorer using windows authentication. I am building a webforms application with multiple tiers. One of them containing my Entity framework tier which contains my Context class.
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<connectionStrings>
<add name="MYSQLSERVER"
providerName="System.Data.SqlClient"
connectionString="Data Source=myComputer\MYSQLSERVER;Trusted_Connection=true"></add>
</connectionStrings>
</configuration>
This is what the app.config in my Entity Framework class library layer looks like.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
Also, I have tried changing the app.config defaultConnectionFactory type to
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
but it did not change anything.
I am not really sure what any of the changes I am making even mean which worries me. Sure I could of found the solution online and fixed my issue, but I would really like to understand the web.config and what this all means. On top of finding a solution to this problem, can anyone point me in the right direction to learning web.configs?
Thank ahead for your help.
In my case, it was my SQL Server instance that was not running. I simply started the service and everything worked fine. Hope this helps someone down the road.
I also faced to this error and I solve that downgrading these NuGet packages
MySql.Data - 6.9.12
MySQL.Data.Entity - 6.8.8
this is my reference URL which I referred
Well I fixed it.
Just needed to put "." for localmachine in the data source as follows:
<add name="MYSQLSERVER"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\MYSQLSERVER;Trusted_Connection=true"></add>
</connectionStrings>
Here's another possible cause:
I have both my (ASP.NET) HTTP server and MySQL/Aurora server on AWS (understood that AWS was not part of the OP's comments).
My desktop's (actually, our building's) IP was whitelisted in the MySQL/Aurora server's security group, so everything worked perfectly for development.
But the ASP.NET server's IP was not whitelisted for the MySQL/Aurora instance, thus the ASP server's EF connection request was being rejected, and that was causing the exception noted at the top of this thread.
Esoteric, but maybe this helps someone.
For those getting this recently, in updating to MySql.Data 8.0.19 you also have to update your references for EntityFramework, Oracle changed the package, it's now MySql.Data.EntityFramework instead of MySql.Data.Entity or MySql.Data.Entities. Props to David Sekar: https://davidsekar.com/asp-net/mysql-error-the-provider-did-not-return-a-providermanifesttoken
For me, It was all of the below.
1. DB not allowed to connect to my dev environment. May be firewall restrictions.
2. Connection string had wrong credentials for the DB.
So generally speaking, incorrect connection string.
i meet this problem when i try to connect to mysql, the reason is that i forget to add the "password" in "connectionStrings"
In my case the paramter was v12.0, I changed to v11.0 and it is working
I had the same problem, reinstalling Npgsql with the package manager did the trick.
Seemed to be a versionning problem.
For me, it was using double backslash between the server and the instance, such like .\SQLExPRESS;...etc.
The correction was to use .\SQLEXPRESS
hope it helps someone.
I often forget why this error comes often. For me its usually I have changed credential of the database and did not change the same on the code section.
Just in case if I come here again to remind myself.
..and FINALLY(?!?) don't forget to build your project with 'Prefer 32-bit' checked as this will eliminate the KNOWN BUG which generates this error message (which has the inner exception message = 'Arithemtic overflow')

EF 5 Migrations cannot connect to our database even though it does just fine at runtime

We have three projects.
Company.Domain (class library)
Company.PublicWebsite (MVC3 Web Application)
Company.InternalWebsite (MVC3 Web Application)
The two website projects have reference to Company.Domain.
Our EF 5 DbContext lives in Company.Domain.Data.EntityFramework and it looks like this:
using System.Data.Entity;
using Company.Domain.Data.EntityFramework.Entities;
namespace Company.Domain.Data.EntityFramework.
{
public class CompanyEntities : DbContext
{
public DbSet<Notification> Notifications { get; set; }
public DbSet<Report> Reports { get; set; }
public DbSet<ReportSection> ReportSections { get; set; }
public DbSet<ReportPage> ReportPages { get; set; }
// brevity brevity
}
}
We have enabled migrations and successfully used the tool in the past so I'm not sure why we are having issues now. Our migrations configuration lives in Company.Domain.Data.EntityFramework.Migrations and looks like this:
namespace Company.Domain.Data.EntityFramework.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using Company.Domain.Data.EntityFramework;
public class Configuration : DbMigrationsConfiguration<CompanyEntities>
{
public Configuration()
{
MigrationsDirectory = #"Data\EntityFramework\Migrations";
AutomaticMigrationsEnabled = false;
}
protected override void Seed(CompanyEntities context)
{
// empty at the moment
}
}
}
We then have an App.config file in the root of the Company.Domain project and it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="CompanyEntities" providerName="System.Data.SqlClient" connectionString="Data Source=devsql;Initial Catalog=CompanyEntities;uid=XXXXX;pwd=XXXXX;MultipleActiveResultSets=True;" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Our database lives on another server on the network. I'm able to connect to it in SQL Server Management Studio and our applications are able to connect at runtime just fine. However, when I try to run add-migration or even update-database I get the following error:
http://content.screencast.com/users/Chevex/folders/Snagit/media/80fbfd6a-4956-407f-b88f-d5a53a9e5feb/03.21.2013-10.25.png
System.Data.ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. ---> System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
I've even reverted my changes to the model and then ran update-database just to see if it would say 'database is on latest migration' but I still got the above error. I've poured over the connection string in App.config over and over. I cannot figure out why migrations won't connect but both of our website projects work just fine at runtime. Migrations have worked in the past. Below are the migrations in solution explorer compared with those found in the __MigrationHistory table in the database.
http://content.screencast.com/users/Chevex/folders/Snagit/media/7abeaa46-ff0f-4817-a0d7-1adb086e8f0c/03.21.2013-10.30.png
http://content.screencast.com/users/Chevex/folders/Snagit/media/3c6ac54d-f63d-417f-9253-39b6a8fea85d/03.21.2013-10.32.png
It looks like I should be able to run update-database and have it tell me that it is up to date, but I get that error instead.
As I understand it, migrations shouldn't be paying any attention to our two website projects when I'm running migrations commands, but I poured over their Web.config files as well just in case. The connection strings are identical to App.config.
Edit:
I've even tried completely uninstalling and removing the EF 5 package from the projects and reinstalling. Same issue >:(
Did your start project contains web.config or app.config as EF use the start project as source of the connection string
OK, so that didn't work for me at first :(
Then after a cup of coffee and adding StartUPProjectName to it, it did!
Try:
Update-Database -StartUpProjectName MYPROJECT.NAME -Script
Try to point it to a start Up project where you web.config/app.config lives
If you get the help for enable migrations in the Package Manager Console
Get-Help enable-migrations -detailed
You can find this documentation for the -StartupProjectName option:
-StartUpProjectName
Specifies the configuration file to use for named connection strings. If
omitted, the specified project's configuration file is used.
The doc it's a little confusing, but it means that if you use this option to specify a project name, migrations will look for the connection string in the config file of the specified project. (The config file can be web.config or app.config).
If you're creating a web app, most probably the connection string will be in its web.config, so you have to specify the web app project. If it's other kind of project, the connection string will be in an app.config file of a class library or whatever, and you'll have to specify that project.
Besides it's recommended that you use a constructor for your DbContext class that specifies the name of the connection string, i.e.
public class CompanyEntities : DbContext
{
public CompanyEntities()
:base("ConnectionStringName")
{
...
}
....
}
In this way you don't depend on default connection strings, which may be confusing.
You say you can connect via SQL Management Studio, but my guess is you use Windows Authentication for that, and not the uid=XXXXX;pwd=XXXXX; supplied in your connection string.
Try to get Management Studio to connect using that userid and password.
Also, that account might be locked out (if it is an Active Directory account).
This sounds eerily like a problem a client of mine had. It had to do with something having mucked up the DbProviders section of machine.config. He put the details here: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/f2a19487-6d38-4a79-a809-d3efe4c9d9fe (it's the Adam Scholz answer to his boss' question. :) )
Julie
May be this is solved already but i got it solved by setting the start up project in my solution to the entity dll project ( having app.config file ). I did set the "Default project" in Package Manager Console window to the correct entity dll project but that did't work. For details
Entity Framework 6 with SQL Server 2012 gives System.Data.Entity.Core.ProviderIncompatibleException
system-data-entity-core-providerin
If your solution has multiple projects, try setting the Startup Project for the solution to the project that contains the Web.Config or App.Config file that contains the settings for EF.
I had a solution with a Web project and seperate project (Data.Models) for my models. All was well until I added a console application to the solution. As soon as I set that to be the startup project, EF Migrations would fail.
Also, if multiple projects in the solution have migrations enabled, always run the Update-Database on each project after you do a Add-Migration. My web project had a pending migration, and the migrations failed weirdly on the second project because of the pending migration in the first.

ASP.NET MVC 3 - Unable to find the requested .Net Framework Data Provider

Background-info:
I'm using Microsoft Visual Web Developer 2010 Express.
Info about my (lack of) experience: the problem occured within the first tutorial that I'm trying to work through.
Some additional-info:
I'm comfortable with C#, Postgres, Rails (so MVC & Web-apps are not new to me)
I have no experience with ASP.NET or SQL Server
Problem Description:
I'm trying to following exactly the steps from the "Intro to ASP.NET MVC 3"-tutorial and I'm running into a problem at the first step from part 5 - Adding the MoviesController:
When I'm trying to add the "MoviesController" with the exact settings that are shown in the tutorial and click 'Add' I get the following error:
"Unable to retrieve metadata for
MvcMovie.Models.Movie. Unable to
find the requested .Net Framework Data
Provider. It may not be installed."
Google gave a ton of results when searching for the phrase "Unable to find the requested .Net Framework Data Provider", but nothing has solved the problem so far.
What I've tried:
I think SQL-Server was not installed so I installed it from the Visual-Studio Express ISO- got an error then I've run a repair from the ISO and it claimed that all 15 points including SQL Server Express repair &.NET 4 Framework went through successfully.
I've run the The_.NET_Framework_Setup_Verification_Tool which succeeded for everything.
http://blogs.msdn.com/b/astebner/archive/2008/10/13/8999004.aspx
After the mentioned (re-)installing & repairing I recreated the Project and followed every step as described in the tutorial and got the same error.
I found that I should look for DbProviderFactories in machine.config,
The root-Web.config of the Project has the following entries
<connectionStrings>
<add name="MovieDBContext"
connectionString="Data Source=|DataDirectory|Movies.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
My machine config-file has only one DbProviderFactories entry:
<DbProviderFactories>
<add name="Microsoft SQL Server Compact Data Provider" invariant="System.Data.SqlServerCe.3.5" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=3.5.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"/></DbProviderFactories>
then I found the following quote
"we have changed the way
DbProviderFactories.GetFactoryClasses()
determines the framework providers in
VS2010. They are no longer listed in
the machine.config file. "
from http://social.msdn.microsoft.com/Forums/en-ZA/adodotnetdataproviders/thread/d79129c4-ae05-4c45-8997-bd90f5765a3a
Question:
So perhaps this is the wrong direction and since I have no clue what to try next, what steps should I take to investigate & solve this problem?
Btw. I have postgres installed, so if using postgres instead of SQL-server would be an easy solution let me know. For my own projects I would want to use a different DB anyway (probably postgres), but for now I would just want to be able to get successfully through the first and seemingly simple tutorial I've tried.
I was having the same problem so I replaced
<add name="MovieDBContext" connectionString="Data Source=|DataDirectory|Movies.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
with the following
<add name="MovieDBContext"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;database=Movies;User ID=sa;password="
providerName="System.Data.SqlClient"/>
And it worked enough to let me continue working. I too would also eventually learn how to make these kinds of applications work with mysql at some point, but for now this should at least help you continue with the tutorial.
You need to install Microsoft SQL Server Compact 4.0.
If you look at the config you'll see that installing SQL Server was a red herring;
<add name="MovieDBContext"
connectionString="Data Source=|DataDirectory|Movies.sdf"
providerName="System.Data.SqlServerCe.4.0"/>
SqlServerCE is not, I'm afraid, full blown SQL Server, it's SQL Server Compact Edition. I would have thought that would have been installed with VS Express, however you can download the specific installers from here
I actually had both SQLServerCE and Express installed, but the tutorial used Compact Edition:
One step within part 4 of the tutorial is to explicitly add the part you quoted to the Web.config. So this is a part of the web.config by intention.
But deleting this part from the web.config makes it possible to add the Controller in the way the tutorial described it. While this means no longer exactly following the tutorial, it's fine for me. (This results in the creation of an MvcMovie.Models.MovieDBContext database in SQL Server Express.)
http://forums.asp.net/t/1679349.aspx/1
CypressBender
Re: Unable to retrieve metadata for * Unable to find the requested .Net Framework Data Provider....
Aug 08, 2011 07:44 PM|LINK
I installed Microsoft SQL Server Compact 4.0, and that fixed the problem for me.
http://www.microsoft.com/download/en/details.aspx?id=17876
I changed my SQL providerName="System.Data.SqlClient" in web.config , since I have SQL client as well as SQL compact installed on my system.
Rebuilding the project wont catch config errors in the DBContext section... the build process does not walk through connections, so you can build all day and still bomb out. As suggested above, fix the config so the connection string matches MachineName/SQLInstanceName/DBName with the correct SQL config. Worked just fine by just modifying my web.config in my solution.
Make sure that you build prior to adding the controller. If that doesn't work...
Create a new project, create a new sql server database manually and see if you can connect to it. If not, then the problem is indeed in your sql server config on your machine. You can try going to postgres just be sure that the provider you choose has support for EF code first.
What I did was in order to overcome the first problem I put in Web.config the code:
<add name="MovieDBContext"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Movies.sdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
Notice I am creating SQL CE 4 database, therefore the .sdf and not .mdf
Next, you should receive another connection errors on the page /Movies, so replace the above code with :
<add name="MovieDBContext"
connectionString="Data Source=|DataDirectory|\Movies.sdf;"
providerName="System.Data.SqlServerCe.4.0" />
And you should be fine.
I had a server. It ran windows updates. And a message waiting for restart was open.
After restart it worked again.
Install Microsoft SQL Server Compact 4.0. The link for same is - http://www.microsoft.com/en-us/download/details.aspx?id=17876
This worked for me, hope it helps
<add name="MovieDBContext"
connectionString="Data Source=(local);Initial Catalog=Movies; Integrated Security=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
After reading other discussions around the web I have found another method.
If you do not add the connection string until after you have created the controller class, then it will work also. It kind of seems like a bug.
Try this:
<add name="MovieDBContext"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|Movies.sdf;User Instance=true"
providerName="System.Data.SqlClient" />

Configuring Enterprise Library 5.0 Data Access Application Block

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

Categories

Resources