Possibility to add database in sqlCacheDependency collection without web.config - c#

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.

Related

Change Database Source Depending on Login Credentials

I'm a new developer and I'm working on a project that utilizes the SalesForce REST API. A portion of my .Net project involves updating the web.config and the database depending on the login credentials.
For example, client 1 logins in, the are updated with the correct Consumer Key and Client Secret. This client has access to Database1.
Client 2 logs in. are updated appropriately. Now, the Database1 is switched out with Database2, programmatically.
Is there a way to programmatically change the database source depending on login?
Quick edit to my post. Client1 and Client2, in this instance, are two separate companies, that should not have access to each other's databases. I want to be able to utilize the same application for both clients, but update the web.config and the database used, depending on which company logs in.
If you are using L2S or EF, you can create a class within your application that inherits your L2S/EF context class, then make the derived class's constructor do the work of figuring out what connection string to use based on log in and initialize itself. You can then use that derived class as a data source as needed.
Basically, it sounds like you may have a situation where you don't want to be updating the web.config every time you add a new client/database. You'll want to store a template for the connection string in web.config, but not the strings themselves.
You don't need to update your web.config with the database data depending on the login credentials. You can include all the connection strings that you want in your web.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="database1" connectionString="..." />
<add name="database2" connectionString="..." />
</connectionStrings>
</configuration>
And then simply retrieve the value that you need when you handle the user login:
var connectionString = ConfigurationManager.ConnectionStrings["database1"];
or
var connectionString = ConfigurationManager.ConnectionStrings["database2"];
just add 2 entries in the .config file like this
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="DbConn" connectionString="Data Source=someDataSrc;User Id=someuderId;Password=somePassWord;" />
<add name="DbConn2" connectionString="Data Source=someDataSrc; User Id=someuderId; Password=somePassWord" />
</connectionStrings>
</configuration>

How to enable/disable Encryption/Decryption of Query String from Web Config?

I've multiple pages that require encryption/decryption of query string. I've written the code for that and its working.
Now my requirement is to enable/disable it using web.config. Like from Web.config only, we can turn the ecryption/decryption process on or off.I don't want to go to every page and change it.
Is it possible using HTTPModules in Web.Config which will be checked from every page that tells whether to encrypt/decrypt or not?
we can have key/value pair settings in appsettings in web.config.
<appSettings>
<add key="EnableURLEncryption" value="false"/>
</appSettings>

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.

Purpose of elements having their connectionStringName set to LocalSqlServer?

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

Categories

Resources