Dynamically change connectionString in web.config - c#

I have the following in my web.config
<connectionStrings>
<add name="ActiveDirectoryConnection" connectionString="LDAP://ActiveDirectoryDomain1.com" providerName="System.Web.Security.ActiveDirectoryMembershipProvider"/>
</connectionStrings>
I need to add a dropdown box to my login page that allows the user to change the connectionString to a different string, e.g. "LDAP://ActiveDirectoryDomain2.com"
In C# code behind how do change the connectionString value?
More info:
The problem I am having is that there are 4 other web.config settings call that one connectionString. For example:
<activeDirectorySecurityContextSettings connectionStringName="ActiveDirectoryConnection" defaultADUserName="ReportUser" defaultADPassword="password"/>
Thanks!

If a user is able to change the value of the Setting, then the web.config file is the wrong place to store the setting.
You should check out a User Scoped value in a Settings file instead.
MSDN - Using Settings in C#
When using settings like this, changing the value at runtime is easy:
Properties.Settings.Default.LdapConnectionString = "New Connection String";
Properties.Settings.Default.Save();

It's a bad idea to modify a *.config file from inside the program.
It's a bad idea for a webpage to modify any file in the root folder of your website.
It's a bad idea to have permission set allowing a web page the modification of files in the root folder of your website.
Basically, you need to forget about the web.config, and structure your code to use a connection string the exist only in memory.

var settings = ConfigurationManager.ConnectionStrings[ 0 ];
var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );
fi.SetValue(settings, false);
settings.ConnectionString = "Data Source=Something";

Even if it's a bad idea to modify the web.config file from inside an app, you can try this:
System.Configuration.ConfigurationManager.AppSettings.Set("keyToBeReplaced", "newKeyValue");

Related

creating absolute URLs that work on both localhost and live site

I want to populate a Literal control with a URL that will work on both my local machine and the live website.
For now, this is what I have:
string TheHost = HttpContext.Current.Request.Url.Host;
string ThePath = HttpContext.Current.Request.Url.AbsolutePath;
string TheProtocol = HttpContext.Current.Request.Url.Scheme;
string TheURL = "SomeText"
The URL that works when I type it manually in the browser looks like this:
http://localhost:12345/ThePageName
but when I run the above code it comes out as
localhost/ThePageName
What do I need to change so that on my local machine I output
http://localhost:12345/ThePageName
and on the live site I get
http://www.example.com/ThePageName
Use the fact that you've already got a Uri via the Request property - you don't need to do it all manually:
Uri pageUri = new Uri(HttpContext.Current.Request.Url, "/ThePageName");
Then build your tag using that - but ideally not just with string concatenation. We don't know enough about what you're using to build the response to say the best way to do it, but if you can use types which know how and when to use URI escaping etc, that will really help.
(I'd also suggest getting rid of your The prefix on every variable, but that's a somewhat different matter...)
Use UriBuilder to modify Urls. Assuming you need to just change path and keep all other parts the same:
var builder = new UriBuilder(HttpContext.Current.Request.Url);
builder.Path = "MyOtherPage";
return builder.Uri;
I don't believe you need to add the hostname for any of your urls in your site.
Just make all your url's relative to the root:
string TheURL = "SomeText"
or
string TheURL = "SomeText"
This will work fine regardless of the hostname.
Or Uri pageUri = new Uri(HttpContext.Current.Request.Url, "ThePageName"); without anti-slash
Just use different key/value in web.config and web.release.config files, and whenever you have to use it, read them from the web.config file.
Here is the example web.config:
<add key="Url" value="http://localhost:58980/" />
Here is the example web.release.config:
<add key="Url" value="http://example.com/" xdt:Transform="Replace" xdt:Locator="Match(key)"/>
This may work. Works for me.

.Net chatroom hash (eStreamChat)

I have a question specific to eStreamChat (An opensource Chatroom for .Net). There doesn't seem to be much in the way of documentation on their websites or any examples online so if anyone could help that would be great. I think that the problem is with my hash.
So far I have managed to download and import the project and set up a virtual IIS directory so that I can use it from my own application. I have created a link on one of my own webpages that brings me to their ChatRoom.aspx webpage. The link that brings me there is in the required format eg:
http://localhost:10833/eStreamChat/ChatRoom.aspx?id=lowens&timestamp=130425080917&hash=eb9fa849033cbf7b967ba472efb46363903f96dc
The page loads and I can see the chatroom but I get the following error popup: Unable to join room! Hash is invalid!
To get this far I have followed the instructions on this page:
The only line I didn't understand was this: You can configure the secret key from the web.config file so maybe if somebody could explain what I'm supposed to be doing in the web.config it might help.
The error that is being thrown is from the RemoteAuthUserProvider.cs. Here is the code:
NameValueCollection hrefParams = HttpUtility.ParseQueryString(hrefUri.Query);
var calculatedHash = Miscellaneous.CalculateChatAuthHash(hrefParams["id"] ?? String.Empty,
hrefParams["target"] ?? String.Empty, hrefParams["timestamp"]);
if (hrefParams["hash"] != calculatedHash)
{
throw new SecurityException("Hash is invalid!");
}
After debugging:
hrefParams["hash"] is "eb9fa849033cbf7b967ba472efb46363903f96dc" this is
calculatedHash is "5129cf1cf65350a387ce53a2b0d31c960f9d96d3"
So why is that hash not the same?
Cheers
In the Web.config in appSettings a value is needed:
<appSettings>
<add key="AuthSecretKey" value="ENTER A VALUE HERE"/>
</appSettings>
This value needs to match the secretKey in the click method provided on the website so that the hashes will match.

AuthenticationSection.Mode returns Windows when web.config is set to Forms

So my Web.Config File has:
<authentication mode="Forms">
<forms loginUrl="~/Home/Index" timeout="2880" />
</authentication>
in my Application_Start() i make the following calls
Configuration configuration = WebConfigurationManager.OpenWebConfiguration(null);
AuthenticationSection authentication = (AuthenticationSection)configuration.GetSection("system.web/authentication");
AuthenticationType = authentication.Mode;
The problem is that AuthenticationType ends up being Windows no matter what the value i set in the web.config file. I need to pull this value to process the page differently depending on how it is configured and can't seem to get the right values.
I think passing null to parameter of OpenWebConfiguration is making it open the configuration file of the machine.
If you read the MSDN docs on this. You'll notice it says that passing null will give you the root web.config.
So you may think that's what you want. But it's not. The root web.config is actually in the .NET installation path....
usually c:\windows\Microsoft.NET\Framework[.NET VERSION]\Config
Try passing the path of the Configuration file. Use this statement in place of path to get current website path
WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath)
this makes it sure you get the right config file every time , in any environment
Or just use the static ConfigurationManager.GetSection method which will open the config.file for the running application the code is executed it.
var authentication = (AuthenticationSection)ConfigurationManager.GetSection("system.web/authentication");
AuthenticationType = authentication.Mode;
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection.aspx
Retrieves a specified configuration section for the current application's default configuration.
May be it is referring wrong web.config. Here is something you might want to try:
Configuration webconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
System.Web.Configuration.SystemWebSectionGroup sysweb = (System.Web.Configuration.SystemWebSectionGroup)webconfig.GetSectionGroup("system.web");
System.Web.Configuration.AuthenticationSection authSection = sysweb.Authentication;
System.Web.Configuration.AuthenticationMode authmode = authSection.Mode;

Accessing web.config from Sharepoint web part

I have a VS 2008 web parts project - in this project is a web.config file:
something like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings/>
<system.web>
<appSettings>
<add key="MFOwner" value="Blah" />
</appSettings>
…….
In my web part I am trying to access values in the appSetting section:
I've tried all of the code below and each returns null:
string Owner = ConfigurationManager.AppSettings.Get("MFOwner");
string stuff1 = ConfigurationManager.AppSettings["MFOwner"];
string stuff3 = WebConfigurationManager.AppSettings["MFOwner"];
string stuff4 = WebConfigurationManager.AppSettings.Get("MFOwner");
string stuff2 = ConfigurationManager.AppSettings["MFowner".ToString()];
I've tried this code I found:
NameValueCollection sAll;
sAll = ConfigurationManager.AppSettings;
string a;
string b;
foreach (string s in sAll.AllKeys)
{
a = s;
b = sAll.Get(s);
}
and stepped through it in debug mode - that is getting things like :
FeedCacheTimer
FeedPageURL
FeedXsl1
ReportViewerMessages
which is NOT coming from anything in my web.config file....maybe a config file in sharepoint itself? How do I access a web.config (or any other kind of config file!) local to my web part???
thanks,
Phil J
Those values look like default SharePoint web.config properties. When you create a SharePoint web part, it gets deployed to the IIS virtual directory that hosts the SharePoint site which has it's own (very large) web.config file and NOT your application web.config file.
Depending on your production environment, you can update the SharePoint web.config file with the values you want and your code should work. If you cannot update the web.config file you can look into using a stand alone config file in the IIS directory that you deploy to (custom code then to read it) or possibly the property bag associated with each SP site collection for which you would need to add your values via code.

How do I "smoothly" format HttpHandler URI?

I'm just meddling in the ways of the RESTful web service in C# using ASP.Net 2.0 and have managed (via a class library, a reference to dll produced by the former and some adjustment of my web.config) to coax out a URI format like so:
http: //localhost/DevelopmentProject/testhandler/?input=thisismyinput
Which unremarkably just returns the input as a piece of text with the enlightening prefix "Your Input Was: "
I was under the impression that I could get the URI to become further ensmoothened to something more along the lines of:
http: //localhost/DevelopmentProject/testhandler/thisismyinput
and have the same result but have no idea how to get rid of the pesky "?input="
The entry to the httphandlers section of my web.config is (spaces added so code displays):
< add verb="*" path="testhandler/*" type="HandlerLib.testhandler, HandlerLib"/ >
I am running IIS 5.1 on the local machine, will this introduce a problem?
Essentially where am I going wrong?
Thanks.
One solution is to use UrlRewriting to rewrite the Url to what you need.
I use http://urlrewriter.net/ to do all my rewriting, and you could setup something like this in your scenario
<rewriter>
<rewrite
url="DevelopmentProject/testhandler/([\w]+)"
to="DevelopmentProject/testhandler/?input=$1" />
</rewriter>
This would remain "http: //localhost/DevelopmentProject/testhandler/thisismyinput" in your browser address bar, yet process as "http: //localhost/DevelopmentProject/testhandler/?input=thisismyinput"
You could implement URL rewriting, using something like URLRewriter.net
That would let you use the syntax you've mentioned.
I kinda cheated.
Try:
My Article About How I Got Round It
Change your config from:
< add verb="" path="testhandler/" type="HandlerLib.testhandler, HandlerLib"/ >
to:
< add verb="" path="testhandler/*" type="HandlerLib.testhandler, HandlerLib"/ >
Check out the value of Request.PathInfo in your handler's ProcessRequest function
with a URL like http://localhost/DevelopmentProject/testhandler/thisismyinput.
If that doesn't do it, make sure that IIS 5.1 is routing ALL requests to the aspnet_isapi.dll. (Although, it seems like it already is) This is the "Configuration..." button > "App Mappings" tab in your virtual directory in IIS.

Categories