How to read custom section data in web.config with minimum code - c#

here is my custom section in web.config. now i want read data by c#
<configuration>
<MailList>
<MailID id="test-uk#mysite.com" Value="UK" />
<MailID id="test-us#mysite.com" Value="US" />
<MailID id="test-ca#mysite.com" Value="CA" />
</databases>
</configuration>
suppose i want technique by which i can only read data based on value. if i supply UK as value then function will return uk mail id test-uk#mysite.com.
guide me how easily i can do this writing very minimum code. thanks

First of all your XML seems to be broken:
It must be something like that:
<configuration>
<MailList>
<MailID id="test-uk#mysite.com" Value="UK" />
<MailID id="test-us#mysite.com" Value="US" />
<MailID id="test-ca#mysite.com" Value="CA" />
</MailList>
</configuration>
This code should do what you want:
string country = "UK";
var result =
XDocument.Load("~/web.config")
.Element("configuration")
.Element("MailList")
.Elements("MailID")
.First(el => el.Attribute("Value").Value.Equals(country))
.Attribute("id")
.Value;
Console.WriteLine(result);

You could use the appsettings tag in your webconfig like:
<configuration>
<appSettings>
<add key="test-uk#mysite.com" value="UK" />
<add key="test-us#mysite.com" value="US" />
<add key="test-ca#mysite.com" value="CA" />
And after that you have your class:
public class WebConfigreader
{
public static string AppSettingsKey(string key)
{
if (WebConfigurationManager.AppSettings != null)
{
object xSetting = WebConfigurationManager.AppSettings[key];
if (xSetting != null)
{
return (string)xSetting;
}
}
return "";
}
}
And in your logic you are calling just:
String strUk = WebConfigreader.AppSettingsKey("test-uk#mysite.com");

Related

How to create a site map using DNN and C#

My website is http://www.bodytshirt.com
This site is built from DotNetNuke. It has default sitemap is http://www.bodytshirt.com/sitemap.aspx
This sitemap only shows the page URL without any parameters. I want my site map to show all product in my database. Such as http://www.bodytshirt.com/product/id/141/key/i-am-a-software-engineer
Please give my suggestion. Should I create a custom sitemap for my requirement?
You can do this with the Sitemap provider in DNN. My open source DNNSimpleArticle module has an example of this:
https://github.com/ChrisHammond/dnnsimplearticle/blob/6d5d2c5bb074dd2bdede40fac4eb3c78408ab884/Providers/Sitemap/Sitemap.cs
public override List<SitemapUrl> GetUrls(int portalId, PortalSettings ps, string version)
{
var listOfUrls = new List<SitemapUrl>();
foreach (Article ai in ArticleController.GetAllArticles(portalId))
{
var pageUrl = new SitemapUrl
{
Url = ArticleController.GetArticleLink(ai.TabID, ai.ArticleId),
Priority = (float)0.5,
LastModified = ai.LastModifiedOnDate,
ChangeFrequency = SitemapChangeFrequency.Daily
};
listOfUrls.Add(pageUrl);
}
return listOfUrls;
}
Then you will need to register that, you can do it with the .DNN file
https://github.com/ChrisHammond/dnnsimplearticle/blob/6d5d2c5bb074dd2bdede40fac4eb3c78408ab884/dnnsimplearticle.dnn
<component type="Config">
<config>
<configFile>web.config</configFile>
<install>
<configuration>
<nodes>
<node path="/configuration/dotnetnuke/sitemap/providers" action="update" key="name" collision="overwrite">
<add name="DNNSimpleArticleSiteMapProvider" type="Christoc.Modules.dnnsimplearticle.Providers.Sitemap.Sitemap, DNNSimpleArticle" providerPath="~\DesktopModules\dnnsimplearticle\Providers\Sitemap\" />
</node>
</nodes>
</configuration>
</install>
<uninstall>
<configuration>
<nodes />
</configuration>
</uninstall>
</config>
</component>

unable to Read the config file data from local drive

I fail to read the appSettings from a config file. It is not located in the default location so when I tried using var aWSAccessKey = ConfigurationManager.AppSettings["AWSAccessKey"]; it didn't work.
Config file:
<appSettings>
<add key="AWSAccessKey" value="1" />
<add key="AWSSecretKey" value="2" />
<add key="AWSRegion" value="4" />
<add key="AWSAccountNumber" value="5" />
</appSettings>
Also tried with no success:
var fileMap = new ConfigurationFileMap("D:AWS\\CoreLocalSettings.config");
var configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
var sectionGroup = configuration.GetSectionGroup("applicationSettings");
Finally it's working:
In the app.config file I read the outside config file data as below
<configuration>
<appSettings file="D:\AWS\CoreLocalSettings.config">
.......
</appSettings>
</configuration>
In the code base I am accessing same using the ConfigurationManager
var strAWSAccessKey = ConfigurationManager.AppSettings["AWSAccessKey"];
var web = System.Web.Configuration.WebConfigurationManager
.OpenWebConfiguration(#"D:\Employee\Hitesh\Projects\Web.config");
var appValue = web.AppSettings.Settings["SMTPServerPort"].Value;
var AWSAccessKey = ConfigurationManager.AppSettings["AWSAccessKey"];

Write appSettings in external file

I have a config file app.exe.config and appSettings section has something like this:
<configuration>
<appSettings configSource="app.file.config" />
</configuration>
app.file.config file has something like this:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="var1" value="value 1" />
<add key="var2" value="value 2" />
<add key="var3" value="value 3" />
</appSettings>
I need to edit var1, var2 and var3 at runtime and I have code like this:
Configuration config = ConfigurationManager.OpenExeConfiguration("...path\app.exe);
config.AppSettings.SectionInformation.ConfigSource = "app.file.config";
config.AppSettings.Settings["var1"].Value = "value 11";
config.AppSettings.Settings["var2"].Value = "value 22";
config.AppSettings.Settings["var3"].Value = "value 33";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
When I run config.Save.... the file app.file.config has a appSettings node with an attribute "file". This attribute has the value to app.file.config
<appSettings file="app.file.config">
<add key="var1" value="value 1" />
<add key="var2" value="value 2" />
<add key="var3" value="value 3" />
</appSettings>
Now, if I try to load the config file, I have an exception with message "Unrecognized attribute 'file'. Note that attribute names are case-sensitive." in app.file.config.
If I delete the file attribute manually, the configuration file is loaded properly.
Any ideas?
How can avoid to write file attribute when I save config files.
Thanks
using an external config file is transparent for the application,
this part is o.k
</configuration>
<appSettings configSource="app.file.config" />
</configuration>
and also this:
<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="var1" value="value 1" />
<add key="var2" value="value 2" />
<add key="var3" value="value 3" />
</appSettings>
change your code to be like this:
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings["var1"].Value = "value 11";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
referring an external configuration file is transparent to the application,
so you don't have to call it directly. you can use the default appSetting section in the configuration manager.
Good luck
A more complete answer to prevent confusion:
Setup:
Commandline project called 'app'
app.exe.config file, App.config:
<appSettings file="App.Settings.config"></appSettings>
App.Settings.config file with 'Copy to Output Directory'= 'Copy Always'
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="test" value="OVERRIDDEN"/>
</appSettings>
Program.cs:
static void Main(string[] args)
{
try
{
Console.WriteLine("Local Config sections");
var exepath = (new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath;
Configuration config = ConfigurationManager.OpenExeConfiguration(exepath);
config.AppSettings.SectionInformation.ConfigSource = "App.Settings.config";
Console.WriteLine("BEFORE[test]=" + config.AppSettings.Settings["test"].Value);
Console.WriteLine($"BEFORE[testExternalOnly]={config.AppSettings.Settings["testExternalOnly"]?.Value}");
//to avoid: Error CS0266
//Explicitly cast 'System.Configuration.AppSettingsSection'
AppSettingsSection myAppSettings = (AppSettingsSection)config.GetSection("appSettings");
myAppSettings.Settings["test"].Value = "NEW";
if (!myAppSettings.Settings.AllKeys.Contains("testExternalOnly"))
myAppSettings.Settings.Add("testExternalOnly", "NEWEXTERNAL");
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
//Read updated config
Console.WriteLine("AFTER[test]=" + config.AppSettings.Settings["test"].Value);
Console.WriteLine("AFTER[testExternalOnly]=" + config.AppSettings.Settings["testExternalOnly"].Value);
Console.WriteLine("AFTER CONFIG EXTERNAL FILE: " + System.IO.File.ReadAllText("App.Settings.config"));
Console.WriteLine("AFTER CONFIG FILE: " + System.IO.File.ReadAllText(System.AppDomain.CurrentDomain.FriendlyName + ".config"));
//Shut current config
config = null;
//Open config
config = ConfigurationManager.OpenExeConfiguration(exepath);
config.AppSettings.SectionInformation.ConfigSource = "App.Settings.config";
Console.WriteLine("AFTER[test]=" + config.AppSettings.Settings["test"].Value);
Console.WriteLine("AFTER[testExternalOnly]=" + config.AppSettings.Settings["testExternalOnly"].Value);
Console.WriteLine("AFTER CONFIG EXTERNAL FILE: " + System.IO.File.ReadAllText("App.Settings.config"));
Console.WriteLine("AFTER CONFIG FILE: " + System.IO.File.ReadAllText(System.AppDomain.CurrentDomain.FriendlyName + ".config"));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("press the ENTER key to end");
Console.ReadLine();
}
This will result in App.Settings.config file updated to be on the filesystem as:
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="test" value="NEW" />
<add key="testExternalOnly" value="NEWEXTERNAL" />
</appSettings>
Finally, I have found a solution.
The solution is to declare the config file as this:
<appSettings configSource="app.file.config">
<add key="var1" value="value 1" />
<add key="var2" value="value 2" />
<add key="var3" value="value 3" />
</appSettings>
And from code
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
AppSettingsSection myAppSettings = config.GetSection("appSettings")
myAppSettings.Settings["var1"].Value = "value 11";
config.Save(ConfigurationSaveMode.Modified);
Note that I use
GetSection("appSettings")
instead of
config.AppSettings.Settings
Thanks to all that help people in StackOverflow.

Custom Config section in App.config C#

I'm a quite beginner with config sections in c#
I want to create a custom section in config file. What I've tried after googling is as the follows
Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="MyCustomSections">
<section name="CustomSection" type="CustomSectionTest.CustomSection,CustomSection"/>
</sectionGroup>
</configSections>
<MyCustomSections>
<CustomSection key="Default"/>
</MyCustomSections>
</configuration>
CustomSection.cs
namespace CustomSectionTest
{
public class CustomSection : ConfigurationSection
{
[ConfigurationProperty("key", DefaultValue="Default", IsRequired = true)]
[StringValidator(InvalidCharacters = "~!##$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)]
public String Key
{
get { return this["key"].ToString(); }
set { this["key"] = value; }
}
}
}
When I use this code to retrieve Section I get an error saying configuration error.
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("CustomSection");
What am I missing?
Thanks.
Edit
What I need ultimately is
<CustomConfigSettings>
<Setting id="1">
<add key="Name" value="N"/>
<add key="Type" value="D"/>
</Setting>
<Setting id="2">
<add key="Name" value="O"/>
<add key="Type" value="E"/>
</Setting>
<Setting id="3">
<add key="Name" value="P"/>
<add key="Type" value="F"/>
</Setting>
</CustomConfigSettings>
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="customAppSettingsGroup">
<section name="customAppSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</sectionGroup>
</configSections>
<customAppSettingsGroup>
<customAppSettings>
<add key="KeyOne" value="ValueOne"/>
<add key="KeyTwo" value="ValueTwo"/>
</customAppSettings>
</customAppSettingsGroup>
</configuration>
Usage:
NameValueCollection settings =
ConfigurationManager.GetSection("customAppSettingsGroup/customAppSettings")
as System.Collections.Specialized.NameValueCollection;
if (settings != null)
{
foreach (string key in settings.AllKeys)
{
Response.Write(key + ": " + settings[key] + "<br />");
}
}
Try using:
var cf = (CustomSection)System.Configuration.ConfigurationManager.GetSection("MyCustomSections/CustomSection");
You need both the name of the section group and the custom section.
Highlight ConfigurationSection press F1,
You will see that the implementation on the MSDN website overrides a property called "Properties" which returns a "ConfigurationPropertyCollection", as your properties have a matching attribute of that type you should be able to populate this collection with your properties if not wrap them in the same way the MS guys have.

How to read a section from web.config on IIS7 w/ .net 4 in C#

I've got the following section in my web.config:
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="0.00:00:30" />
<remove fileExtension=".ogv" />
<mimeMap fileExtension=".ogv" mimeType="video/ogg" />
<remove fileExtension=".webm" />
<mimeMap fileExtension=".webm" mimeType="video/webm" />
<!-- and a bunch more... -->
</staticContent>
<!-- ... -->
</system.webServer>
Here's what I'm trying to do in psuedo-code:
var ext = ".ogg";
var staticContentElements = GetWebConfig().GetSection("system.webServer/staticContent").ChildElements;
var mimeMap = staticContentElements.Where(c =>
c.GetAttributeValue("fileExtension") != null &&
c.GetAttributeValue("fileExtension").ToString() == ext
).Single();
var mimeType = mimeMap.GetAttributeValue("mimeType").ToString();
Basically, I need to search the mimeMaps by a fileExtension and get their mimeType.
You need to create a custom configuration section to get that information.
George Stocker's answer led me to a Google search for["staticContent" custom configuration section] which brought me to an iis.net article titled Adding Static Content MIME Mappings <mimeMap>.
The article led me to come up with:
using (var serverManager = new ServerManager())
{
var siteName = HostingEnvironment.ApplicationHost.GetSiteName();
var config = serverManager.GetWebConfiguration(siteName);
var staticContentSection = config.GetSection("system.webServer/staticContent");
var staticContentCollection = staticContentSection.GetCollection();
var mimeMap = staticContentCollection.Where(c =>
c.GetAttributeValue("fileExtension") != null &&
c.GetAttributeValue("fileExtension").ToString() == ext
).Single();
var mimeType = mimeMap.GetAttributeValue("mimeType").ToString();
contentType = mimeType.Split(';')[0];
}
Which works perfectly for me. I just need to add some null checks here and there and it should be good to go.

Categories