What is ConfigurationManager.AppSettings? - c#

I'm using this, as a sample Authentication to try out. What I want to know is what happens in this line. i.e. ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]). Would somebody be kind enough to explain it?

You can set the default configurations for your application in web.config file and access them using the ConfigurationManager.AppSettings property.
e.g.
web.config
<configuration>
<appSettings>
<add key="highestScore" value="200" />
<add key="defaultSport" value="Cricket" />
</appSettings>
</configuration>
Code
int maxScore = Convert.ToInt32(ConfigurationManager.AppSettings["highestScore"]);
string Sport = ConfigurationManager.AppSettings["defaultSport"].ToString();

The ActiveDirectory.ResourceId app setting for the AuthBot example you referenced is:
<add key="ActiveDirectory.ResourceId" value="https://graph.windows.net/" />
The reason the .ResourceId is graph.windows.net as opposed to graph.microsoft.com is explained some here: https://github.com/matvelloso/AuthBot/pull/10
They are both valid. It only depends on which one you configure your
application in AAD for. Not everybody has Office 365 and therefore not
everybody will have graph.microsoft.com so I'd rather just leave it
with the option that is more likely going to work for most people
--Matt Velloso

Related

Write and access frequent changing information

I have a requirement where I need to write few information which will be changed frequently after the application gets deployed on server. Is there any way I can keep those information on some files of my asp.net application which when required can be updated and accessed in the application.
I tried to add the information in Web.config as that can be updated after deployment.Here is the code
<QueryConstants>
<add name ="SColumnName" value="UserId,First Name,Last Name,Description" />
<add name ="IColumnName" value="Company Name,Account Active Status" />
</QueryConstants>
but I am not able to access by the values from the keys.
How to achieve it ?
use app settings section as below in your web.config
<appSettings>
<add name ="SColumnName" value="UserId,First Name,Last Name,Description" />
<add name ="IColumnName" value="Company Name,Account Active Status" />
</appSettings>
then you can read as below
var sColumnName= ConfigurationManager.AppSettings["SColumnName"];
var iColumnName= ConfigurationManager.AppSettings["IColumnName"];
also check How do you modify the web.config appSettings at runtime?

Custom config elements collection in Web.config - Using a key to choose

Intro
I'm developing a WebApp built on C# ASP.NET.
I've been researching creating a "Custom Configuration" section with child elements in the Web.config file, and I've hit a bit of a snag when it comes to consuming the keys/values in the data.
I seem to be going round in circles and I don't know how to tackle the issue I'm having.
Situation
I have a few different Connection Strings defined in the Web.Config file, in the <connectionStrings> section. They are for dev, test, and live databases.
<connectionStrings>
<add name="connectionOne" connectionString="..." providerName="..." />
<add name="connectionTwo" connectionString="..." providerName="..." />
<add name="connectionThree" connectionString="..." providerName="..." />
</connectionStrings>
The WebApp is currently hard-coded to use one of these connection strings - if I need to change which one to use, I need to re-compile.
Desired Functionality
I'd like to define a section in the Web.config, let's say DbSettings.
In that, I'd then like to be able to define some child elements for, let's say DbSettings, in which I could define dbConnectionName, foo, bar etc. as attributes.
For example:
<dbSettings>
<dbSetting key="DbSetting1"
dbConnectionName="connectionOne"
foo="fooOne"
bar="barOne" />
... and so on
</dbSettings>
Then, perhaps in the <appSettings> section, define which of these DbSettings elements I want to use to get the settings from:
<appSettings>
<add name="dbSettingsKey" value="DbSetting1" />
</appSettings>
Desired Web.config section
Here is a fuller example of what I'd imagine my Web.config file to look like:
Connection Strings
<connectionStrings>
<add name="connectionOne" connectionString="..." providerName="..." />
<add name="connectionTwo" connectionString="..." providerName="..." />
<add name="connectionThree" connectionString="..." providerName="..." />
</connectionStrings>
App Settings
<add key="dbSettingsKey" value="DbSetting1" /> // or 2, or 3 etc.
DbSettings (custom section)
<dbSettings>
<dbSetting key="DbSetting1"
dbConnectionName="connectionOne"
foo="fooOne"
bar="barOne" />
<dbSetting key="DbSetting2"
dbConnectionName="connectionTwo"
foo="fooTwo"
bar="barTwo" />
<dbSetting key="DbSetting3"
dbConnectionName="connectionThree"
foo="fooThree"
bar="barThree" />
</dbSettings>
My question...
How the devil am I going to get this desired functionality in the C# code?
I've read loads on "creating your own custom section", and similarly "creating a custom config collection". But, I just can't seem to glue it all together to apply for my situation.
I'd like to be able to have a class (like the one I'm using at the moment with the hard-coded strings), which I can reference necessary properties (as I am doing, at the moment) - and then the code can dynamically load the correct settings at run-time from the sections I've described above.
As always, thank you in advance for your suggestions and help.
I agree with the comments. The way this is usually done is you deploy a different web.config to each environment. When your deployment group (or you) deploys, you deploy everything EXCEPT the web.config unless you have changes to push.
In answer to your other question, adding a custom section is not trivial. It's quite a bit of work. Custom section handler which requires a whole bunch of configuration element classes and a bunch of configuration element collection classes... and then, if you want it to "work" correctly, you also need to create a schema and register that with the IDE, etc.
For your particular case, I'd just do it the "normal" way :).

Castle Windsor / ActiveRecord / NHibernate: How to intercept/modify connection string

I have consolidated the connection string information for a number of C# .NET solutions that are in my possession. Previously, each project was storing its connection string in its own format, requiring me to modify several files for each installation of the software.
Only one remaining solution is giving me trouble. This particular solution uses Castle Windsor 2.0, ActiveRecord 2.0 and NHibernate 2.1. The code reads its configuration from an XML file. I wish to remove the connection string from the config file and set it programmatically in the code.
Here is the relevant section of code that initiates Windsor:
windsorContainer = new WindsorContainer(new XmlInterpreter(xmlFileName));
windsorContainer.Resolve<IWindsorConfigurator>().Configure(windsorContainer);
logger = windsorContainer.Resolve<ILogger>();
Here are the contents of the XML file:
<?xml version="1.0"?>
<configuration>
<properties>
<connectionString>Server=*****;Database=*****;User Id=*****;Password=*****</connectionString>
</properties>
<facilities>
<facility id="logging" type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging" loggingApi="log4net" configFile="Configs/log4net.config" />
<facility id="atm" type="Castle.Facilities.AutomaticTransactionManagement.TransactionFacility, Castle.Facilities.AutomaticTransactionManagement" />
<facility id="arfacility" type="Castle.Facilities.ActiveRecordIntegration.ActiveRecordFacility, Castle.Facilities.ActiveRecordIntegration" isDebug="false" isWeb="false">
<!-- Configure the namespaces for the models using Active Record Integration -->
<assemblies>
<item>ChronoSteril.Application</item>
</assemblies>
<config>
<add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
<add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
<add key="connection.connection_string" value="#{connectionString}" />
<add key="hibernate.cache.provider_class" value="NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache" />
<add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
<add key="hibernate.expiration" value="60" />
</config>
</facility>
</facilities>
<components>
<component id="windsorConfigurator" service="ChronoSteril.Application.IWindsorConfigurator, ChronoSteril.Application" type="ChronoSteril.WinApp.ClarionIntegrationWindsorConfigurator, ChronoSteril.WinApp" />
</components>
I am not familiar with Windsor. During my Google tour, I did see some code that adds facilities programmatically, but those examples were not valid for my version of Windsor (I assume).
Question: Can anyone guide me in removing the connection string information from the XML file and allow me to set it in the code?
Thank you!
I managed to accomplish my intention. It is not ideal, but will work until the code base is rewritten. (I cannot wait to drop the existing code like a bad dream.)
Patrick's comment, under my initial question, let me to refine my search criteria, which yielded the thread located here.
My XML file remains the same, except that I use bogus values for the connection string information. I will never need to modify these, and they do not reveal any valid connection information. This was my intention. I still have not discovered how to successfully remove the ActiveRecord configuration from the XML file and configure using code.
I now call a method that contains the following code:
ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
NHibernate.Cfg.Configuration configuration = sessionFactoryHolder.GetConfiguration(typeof(ActiveRecordBase));
connectionString = ReadConnectionString();
configuration.SetProperty("connection.connection_string", connectionString);
This works for me. I hope that it can also help someone else who is in the same position as I was.

Adding and reading a custom section in AppSettings in C#

I hope you can help me.
I'm supposed to add a new type of values to an AppSettings file (already existing with some values). Those values are a whole list of special folders so I thought the best way would be to have a new section for those folder values so that the file would look like this:for
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="usPath" value="folderName1" />
<add key="tcPath" value="folderName2" />
<add key="usGUID" value="folderID1" />
<add key="tcGUID" value="folderID2" />
</appSettings>
<updateFolders>
<add key="folderID3" value="folderName3">
<add key="folderID4" value="folderName4">
</updateFolders>
</configuration>
Reading and writing within the already existing appSettings-tag is no problem but I haven't find a way yet to modify the updateFolders section. I'm really new to using AppSettings in this way so I don't know too much about what's possible and what's not. In addition to that I think the AppSettings file might have been set up in a wrong way from the very beginning (it gets created by using a System.IO.File-Writer).
see ConfigurationManager.GetSection
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection(v=vs.110).aspx

Using ELMAH and URLRewritingNet Together

I have ELMAH setup on my production server and it has done a fantastic job of letting me know about any niggles - as well as any creative SQL injection!
I've decided to introduce URl Rewriting and went for http://www.urlrewriting.net/ in the end. It was nice and easy to setup and it's doing exactly what I want with the customer-facing site.
The problem is ELMAH. Because I've set the urlrewritingnet node in my config like so:
<urlrewritingnet
rewriteOnlyVirtualUrls="true"
contextItemsPrefix="QueryString"
defaultPage = "default.aspx"
defaultProvider="RegEx"
xmlns="http://www.urlrewriting.net/schemas/config/2006/07" >
...ELMAH likes to do this to it's axd links;
http://www.mydomain.com/elmah.axd/stylesheet/default.aspx
Does anyone have any idea how to either
a) stop the re-writer following the .axd; or
b) add rules to the re-writer to get ELMAH to work
Any ideas? I'm happy to hack about with the httpHandlers...
I had the same issue - urlrewritingnet messing up my elmah - but found an answer here: http://markmail.org/message/ctbh6ozzqpe4qn6j#query:+page:1+mid:ctbh6ozzqpe4qn6j+state:results
Basically set defaultPage to empty like this:
Before (shortened):
<urlrewritingnet defaultPage="default.aspx" ... >
After (shortened):
<urlrewritingnet defaultPage="" ... >
Now all css styles work for Elmah.
I came up with a simpler solution if others are interested.
I just modify the source code directly and add in some basic logic to ignore specific rewrite rules.
I kind of solved this, but not in the way I wanted too. For the reference of others, I will provide a breakdown of what I did and the resources;
ELMAH: http://code.google.com/p/elmah/
URLRewritingNet: http://www.urlrewriting.net/149/en/home.html
This was really the only available option to me: http://csharpin.blogspot.com/2009/03/using-urlrewritingnet-and-elmah.html, but I had untold difficulty to get the code into my existing architecture without other adverse affects. I did try adding rules to the ExternalRewrite.config (URL Rewrite) to ignore *.axd, but that didn't pan out either. I was getting all sorts of weird behaviour.
I then decided to use Health Monitoring: https://web.archive.org/web/20211020102851/https://www.4guysfromrolla.com/articles/031407-1.aspx instead of ELMAH. Sorry ELMAH :(
Health Monitoring was a snip to setup and then all I had to do was solve the nasty postback problem on rewritten URLs;
Health Monitoring web.config;
<!--he-mon-->
<healthMonitoring enabled="true">
<eventMappings>
<clear />
<add name="All Errors" type="System.Web.Management.WebBaseErrorEvent" startEventCode="0" endEventCode="2147483647" />
</eventMappings>
<providers>
<clear />
<add connectionStringName="healthMonitoringConnectionString" maxEventDetailsLength="1073741823" buffer="false" name="SqlWebEventProvider" type="System.Web.Management.SqlWebEventProvider" />
<add type="System.Web.Management.SimpleMailWebEventProvider" name="EmailWebEventProvider" from="xxx" to="yyy" bodyHeader="zzz" bodyFooter="000" buffer="false" />
</providers>
<rules>
<clear />
<add name="All Errors Default" eventName="All Errors" provider="SqlWebEventProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
<add name="All Errors Default Email" eventName="All Errors" provider="EmailWebEventProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:00:00" />
</rules>
</healthMonitoring>
<!--he-mon-->
Add the connection string to the connectionString node too.
To fix the rather nasty postback on URL rewritten strings, I tried ScottGu's suggestion; Handling ASP.NET PostBacks with URL Rewriting: http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx, but I couldn't get that to work at all.
Starting to really regret getting into URL Rewriting, I finally added this to the one problematic page I had; Me.Form.Action = Me.Request.RawUrl within the Page_Load and it worked a treat.
I know this doesn't directly answer the question, but I hope it helps. I hope someone finds my information at least somewhat useful.

Categories