Purpose of elements having their connectionStringName set to LocalSqlServer? - c#

1) By default configuration elements have their connectionStringName attribute set to LocalSqlServer, and as far as I know, this attribute refers to connection defined in the element in machine.config file.
a) I assume this connection string refers to database aspnetdb.mdf?!
b) I understand aspnetdb.mdf is used in cases where we don’t manually create membership or profile database ( by calling aspnet_regsql ), but I still don’t understand the purpose of configuration elements having connectionStringName attribute set to LocalSqlServer set? Namely, when and why would they need to access this database?
c) What happens if we manually set membership database via aspnet_regsql and thus don’t use aspnetdb.mdf? How will configuration elements know that we’re not using aspnetdb.mdf and thus instead try to access database we created?
2) If we wanted LocalSqlServer entry from machine.config to point to some other database file, we could do the following:
<connectionStrings>
<remove name="LocalSqlServer" />
<add name=”LocalSqlServer” ... />
</connectionStrings>
I understand that the purpose of <remove> element is to cancel any previously declared elements with same name, but in above example we simply changed the attribute of already existing connection, and as such machine.config doesn’t have two connections with same name, so why did we have to include <remove> element?
thanx

From the connectionStrings element article on MSDN:
Connection strings that are contained
in a parent configuration file are
inherited, unless the clear element is
used in the child configuration file.
The following default
connectionStrings element is
configured in the Machine.config file.
Copy Code
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User
Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>
So if that section of the config file is not modified, it automatically has that connection string.

The convention used is one of many that could have been chosen to accomplish the same task, but the people who were on the ASP.NET team at MS at the time are really the only ones who can say "why" that set of conventions was used. My understanding is that the purpose of the current configuration is to make it as easy as possible for a beginner to get started. i.e. run some wizards, automatically generate database with preconfigured settings, drag-n-drop a few security controls and they have something to work with. Since this was designed for beginners, more experienced developers run into the same set of questions that you're having now because digging into how the pieces fit together isn't simple.
One of the things you'll notice in machine.config is that all of the providers (Membership, Roles, Profile, etc) use this LocalSqlServer connection string name, which again supports the beginner scenario. Therefore, to use youur own database, you need to remove the default definition of LocalSqlServer and define your own. There isn't a replace element in the config file definition, so you have to use the remove/add sequence, which is the logical equivalent. By changing the connection string and leaving its name as LocalSqlServer, all of the providers in machine.config get pointed at your DB. This gives you the default provider definitions in for your database.
Now, if you wanted to customize the provider definitions, you could add them to your own Web.config and change their settings. At that point, you could leave LocalSqlServer as the connection string for the custom provider definitions or you could create your own connnection string and then point your custom provider definitions at your own connection string and you won't need to worry about LocalSqlServer anymore. If you remove LocalSqlServer from you web.config, you'll need to add custom provider definitions to your own web.config that reference your database string.
Hope this helps,
Joe

Related

ASP .NET MVC Database First Individual User Accounts

I am developing a large MVC Web Application with ASP .NET.
I make it as Database First, not Code First.
By creating the Web App with Individual User Accounts Authentication it creates the models, views, controllers and the database for it, which is pretty nice
But I want to change the migration to use my hosted database in the cloud. I tried to change [base("DefaultConnection",...)] in the IdentityModel.cs to use the hosted database, and I also tried to make changes on the Web.config
It was not a good idea! :D
Please, help me!
You just need to search for the "DefaultConnection" ConnectionString in your Web.config file, replace it with your remote server's information and that should be enough to connect to your hosted database.
It should look like this:
<add name="DefaultConnection" connectionString="data source=**YourServer**;initial catalog=**YourDatabaseName**;user id=**DatabaseUsername**;password=**DatabasePassword**" providerName="System.Data.SqlClient" />
I working on a project like you do. I'm using Database First Approach. After create a project with Individual User Authentication, you need to transfer these user tables to your database. You can do this with schema compare.
On the SQL Server Object Explorer > find your localdb that contain user tables > right click > Schema Compare
schema compare
Then select target (your database) and click Compare on right corner.
Select table(s) you want to transfer to your database.
After doing this edit Web.config file:
<add name="DefaultConnection" connectionString="Data Source=YourServerName;Initial Catalog=YourDatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
(This connectionString is to use default model, controllers and actions provided by project. If you want to create your own functions for user operations you only need to add below line after transfer tables.)
Here, provider name is important. Don't chance it. This connection string is for user operations.
Then add ADO.NET Entity Data Model to use your other tables with Entity framework
<add name="YourEntityName" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=YourServerNameL;initial catalog=YourDBName;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
providerName is important here as well.
I add my ado.net in (model folder)
on the web.config change my new connection string to "DefaultConnection"
in the Dbcontext "my ado.net" change to : base("DefaultConnection")

Possibility to add database in sqlCacheDependency collection without web.config

Situation is like this: I have two projects. One Asp.net and one project which does all data related stuff with database. I keep my connectionstring in a seperate encrypted XML file.
Now instead of requesting all data constantly from sql. I want to use SqlCacheDependency to gain performance. If I follow the instruction they advice me to add a database name in web.config.
<caching>
<sqlCacheDependency enabled ="true">
<databases>
<add name="dbName" connectionStringName="connectionstringName" />
</databases>
</sqlCacheDependency>
</caching>
Is there any way to this in code. Like in Application Application_Start() event in global.asax file where I can link to a custom method that provides me that connectionstring?
Thanks in advance
Thanks to David Gardiner's work around.
I found in the following post.
How do I set a connection string config programatically in .net?
I've put it in the Global.asax application load event. Now I can from my sqlcachedependency section in web.config. to that existing connectionStringName from the connectionstring collection.

Building Sitecore connection strings in c#

I am currently working on a Sitecore project where the same sitecore webapplication would point to Sitecore databases based on witch IIS website name the webapplication is running under.
Let’s say the IIS webapplication is called www.company1.com, then the database names would be: www.company1.com.master, www.company1.com.web in \App_Config\ConnectionStrings.config.
I have tried to modify the connection string on Application_Start(), but that is not the best solution (possible but slow and ugly, first request dropped etc.).
Another approach is to use config file transformations, but that is not an options based on the number of web sites.
Is it possible to modify Sitecore.Context, somewhere in Application_Start – so Sitecore.Context.Database would work as expected?
You could setup multiple connection strings entries and then reference it in the node in your web.config.
<connectionStrings>
<add name="core" connectionString="[connection_string]" />
<add name="master" connectionString="[connection_string]" />
<add name="web" connectionString="[connection_string]" />
<add name="web1" connectionString="[connection_string]" />
<add name="web2" connectionString="[connection_string]" />
</connectionStrings>
<sites>
<site name="website1" database="web1" hostName="www.company1.com" (...) />
<site name="website2" database="web2" hostName="www.company2.com" (...) />
</sites>
Would that work for you?
I don't think there is. But you would not want to change the actual name of the connection string, you would want to change the value produced by it. Changing the standard Sitecore connection string names ("master", "core" and "web") would require a lot of related changes in web.config and related config files. On top of that you would probably end up in trouble, as there are modules and code out there still - doing specific Factory.GetDatabase("master") API calls - even if they shouldn't.
I've never attempted what you're asking for here in a Sitecore solution, but I expect it should be possible to create your own ConnectionStringProvider, as described in http://msdn.microsoft.com/en-us/library/vstudio/ms254494(v=vs.100).aspx
The provider would need to return proper results for "master", "core" and so on - any databases you would normally have defined in your solution - and then a dynamic connection string based on the pattern you describe; considering the IIS application name or whatever you need.

Access .NET Membership on Live or Local provider

In my web.config file I have two SQL Server connection strings, one for local and one for live:
<connectionStrings>
<remove name="LocalSqlServer" />
<add name="LocalSqlServer" connectionString="[removed]" providerName="System.Data.SqlClient"/>
<add name="LiveSqlServer" connectionString="[removed]" providerName="System.Data.SqlClient"/>
</connectionStrings>
I then have a "utils" singleton class which basically sets the connection string depending if I'm running the site on "localhost" or on my live server:
if (Environment.MachineName.ToUpper() == MyOwnConfig.GetAppSettingsValue(ConfigKeys.localhost).ToUpper()) {
this.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString();
//MembershipProvider provider = Membership.Providers["LocalAspNetMemberSqlProvider"];
//RoleProvider role = Roles.Providers["LocalAspNetMemberSqlProvider"];
}
else {
this.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["LiveSqlServer"].ToString();
//MembershipProvider provider = Membership.Providers["LiveAspNetMemberSqlProvider"];
//RoleProvider role = Roles.Providers["LiveAspNetMemberSqlProvider"];
}
My Database class then simply uses the connectionString property of my utils class. All this works fine so when I place the site locally I can then simply upload it to live without making changes to the connection strings etc in the config file and it starts using my live database.
Now I'm currently implementing "membership" into my site and for ajax for use some webmethods I'm storing the providerUserKey in a text field of the current logged in user. my web method then checks that this key is authenticated. e.g.
ajaxCreds.ajaxID1 = ((MembershipUser)Membership.GetUser()).ProviderUserKey.ToString();
QUESTION:
the question I have is How do I know if this membership is from the LIVE database or my LOCAL database. As you can see from the web config I've added in the membership/provider lines (commented out) but I don't know how to use them with the above membership.getUser() command.
Alternative... Is this a good way to go? or is it simpler to edit the web.config file when I upload to live?
Many thanks
Most people don't do it this way though I applaud you for figuring all this out. Typically, people use the deployment manager or some other build system to have a different web.config value on the server verses local.
Here is a link on changing in deployment: How do I use Web.Config transform on my connection strings?
I would suggest you to read this article:
http://blogs.msdn.com/b/schlepticons/archive/2010/07/22/modifying-asp-net-providers-at-runtime.aspx
It will show you, that also others were trying to do the similar. And this is how to succeed. Solution (if adjusted) could be similar to your needs.
put all the providers into your web.config
On App_Start adjust which will be the default (based on the Environment)
Membership API will be available as you need for Provider Key
No need to search for Provider by Name
NOTE: you have to tweak the void Application_Start(object sender, EventArgs e) implementation but the idea is there
NOTE2: What you are trying to do is definitely not exception. Configuration based on environment is pretty smart! What must be achieved is standard API usage, e.g. calls via Manager pattern
System.Web.Security.Membership
System.Web.Security.Roles
and not calls to the providers by name.

EF + layers, connectionString

I have an EF model in my DAL project, I want the executing project, the web application, to be the one containing the connection string information.
I also would like being able to store the connectionString separately from the metadata EF requires.
Is this possible from web.config connectionStrings alone, or do I need some sort of code-behind to accomplish this? If that's the case, what would be the code?
The EntityConnection class contains constructor overloads that you can use to pass it in a connection string from your web.config. Keep in mind though that the connection string that EF wants is not what you typically would store in a connection string in a web.config, it has more than just the SQL Server connection information. But you can use the EntityConnectioBuilder class to help you out with that.

Categories

Resources