Is there anything wrong with modifying the web.config file dynamically - asp.net

I read this article. I was planning on creating a setup page that runs and allows the user to change the sql connection strings which is stored in the web.config file. With some changes this may help in deployment or even development. My question is is it possible to change the connection string in the web.config file based on user input and is this advisable. N.B The connection string must be contained in the web.config
THank you

You may find helpful this blogpost on this topic.

hmmmm. Changing the web.config file would cause the app to restart. At least that's what would normally happen and from my understanding of the dependencies involved would happen if you did it from code.
That might be acceptable to you though & it is the best way to do it if the restart is acceptable.
Simon

It's possible to modify web.config based upon user input. It's just an XML file.
We do this as part of a custom action in an installer (MSI).
Modifying a web.config will cause the application pool to recycle though. Depending on your site, this (recycling) may or may not be a big deal.

Related

Save a string for later use in ASP.NET

I have a simple string that I would like to save for later use on an ASP.NET server. It is an authorization string for a web service. It mostly stays the same, but may expire every few months. It will be saved programmatically from a code-behind file. Is there a simple place I can save it?
Initial thoughts are:
File - seems reasonable
Database - we don't have one setup and it seems like a lot of overhead to hold a string
Session - this would be too short lived
Config file - Based on answer from MK_Dev this would require a web app restart. No go then.
Somewhere else that I don't know about, but would be perfect?
Another possibility is to create a custom registry key. Here is an article with some code examples: Manipulating and Editing Registry with .NET.
If you don't mind restarting the app when the value changes, then config file is the way to go. If you need it to be fully dynamic, you can add a config table to the database and update it when changes.
How about server side cache?
Check this out: http://msdn.microsoft.com/en-us/library/18c1wd61%28v=vs.71%29.aspx
If the string remains static for the most part, I would store it in Cache with an expiration and/or dependency. If you go the dependency route, you can use a file or store the string in the database, and it will update automatically if and when it's changed.
See this article for details: Caching Application Data
How about System.Environment variables?
System.Environment.SetEnvironmentVariable("mystring","asdf");
System.Environment.GetEnvironmentVariable("mystring");

Changing Global.asax variables from IIS

Can I change access or edit the values specified in Global.asax from IIS?? The reason is that I don't have the source code and the only change we need right now is to change the connection strings (database) specified in Global.asax.vb file.
Thanks!!
Usually, connection strings are specified in the Web.config for this very reason. If the values are hardcoded, there's no way for you to modify them unless you can change the code. You can setup an identical database (name, creds) and change some config settings so that your database server resolves to the same machine name. That's all I can think of...
Well, I was able to circumvent the issue. Not very elegant and might add to performance load, but was the simplest considering the work involved to recreate the project.
I created another aspx page and set the connection variables using the Application object in the Page's Page_Load, and then did a response.redirect to the previous default file. I was lucky as all code referred to the Application Object, and this was set only in Global.asax - had there been any code which directly specified the connection string - then I would be screwed!
The only overhead was that the Application_Start would be called only once - but overwriting those values with Page_Load will be called every time a request is made. Kind of trade-off I am ready to do.
I could not agree the previous answer as it mentioned the "Ideal" Case and the best practices - it did not solve my problem. The previous solution should be adopted if the previous sql server can be completely demoted.
Thanks Guys!

ASP.NET - Basic checklist for putting a site into production

I'm building a static ASP.NET site (using Masterpages and a few forms) and I'm about to release it onto my production server.
I know about changing <compilation debug="true"> to false, but I'm wondering what other things I can do to obtain the highest speed possible. There is no data access in the site, it's all static content.
Does anyone have a checklist they run through or know of a good resource for setting up sites in a production environment, with a focus on performance?
Checklist so far (Feel free to edit this yourself with any worth additions)
Make sure <compilation debug="false" /> is actually set to false in Web.Config
Make sure <trace enabled="false" /> is actually set to false in Web.Config
Set necessary read/write/modify folder permissions for site
Enable GZIP in IIS (reduces size of pages/css/javascript dramatically)
Have you considered OutputCaching for any pages / controls?
Consider setting up Web Tests (Eg WatiN for .NET) to make sure functionality on your site is still working ok
Make sure it isn't Friday afternoon!
If you're writing any log or output files, make sure the proper folder permissions are setup in the production environment. Typically debug/test environments are much more lax on file read/write permissions than production.
Don't deploy on Friday afternoons! This is guaranteed to mess up your head for the weekend.
Also, don't forget to check the gzip settings in IIS. Compressing output will make things travel across the wire much faster.
There is actually a very good checklist on how to perform a security deployment review provided on MSDN.
if its all static content, you'll want to use aggressive Output Caching
If your site use a database and only presenting information, make the database read-only. That takes away all locking handling and speeds upp the access a great deal.
If you have a back-end that updates the data, make it a separate database and have sheduled periods that update the readonly database once a day or what is needed for that application.
If you just present news and other small things on a company web-site that not change so often then this solution is probably for you. Even if its a site with gigabytes of data.. The key word is, how often does we update the data?
From what I see in daily business,noone really thinks about this solution because everything has to be "real time", but there are plenty of cases where this would be a perfect solution.
Review your web.config
Check debug (web.config / *.svc), tracing, ...
Update debug to production values:
email addresses
(web)service addresses
location log files
quick search: link
You should have some sort of test to verify various functions of your site, and the permissions. For instance, once you publish. Walk through a checklist, can I access x if I don't have permission? Does x,y,z work on the application? I do this after every publish because small changes can have a big impact.
You should read this:
https://stackoverflow.com/questions/72394/what-should-a-developer-know-before-building-a-public-web-site
It's currently the 9th highest voted question on SO and in the top 3 most favorited. The caveat is that it's platform agnostic, so it's missing some ASP.Net-specific items.
Thoroughly test the site outside of your corporate firewall / proxy after clearing your browser cache. This will help to ensure that all resources are publicly accessible (and are not on a local server or cached). For instance, you might find that you have used absolute URLs to include, say, JavaScript or CSS files. These work fine in your development environment, but as soon as the site goes live they are inaccessible. Or you have a CSS file in your cache that has subsequently been deleted, but you don't notice.
Ensure that any products / applications you use that have keys that are tied to a domain will work on your live site. This includes things like Google Map keys or commercial 3rd party applications. It also includes automatically generated hyper-links sent out in, say, emails. You wouldn't want a user registration to have a link back to http://localhost/comfirm.aspx or the like, would you?

Editing Web.config programmatically

What is a good way to edit a Web.config file programmatically?
I looked into System.Xml but couldn't find any obvious answers.
This fellow shows sample code if you still want to do it after all the caveats:
protected void EditConfigButton(object sender, EventArgs e)
{
Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
//Edit
if (objAppsettings != null)
{
objAppsettings.Settings["test"].Value = "newvalueFromCode";
objConfig.Save();
}
}
One valid reason for editing a web.config is to encrypt it, which is what that article is about.
You can use the WebConfigurationManager to read specific configuration sections. This will return a ConfigurationSection object. You can use this to read/modify the ConfigurationElements in the section. Once you have updated them, you can Save the ConfigurationSection and it will update the file with your changes.
I use this to automatically encrypt the appSettings and connectionStrings on Application_Start if they aren't already encrypted. I haven't actually changed any settings this way, but it seems like you ought to be able to do so.
Saving the updated configuration file may cause the app to recycle depending on how it is built.
Depending on what you are doing, the method is really a bit different in each situation. However the most robust method is to load it as an XmlDocument and modify it as needed via that method, but you MUST be careful to only modify it in the needed manner.
In theory; you could just generate a web config file programmatically and with some templating to make it easy.
However, if you're trying to edit your web.config from within the site; it's highly recommended you don't. At the very least; you'd trigger an app reset every time you updated it; which would be especially bad if you're using in-process sessions.
As Anders asked, what is it you're trying to do?
Yes I agree with Josh. I have tried this before and I've had two negative effects:
Slow loading if the current page after postback because ASP.NET is loading the web.config and all related resources
If you change the web.config early enough in the load cycle (e.g. global.asax events) the site may never load or fail in unpredictable ways
Agree with others, editing the webconfig is achievable, but has knock on effects are just to dangerous / risk involved
If its a value that is application specific, then it should be in an application specific config file
Lot of time you want to modify application specific settings after deployment like say when something is wrong e.g. switching the database connection in case current DB goes down. Moreover sometimes you want to create your own XML based configuration file which you want o modify programatically.
Try XML Webpad - http://xmlwebpad.codeplex.com/
Its a framework to view an edit XML files. Once you integrate it with your web app, editing web.config ill be as simple as viewing the web.config page, making the required changes and hitting the save button (all from within your application).

Why is ASPNETDB.mdf created and how do I rid myself of it?

My question is stated in the title, to give some background though.
I'm helping a customer use webparts within a ASP.net environment and I don't want them to get attached to this database. I'd like to be able to use the site without it creating this database.
I'm currently researching more into this, but any suggestions on sites to look at or information regarding this will be much appreciated.
Most of your configuration is saved in this database. It's created to hold all the complex data that is necessary for membership and personalization to work.
You can point to a different database if you have one set up, but out of the box, Visual Studio uses this local file for the database.
I believe that web parts relies on having the database available, so you'll need to keep this database, or follow the link above to use a centralized database.
http://msdn.microsoft.com/en-us/library/879kf95c(VS.80).aspx
I know this is a very old post, but I had basically the same question, "Why is ASPNETDB.mdf being created?". Since my site used a SQL database, ASPNETDB.mdf had not previously been present. But then suddenly it appeared and my entire site crashed at the hosting location. It was a little insidious because everything worked fine in the development environment.
In my case I wanted to get a list of user roles and I had added < roleManager enabled="true" /> in web.config. I didn't connect at the time that this would create ASPNETDB.mdf. This SO post The Role Manager feature has not been enabled has some good discussion regarding this topic.
But the point is that when I enabled the role manager, the MVC framework automatically created ASPNETDB.mdf, causing my problems at the hosting location. I found a different way to get the roles without activating the default role manager and my immediate problem was resolved.
I just wanted to add this post in the event someone else was surprised by the sudden appearance of ASPNETDB.mdf. This is another way it can show up, which is related to the op's question.
If the ASPNETDB.mdf is not needed by your application, then you can simply remove it from the "App_Data" folder where this database file is probably located and also remove the line in the web.config file that references to it.
However, this database is needed if you are using membership services as this is the place where all this information will be stored - as it was mentioned in David's answer.
Are you using one of the ASP.NET toolkits for this application? please provide more details in order to help you better.
The 'why' is here:
To get the aspnetdb.mdf created on the fly, one can simply Ctrl-F5 to run the web site or web application. Click “Log In” button to let the ASP.NET Development Server or IIS server process create the aspnetdb.mdf file for you.
But this is a little old I think and things have moved around a bit. The default connection string is now in the machine.config:
The default connection string is defined in machine.config
I find this incredibly odd and it caught me by surprise when i was iterating thru connection strings.
There is also a lot of talk on the internet that User Instance=true is now deprecated in favor of localdb, but I struggled to find an official line for that.
To make it stop, you can add a "clear" tag to connectionStrings section (I confirmed that this works):
<connectionStrings>
<clear/>
I'm thinking of removing it from the machine.config.? Having it in there in the first place seems pretty heavy handed on MS's part.

Resources