How to change multiple connection string value using one method - asp.net

I'm currently handling a .Net system that was developed in Linq for its data retrieval structure. This system was developed by other developers last time and I'm dealing a big problem now.
One of the bad practice (or i just not sure why must the developer do that) i found from this system is that, inside /AppData/DataContext/, there are alot of .dbml files and in the .designer.vb, for example Product.designer.vb file, consists of this piece of code:
Private Shared mappingSource As System.Data.Linq.Mapping.MappingSource = New AttributeMappingSource
Public Sub New()
MyBase.New(Global.System.Configuration.ConfigurationManager.ConnectionStrings("DBconstr").ConnectionString, mappingSource)
OnCreated
End Sub
My current major challenge is, I need to change to a new connection string name for all DBconstr and point to another database while keeping the current "Dbconstr" setting in web.config. There are over 400 lines in the entire system I need to find and replace if i have to do it manually. So I need advice if there is any way i can change all hard-coded connection string using one or few direct methods instead of changing all 400 plus lines manually?
I had thought about calling certain method in .Master page and override the value of .ConnectionString for all the child pages but not sure if this is possible.
Please advice. Thanks

You should have a look at this: http://blogs.msdn.com/b/webdev/archive/2009/05/04/web-deployment-web-config-transformation.aspx. It explains how to use web.config transformation. It basically allows modifying the value of a setting (ie. connection strings) depending on your solution/build configuration.
Modifying the configuration file "on the fly" is much easier than trying to modify it in the code.
You should also check these two answers I provided on the same topic:
How to have different web.config settings for my local machine? -
https://stackoverflow.com/a/19294499/375304
Applying web.config transformations locally - https://stackoverflow.com/a/19301084/375304

Related

best approach to implement getRealPath()

I am working on struts 2.0 . I am designing a web application.
I am using Jasper Report in my application. I want to access the *.jrxml files in my action class. I don't want to give hard coded path to the files. So to get the path dynamically I googled it and got the solution that I can get the path using getRealPath() method. But I found two implementation of doing this:
Using HttpSession to get object of ServletContext and using the getRealPath() method of the ServletContext object.
Like this:
HttpSession session = request.getSession();
String realPath = session.getServletContext().getRealPath("/");
The second approach to do it directly using the static method getServletContext() of ServletActionContext. And then we can get the real path of the application using the getRealPath() method.
Like this:
String realPath = ServletActionContext.getServletContext().getRealPath("/");
Please tell me, is there any difference between the above two and also please tell me whether there is any other way to get the path?
Neither is "better", really, and I'd argue that neither is particularly good, either.
I might try getting the context path in an initialization servlet and stick it into the application context, then make your action(s) ApplicationAware and retrieve the value from the map.
This has the added benefit of aiding testability and removing the static references in the action.
That said, I see zero reason to go through the extra mechanics of your first approach: it adds a lot of noise for no perceivable benefit; I'm not even sure why it wuld be considered.
I'd also be a little wary of tying your actions to a path like this unless there's a real need, what's the specific use? In general you shouldn't need to access intra-app resources by their path.

what is the difference between System.Net.Cookie and System.Web.HttpCookie?

I obtain a HTTPCookie, but need a Net.Cookie. Are they just something you can recast, or how would i go about it?
Actually you have two questions:
Difference between System.Web.HttpCookie and System.Net.Cookie
How to convert from HTTPCookie to a Cookie.
Part 1)
This question is really interesting ,I'm still thinking why there are two classes which looks pretty same ,My initial thought was System.Web.HttpCookie inherits System.Net.Cookie but this isn't true both directly inherit from Object so they are distinct classes ,but the properties matches a lot ,so this gives a hope for the solution of part 2.
Part 2)
I think its possible to convert one into another theoretically since both are just objects if you populate them the right way it will work , here a little analysis when I compared the two classes.
Click to open in new tab to enlarge
Update:
The System.Web is made to be used in server-based apps and System.Net can be used for client based apps.
Some Thoughts:
Write a method or a static class which can convert one object into another, I haven't check all of them but properties whose names match, there signature also matches.
Properties which don't exists in the another object you can stuff some constant or a value which you know matches the scenario like Port number.
Good luck ,let me know how you came up with the final solution ,post the code or link.
Some Links
this post has some related code

Where to store application settings?

Recently, I discovered that the "Web.Config" file contains an <appSettings> section which seemed good for storing one's Application Settings. Heck, it even has a programmatic way to access the file thru a standard System library. So being all clever, I wrote an Interface to access it and then a Concrete implementation of the interface, shown here:
public interface IAppSettings
{
IEnumerable<string> GetValues(string componentName, string settingName);
IEnumerable<KeyValuePair<string, string>> GetValuePairs(string componentName, string settingName);
void SetValues(string componentName, string settingName, IEnumerable<string> valueList, bool append);
void SetValuePairs(string componentName, string settingName, IEnumerable<KeyValuePair<string, string>> pairList, bool append);
}
Then I came to discover that saving settings back to "web.config" while the application is running causes the entire application to re-start. This seems completely unreasonable to me because if I'm writing back to web.config a lot and the application is restarting each time, then things like HttpRuntime.Cache get completely emptied effectively making my Cache useless because it's constantly emptying and repopulating.
So I'm wondering: Where should I store my Application Settings?
Is there a good solution out there for this so that I don't have to roll my own?
EDIT:
Okay, thanks to everyone who suggested using a DB and a potential table schema. I think I'm going to go with the following schema:
settings:
index NUMBER NOT NULL AUTO_INCREMENT <== Primary Key
component NVARCHAR(255) NOT NULL
setting NVARCHAR(255) NOT NULL
key NVARCHAR(255)
value NVARCHAR(255) NOT NULL
Though I don't think I'll make the "setting" the P-Key, but use an Auto-Incr Index instead. This way if I have an application that needs to mail something to multiple managers, I can store many:
index component setting value
1 RequestModule ManagerEmail manager1#someplace
2 RequestModule ManagerEmail manager2#someplace
And then I can use:
IEnumerable<string> GetValues(string componentName, string settingName);
And it will return a list of email addresses, rather than just a single value.
Does this make sense?
web.config is generally used for read-only settings, ie. the settings set during deployment of the application by the system administrator.
If you want to read and write the settings, the most obvious way is to use the database. By the way, this has an advantage: an application can be hosted on several servers and will still read and write the settings correctly,
You can also implement your custom storage for the settings, but it will be probably more difficult to implement and not much faster.
To answer your second question, the structure of your database depends on the type of settings you want to store.
If you need to store heterogeneous unique entries like this:
Mail address of an administrator,
Maximum number of entries to display on home page of the website,
Text to display on "About us" page,
Boolean value indicating whether public comments are enabled or not,
then you have to use varchars or other more or less friendly types as keys to identify the entries (rather than to refer to them by their index).
On the other hand, if your purpose is to store the mail addresses of several managers, you should create a Manager table containing their mail addresses, names, datetime of their last connection, etc.
You really shouldn't mix both. In theory, you can refer to the entry in settings by component/setting pair. In practice, it makes things harder and creates a bunch of problems:
What if, further, you will need, for every manager, to store a boolean value indicating whether she/he wants to receive alerts from you? With your current structure, this will be impossible.
Since the same setting can have multiple values, how do you intend to handle the settings which must be unique? For example, there must be only a single value of text to display on "About us" page. What if there are two values stored in database?
Storing settings in web.config is useful because it makes it easy to have different settings in different environments. However, as you say, this is no use if you are likely to want to change the settings in a live environment.
A simple database table is the most useful way to do this if you need to change the values.
eg.
create table Settings
(Name varchar(50) primary key,
Value varchar(50))
If you're using SQL Server, you can set to the Value column to be sql_variant which will allow you to store a variety of datatypes.
It is meant for application settings, but not settings that are meant to be dynamically changed during runtime. Rather, it is for settings that change only occasionally, and where you would expect (and even desire) an app restart when they change.
For more ephemeral settings, you may want to just use a simple database system - even a flat file/XML in the App_Data dir can work, if your app doesn't use a database otherwise.
Yes.Changing the web.config will reset the application.I usually maintain a settings table to store key-value pairs for the settings and access it from there.
SETTINGS
SETTING_NAME VARCHAR(100)PRIMARY KEY
SETTING_VALUE VARCHAR(100)
Then write a class which can Insert,Delete,Update values to this table.
Ex Data for the SETTINGS table
SETTING_NAME SETTING_VALUE
AdminEmail admin#mysite.com
ErrorTrackingEmail errors#mysite.com
I usually add a "type" field to my settings table so that I only retrieve the group of settings needed this works for me as a way of grouping like settings and retrieving them at once.
Create a key-valued table like this:
settings:
name NVARCHAR(255) PRIMARY KEY
value NVARCHAR(255) NOT NULL
First of all, it's not unreasonable at all when you consider what information is supposed to be stored in the web.config file. When you change things like assembly information, connection strings, etc., your application needs to stop and reload the values to run with those settings.
If you're storing application wide settings, then you can create a Settings table in your database or even use a separate text file to store the settings.
If you're talking about storing per-user settings, you shoul check out ASP.NET Profile Properties.
Application-wide settings should certainly be stored in this section of the web.config file, as it prevents hard-coding values which may change over time. There's no need to read them out using your own code, as there's a built-in method: use the System.Configuration.ConfigurationManager.AppSettings array to retrieve them (you'll need to add a reference to the System.Configuration assembly in your project). You can edit AppSettings through the ASP.NET Web Site Administration Tool, too (Project menu -> ASP.NET Configuration).
For values which you envisage changing more often and while the site is up and running, it's reasonable to use an XML file, lightweight database (such as SQLite or SQL Server Compact) or even a text file for these settings.
If you need to save settings, you can always save them in a custom configuration file.
I did just that a while back, and I have the code available to do it here.

ASP.NET Localized web site -- updating on the fly

I think I have a solution to this, but is there a better way, or is this going to break on me?
I am constructing a localized web site using global/local resx files. It is a requirement that non-technical users can edit the strings and add new languages through the web app.
This seems easy enough -- I have a form to display strings and the changes are saved with code like this snippet:
string filename = MapPath("App_GlobalResources/strings.hu.resx");
XmlDocument xDoc = new XmlDocument();
XmlNode xNode;
xDoc.Load(filename);
xNode = xDoc.SelectSingleNode("//root/data[#name='PageTitle']/value");
xNode.InnerText = txtNewTitle.Text;
xDoc.Save(filename);
Is this going to cause problems on a busy site? If it causes a momentary delay for recompilation, that's no big deal. And realistically, this form won't see constant, heavy use. What does the community think?
I've used a similar method before for a very basic "CMS". The site wasn't massively used but it didn't cause me any problems.
I don't think changing a resx will cause a recycle.
We did something similar, but used a database to store the user modified values. We then provided a fallback mechanism to serve the overridden value of a localized key.
That said, I think your method should work fine.
Have you considered creating a Resource object? You would need to wrap your settings into a single object that all the client code would use. Something like:
public class GuiResources
{
public string PageTitle
{
get return _pageTitle;
}
// Fired once when the class is first created.
void LoadConfiguration()
{
// Load settings from config section
_pageTitle = // Value from config
}
}
You could make it a singleton or a provider, that way the object is loaded only one time. Also you could make it smart to look at the current thread to get the culture info so you know what language to return.
Then in your web.config file you can create a custom section and set restartOnExternalChanges="true". That way, your app will get the changed when they are made.

Is there any way to use XmlSiteMapProvider within WinForm/Console/VSTest application?

I wonder whether there is a workaround for using the standard XmlSiteMapProvider within a non asp.net application, like WinForm/Console or, in my case, VS Unit Test one.
The following code fails, because it cannot create a path to the .sitemap file inside a private GetConfigDocument method.
XmlSiteMapProvider provider = new XmlSiteMapProvider();
NameValueCollection providerAttributes = new NameValueCollection();
providerAttributes.Add("siteMapFile", "Web.sitemap");
provider.Initialize("XmlSiteMapReader", providerAttributes);
provider.BuildSiteMap();
I feel the right solution is to write another provider.
I do not see why not. It is just a provider that implements an interface. You may not need many of the features, but you can access the API for what it provides you. Your WinForms screens can simply use the Urls for identification so that you can determine your place in the hierarchy.
What you may have to do is create a custom implementation of the provider because it will use the HttpContext to get the Url of the current web request to identify current placement while you will need to get that value differently. That is what could be tricky because your WinForm application could be displaying multiple windows at time. If you know there is only one window showing at a time you could use a static value which is set prior to accessing the SiteMap API.
Now you have to question the value of using an API if you have to do all of the work. There may not be enough benefit to make it worthwhile.

Resources