Accessing web.config from Sharepoint web part - c#

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.

Related

.cscfg file gives error when i specify <Setting name="serilog:write-to:AzureDocumentDB.endpointUrl" />

When I publish my API project to Azure here is the error what i'm getting.
Is there any way to resolve this issue and here is the code and the problem comes when this symbol ":" is init.
Here are some more details.
It's a web API Project
Version 4.6
Locally it's running without any issues but when it comes to release automation I should be able to change the value of endpointurl , key, and TTL manually so that I need to modify .csfg and .csdef file environment to environment. When i do that .csdef does not support that colon mark ":" so the build fails.
Expecting : Build is successful so that the log works as expected.
Actual : Build fails and log is not working as expected.
As you mentioned that ServiceDefinition:NamedElementNameString doesn't allow ':' (colon) in name. But we could add it with Azure friendly name. Then we could get it with following code. I also do a demo on my side, it works as expected.
var endpoint = RoleEnvironment.GetConfigurationSettingValue("endpointUrl");
var authorizationKey = RoleEnvironment.GetConfigurationSettingValue("authorizationKey");
var logger = new LoggerConfiguration()
.WriteTo.Console() //if no writeto.console there is no document in documentdb
.WriteTo.AzureDocumentDB(endpoint, authorizationKey)
.CreateLogger();
logger.Information("Tom Test");//log demo
About .csdef configuration please refer to the screenshot.
We could get more information from Configure Azure cloud service roles with Visual Studio
Check from Azure Portal:
Related serilog sdk
It seems this is not supported.
ServiceDefinition:NamedElementNameString doesn't allow ':' (colon) in name
So that I implemented custom configuration values and extract the values at run-time when the logger is initialized.
Here is the implementation.
.cscfg, .csdef, and web.config contains
<add key="LogEndpointUrl" value="xxxxxx/" />
<add key="LogAuthorizationKey" value="xxxxxxxxxxxxxxx=" />
<add key="LogTTL" value="1" />
When initializing got the values as follows from web.config
var endpoint = Common.Configuration.GetSetting(Constants.AppSettings.LogEndpointUrl);
var authorizationKey = Common.Configuration.GetSetting(Constants.AppSettings.LogAuthorizationKey);
int ttl = (int)Convert.ToInt64((Common.Configuration.GetSetting(Constants.AppSettings.LogTTL)));
And then
Log.Logger = new LoggerConfiguration().ReadFrom.AppSettings().WriteTo.AzureDocumentDB(endpoint, authorizationKey,timeToLive: ttl).CreateLogger();
// Used to debug serilog itself and confirm it is writing entries to document db
Serilog.Debugging.SelfLog.Enable(Console.Out);
var errorOrInformation = new Dictionary<string, string>();
errorOrInformation.Add(Constants.LoggingProperties.PartitionKey, logMetadata.PartitionKey);
errorOrInformation.Add(Constants.LoggingProperties.RowKey, logMetadata.RowKey);
//Add as many items as you want
Log.Verbose("Log Information Message {Information}", errorOrInformation);
// Also good idea to force flush of log entries before the app ends
Log.CloseAndFlush();

ClickOnce change WS URL dynamically

I develop the ClickOnce application (C# Framework 4.5)
It access data through Web Service.
We have three environments: dev, test and prod.
Each environment - another server name.
I would like to make one publish and copy it to each environment with external tool.
Problem, to access correct url for web service for each environment.
I need to change url dynamically in code for each environment.
I add to app.config the WS references
<add key="ws_url_local" value="http://localhost/app/ws.asmx" />
<add key="ws_url_prod" value="http://server_prod/app/ws.asmx" />
<add key="ws_url_test" value="http://server_test/app/ws.asmx" />
<add key="ws_url_dvlp" value="http://server_dvlp/app/ws.asmx" />
I make a publish into folder, and then, another system copy the folder to
all environments.
How I can change dynamically the url by environment in code?
switch(fromWhereInstaled?){
case "prod":
url = ConfigurationManager.AppSettings["ws_url_prod"];
break;
case "test":
...
}
Thanks for help!
Found solution:
string url = ConfigurationManager.AppSettings["url_ws_local"];
if(ApplicationDeployment.IsNetworkDeployed)
{
ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
if(ad.ActivationUri.AbsolutePath.Contains("prodservername"))
{
url = ConfigurationManager.AppSettings["url_ws_prod"];
}
else if ad.ActivationUri.AbsolutePath.Contains("testservername")
.....
}
ws.Url = url;
But if you move your application without update ActivationUri, use this solution:
string url = ConfigurationManager.AppSettings["url_ws_local"];
if(AppDomain.CurrentDomain.SetupInformation.ActivationArgument != null && AppDomain.CurrentDomain.SetupInformation.ActivationArgument.ActivationData != null) // Network published
{
string strParam = AppDomain.CurrentDomain.SetupInformation.ActivationArgument.ActivationData[0];
if(strParam.Contains("prodservername"))
{
url = ConfigurationManager.AppSettings["url_ws_prod"];
}
else if ...
}
ws.Url = url;
But don't forget go to Properties=>Publish>Options=>Manifests, and check:
Allow URL parameters to be passed to application.
Also in this way you can change url for check updates.

IIS Error: Unrecognized configuration path 'MACHINE/WEBROOT/APPHOST/websiteName

I am trying to set IP Address and Domain Restrictions in the c# code, i am following this article, but it gives me unrecognized location error.
Error: Unrecognized configuration path 'MACHINE/WEBROOT/APPHOST/websiteName
My Code:
using (var serverManager = new ServerManager())
{
var config = serverManager.GetApplicationHostConfiguration();
var ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "websiteName");
var ipSecurityCollection = ipSecuritySection.GetCollection();
var addElement = ipSecurityCollection.CreateElement("add");
addElement["ipAddress"] = #"SomeIP";
addElement["allowed"] = false;
ipSecurityCollection.Add(addElement);
var addElement1 = ipSecurityCollection.CreateElement("add");
addElement1["ipAddress"] = #"SomeIP";
addElement1["subnetMask"] = #"255.255.0.0";
addElement1["allowed"] = false;
ipSecurityCollection.Add(addElement1);
serverManager.CommitChanges();
}
It gives me error after this line:
var ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "websiteName");
Can any one tell what is wrong, or something that i have missed.
You might get a broken applicationHost.config for IIS/IIS Express, where the web site fails to have a root application. If you don't know how to edit that, post the <sites> tag of your file in the question so that others can review and suggest how to fix.
Aging question, but I thought I'd share my solution.
The location parameter must match the location path in your applicationHost.config file. This means that if websiteName is actually an application under another site, e.g. Default Web Site, its location section will look like this:
<location path="Default Web Site/websiteName">
<system.webServer>
<.../>
</system.webServer>
</location>
If so, your line 5 should look like this:
var ipSecuritySection = config.GetSection("system.webServer/security/ipSecurity", "Default Web Site/websiteName");

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;

Dynamically change connectionString in web.config

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");

Categories