Enterprise library 4 dataconfiguration tag - asp.net

I am using Enterprise library for my data access.
When I am running the application, at the CreateDatabase() statement I am getting this exception:
Microsoft.Practices.ObjectBuilder2.BuildFailedException
was unhandled by user code
Message="The current build operation
(build key Build
Key[Microsoft.Practices.EnterpriseLibrary.Data.Database,
null]) failed:
The value can not be null or an empty string.
(Strategy type Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder.ConfiguredObjectStrategy,
index 2)"
Source="Microsoft.Practices.ObjectBuilder2"
Now, I googled a bit and I found that I have to place
<dataConfiguration defaultDatabase="LocalSqlServer"/>
but I don't know where. Is it the right solution?
Also, at the time of installing enterprise library I didn't see any connection string statement? So, I wonder how it will take the connection string from web.config file.
In the connection string section of my web.config file I have:
<remove name="LocalSqlServer"/>
<add name="LocalSqlServer" connectionString="Data Source=MSTR;Initial Catalog=USERDb;Integrated Security=true;" providerName="System.Data.SqlClient"/>

Yes you need to add the dataConfiguration section to the web.config.
First you need to add dataConfiguration to the list of ConfigurationSections in your web.config:
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</configSections>
Then you need to add your connection strings to the web.config (you've already done this):
<connectionStrings>
<add name="LocalSqlServer" connectionString="Data Source=MSTR;Initial Catalog=USERDb;Integrated Security=true;" providerName="System.Data.SqlClient"/>
</connectionStrings>
Then you need to add the actual dataConfiguration section to the web.config:
<dataConfiguration defaultDatabase="LocalSqlServer"/>
You can also use the Enterprise Library Configuration Tool to do this for you as well.

Related

User Secrets in .NET 4.7 connectionstrings format

I have been digging for hours and keep coming up with information about .NET Core, yet hardly anything about .NET 4.7 full framework. I figured out how to add User Secrets to the main project of my Web API solution. I get the basic secrets.xml file where I need to to either store my database username and password or my connection string. Every post I find talks about the changes you need to make to web.config. However nothing shows what to do with my connection string, how to format it, in the secrets.xml file. I could create a name/value pair but that does not seem to do anything, my app cannot connect to the database.
I have this in my Web.config:
<configBuilders>
<builders>
<add name="Secrets" userSecretsId="5c65f7eb-a7e1-46cc-bff4-a526678005f2" type="Microsoft.Configuration.ConfigurationBuilders.UserSecretsConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.UserSecrets, Version=1.0.0.0, Culture=neutral" /></builders>
</configBuilders>
<connectionStrings configBuilders="Secrets">
<add name="ShopAPDbConnectionString" connectionString="" providerName="System.Data.SqlClient" />
</connectionStrings>
My secrets.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<root>
<secrets ver="1.0">
<secret name="ShopAPDbConnectionString" value="Server=SQLDEV01;Database=ShopAP; Integrated Security=True;" />
</secrets>
</root>
How do I properly format and get this to work?
Here is what I was able to get to work based on https://github.com/aspnet/MicrosoftConfigurationBuilders
Web.config
<configuration>
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="Secrets" userSecretsFile="~/../../../SecretsTest/secrets.xml" mode="Greedy" type="Microsoft.Configuration.ConfigurationBuilders.UserSecretsConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.UserSecrets, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="Json" jsonFile="${JSONConfigFileB}" optional="true" type="Microsoft.Configuration.ConfigurationBuilders.SimpleJsonConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Json, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</builders>
</configBuilders>
<!--...-->
<appSettings configBuilders="Secrets">
<!--...-->
</appSettings>
<!--...-->
<connectionStrings configBuilders="Json">
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="dummy.value.required" />
</connectionStrings>
<!--...-->
</configuration>
secrets.xml
<?xml version="1.0" encoding="utf-8" ?>
<root>
<secrets ver="1.0">
<secret name="usersecret1" value="dogodog" />
<secret name="usersecret2" value="secretbar" />
<secret name="JSONConfigFileB" value="C://Users//xxx//Documents//xxx//xxx//SecretsTest//settings.json" />
</secrets>
</root>
settings.json
{
"DefaultConnection": "Server=666.66.666.6;Database=BigToe;User ID=FireBall;Password=BunniesAreSoft",
}
Both your files look fine - pretty much exactly the same as mine.
How did you create your secrets file? Did you use right-click on the Web project and Manage User Secrets?
That will create a file in a folder location in %APPDATA% that should be picked up when you hit F5 in Visual Studio (Debug > Start Debugging). However, it will not be seen by IIS if you compile and then browse to localhost. Even if you change the App Pool Identity in inetmgr to run under your account, and set Load User Profile - it still will not find it.
To find the correct location for the secrets for this case, run your web app and obtain the result of
string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
and copy the secrets file into the matching sub-folder Microsoft\UserSecrets\(guid)\
e.g.
C:\Windows\System32\config\systemprofile\AppData\Roaming\Microsoft\UserSecrets\5c65f7eb-a7e1-46cc-bff4-a526678005f2\secrets.xml
you may need to one-off obtain access in Explorer, and create the UserSecrets folder and below.
Remember to update both copies if you edit it in future.
Make sure the only file in your UserSecrets folder (C:\Users...\UserSecrets{guid}) is the secrets.xml file. I was messing around and had a secrets.json file in there (along with the secrets.xml file) and it wouldn't load my secrets.xml file. After I removed the json file, it worked fine.
I am attempting to do the same thing, but unfortunately I think this is only for appSettings when it comes to .Net Framework/Web.config.

How do I stop using ASPNETDB.MDF in LocalDB?

I implemented ASP.NET Identity and it automatically created ASPNETDB.MDF and aspnetdb_log.ldf in my App_Data folder. I already have the AspNet tables (i.e., AspNetRoles, AspNetUsers, etc) in my SQL Express instance (which is where all my other tables are sitting). As far as I can see, my application is reading and writing membership and role data from the SQL Express database and not ASPNETDB.MDF.
I have set my connectionString in web.config to:
<add name="DefaultConnection" connectionString="Data Source=MyComputerName\SQLEXPRESS;Initial Catalog=MyDatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
However, if I remove ASPNETDB.MDF from App_Data, I get the following error when I login:
Exception Details: System.Data.SqlClient.SqlException: One or more files do not match the primary file of the database. If you are attempting to attach a database, retry the operation with the correct files. If this is an existing database, the file may be corrupted and should be restored from a backup.
Cannot open user default database. Login failed.
Login failed for user 'MyComputerName\MyUserName'.
Log file 'C:\Users\MyProjectName\App_Data\aspnetdb_log.ldf' does not match the primary file. It may be from a different database or the log may have been rebuilt previously
The error goes away once I add ASPNETDB.MDF back to App_Data.
I have searched all the code in my solution and it makes no reference to ASPNETDB. So why is it still trying to read from it?
I am developing ASP.NET web forms on .Net 4.5.
I was getting exactly the same problem. I discovered that VS annoyingly pulls in config settings from machine.config, which lives outside of the project, in my case in...
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
Identity 2.0 had used the following connection string inside machine.config...
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
to set up a connection for...
<membership>
<providers>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, ........" connectionStringName="LocalSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
</providers>
</membership>
.. (which was also set in machine.config). If you haven't been using Membership then it's fine to do as Lord nick suggests (except just the clear/ will do the job) and simply do the following in web.config...
<connectionStrings>
<clear/>
<add name="DefaultConnection" connectionString="whatever" providerName="System.Data.SqlClient" />
However, if you, like me, previously had Membership running (https://msdn.microsoft.com/en-us/library/6e9y4s5t(v=vs.100).aspx), you will need to comment out or delete the following sections from machine.config...
<!--
<membership>
<providers>
...
</providers>
</membership>
<profile>
<providers>
...
</providers>
</profile>
<roleManager>
<providers>
..
</providers>
</roleManager>
-->
... since all this stuff is no longer needed for AspNet Identity 2.
I also had to add the following into in my web.config:
<modules>
<remove name="RoleManager"/>
</modules>
... as per this answer: Default Role Provider could not be found on IIS 7 running .NET 4
I hope I've saved someone some time. This took me hours and hours to work out.
I had the same Problem where the ASPNETDB.MDF was automatically created, even if I use Asp.Net Identity as the main user management.
I solved it by removing the following line from web.config:
<roleManager enabled="true" />
This one tells ASP.NET to use the older ASP.NET Membership user management, which is not supported by ASP.NET Identity.
It seems you have something like in your web.config
<add name="DefaultConnectionForLocalDb" connectionString="Data Source=(LocalDb)\v11.0;..."; />
In your AccountModels.cs file, you have:
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnectionForLocalDb")
{
}
}
However it should be this way:
<add name="DefaultConnectionForSQLEXPRESS" connectionString="data source=.\SQLEXPRESS;...;" />
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnectionForSQLEXPRESS")
{
}
}
Then you can remove safely DefaultConnectionForLocalDb entry from your web.config and ASPNETDB.MDF from to App_Data.
I don't know if you've figured this out or not but one of the things you can try is: in web.config, connections section, add <Clear/> and then <Remove Name=LocalSqlServer/>
Apparently if you don't change/remove the LocalSqlServe will still try to connect to the aspnetdb.mdf.
You might also think about adding back in the LocalSqlServer and having it point to your SqlExpress or SqlServer.

SimpleMembershipProvider not working

I started a new internet project with VS2012 and am trying to just restructure my project a bit and I can't seem to keep the SimpleMemberhsipProvider working. Basically, all I've done is move the models objects into a core project along with a couple other items. I've implemented Ninject and am trying to abstract Entity a bit by using a repository pattern to get my data. I really don't feel as though I've changed much with the current project, but for some reason when I start the application now I get:
{"The Role Manager feature has not been enabled."}
The ActionFilter that is supplied by the framework is where the error is thrown when:
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "Id", "UserName", autoCreateTables: true);
is called.
Here is some of the stacktrace:
[ProviderException: The Role Manager feature has not been enabled.]
System.Web.Security.Roles.EnsureEnabled() +9561885
System.Web.Security.Roles.get_Provider() +8
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo
connect, String userTableName, String userIdColumn, String
userNameColumn, Boolean autoCreateTables) +104
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String
connectionStringName, String userTableName, String userIdColumn,
String userNameColumn, Boolean autoCreateTables) +100
InoutBoard.Core.Infrastructure.Filters.SimpleMembershipInitializer..ctor()
in c:\Users\Kyle\Documents\Visual Studio
2012\Projects\InoutBoard\InoutBoard.Core\Infrastructure\Filters\InitializeSimpleMembershipAttribute.cs:42
[InvalidOperationException: The ASP.NET Simple Membership database
could not be initialized. For more information, please see
http://go.microsoft.com/fwlink/?LinkId=256588]
InoutBoard.Core.Infrastructure.Filters.SimpleMembershipInitializer..ctor()
in c:\Users\Kyle\Documents\Visual Studio
2012\Projects\InoutBoard\InoutBoard.Core\Infrastructure\Filters\InitializeSimpleMembershipAttribute.cs:46
I'm hosting the code on github at the following link https://github.com/keroger2k/InoutBoard
First way
Check the sphair's answer out (in current thread).
Second way
Add following assemblies to the web.config:
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="WebMatrix.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add assembly="WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation>
</system.web>
Update
The WebMatrix.WebData assembly contains a start up method to initialize Membership/Role providers and enable RoleManager (PreApplicationStartCode.Start). But ASP.NET couldn't find that to run in your case. By adding these two lines of code, we force ASP.NET to search these assemblies for PreApplicationStartMethodAttribute(s).
In case others are getting this error and the above solution doesn't work, like in my case. It said invalid child object when I tried to add in the assemblies markup. I had to specify the roleManager and membership tags as below. Once I did that the update-database worked.
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear/>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider"
type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
</providers>
</membership>
I had the exact same error running at my hosting company (WinHost.com - they are excellent BTW).
My solution was to add to the web.config:
<appSettings>
<add key="enableSimpleMembership" value="true" />
</appSettings>
Instead of adding the assemblies to the web.config as Mehdi Golchin suggests, an alternative is to change the assembly references on WebMatrix.Data and WebMatrix.WebData to CopyLocal=True.
add the key to the Web.Config as the page:
http://devbla.wordpress.com/2013/07/03/corrigindo-o-erro-no-aspnet-the-role-manager-feature-has-not-been-enabled/
[]'s

Switching asp.net connection strings live/test/dev

We have a different set of connection strings in our config file as follows.
<!-- TEST CONNECTION STRING -->
<!--
<add name="fooConnection" connectionString="Data Source=Test_server;Initial Catalog=foo_dbTEST;User ID=foo_user;Password=abc1234;"/>
<add name="barConnection" connectionString="Data Source=Test_server;Initial Catalog=bar_dbTEST;User ID=bar_user;Password=abc1234;"/>
<add name="chewConnection" connectionString="Data Source=Test_server;Initial Catalog=chew_dbTEST;User ID=chew_user;Password=abc1234;"/>
-->
<!-- LIVE CONNECTION STRING -->
<add name="fooConnection" connectionString="Data Source=Live_server;Initial Catalog=foo_dbTest;User ID=fooTest_user;Password=abc1234;"/>
<add name="barConnection" connectionString="Data Source=Live_server;Initial Catalog=bar_Testdb;User ID=barTest_user;Password=abc1234;"/>
<add name="chewConnection" connectionString="Data Source=Live_server;Initial Catalog=chew_Test;User ID=chewTest_user;Password=abc1234;"/>
<!-- Local DEV CONNECTION STRING -->
<!--
<add name="fooConnection" connectionString="Data Source=MyDoombaPC;Initial Catalog=fooDEVdbTest;User ID=foouser;Password=abc1234;"/>
<add name="barConnection" connectionString="Data Source=MyDoombaPC;Initial Catalog=barDEVdb;User ID=barTestuser;Password=abc1234;"/>
<add name="chewConnection" connectionString="Data Source=MyDoombaPC;Initial Catalog=chewDEVdb;User ID=chewuser;Password=abc1234;"/>
-->
When I need to change from, for example, live to test I move the XML comments from the Test section to the live section. Is there a more elegant way of doing this using Visual Studio 2010?
Just to be clear this is not a requirement of the application once it is in production, this is for developers to switch between different database connection string sets.
How do others approach this?
You could use the web.config transformation : web.config Transformation
This will allow you to have seperate config files for both debug and release and have different setting in each.

Parser Error Message: The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty

I'm currently setting up my website on a new SQL Server 2008 server, however I'm getting the following error:
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty.
Source Error:
Line 158: <roleManager>
Line 159: <providers>
Line 160: <add name="AspNetSqlRoleProvider" connectionStringName="LocalSqlServer" applicationName="/" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Line 161: <add name="AspNetWindowsTokenRoleProvider" applicationName="/" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
Line 162: </providers>
Source File: C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Config\machine.config Line: 160
Why is this? And how can I resolve the issue? Thanks!
Well I've never had to do this before
on IIS6 and it seems unnecessary. For
starters if you are to add a
connectionString in the web.config
called 'LocalSqlServer' it'll clash
with the machine.config? So you have
to remove the connection from the
machine to add it to the web. This is
what I've done as a temporary fix, but
I've never seen this setup on IIS6 or
IIS7 before.
As Steven said, you do a in that case, no need to modify the machine config for that.
There surely is another different between both computers for that to have happened. A couple:
you had a in the new server, and not in your original server
you are inheriting a from another config.
You are missing a connection string in the <connectionStrings> section of you config file:
<connectionStrings>
<clear />
<add name="LocalSqlServer" connectionString="[your connection here]" />
</connectionStrings>

Resources