Reading specific section of App.config - c#

I'm trying to get the values from the oracle.manageddataaccess.client section in my App.config file. This section looks like this:
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="alias1" descriptor="connection string 1" />
<dataSource alias="alias2" descriptor="connection string 2" />
</dataSources>
</version>
</oracle.manageddataaccess.client>
I've tried using the ConfigurationManager API to read the values, but I haven't had any luck.
With:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["oracle.manageddataaccess.client"]
just returns an empty string.
config.Sections seems to only work for tags that are explicitly a section tag.
I just need to be able to read the dataSource values in this section.
Update:
config.Sections["oracle.manageddataaccess.client"].SectionInformation returns information about the section, and the GetRawXml() is getting closer to what I want, but I'm trying to get a specific subset of this.

I didn't find exactly what I was looking for, but I found a way around it.
If anyone else has the same issue, you can use XDocument and Linq to filter for what you need. You need to include your using statements: System.Linq and System.Xml.Linq
XDocument doc = XDocument.Parse(config.Sections["oracle.manageddataaccess.client"].SectionInformation.GetRawXml());
var value = from node in doc.Descendants("dataSource")
where node.Attribute("alias").Value == whatever
select node.Attribute("descriptor").Value;

Related

What is wrong with this file or code?

What is happening \ what is the difference ?
I'm trying to return a specific node from an XML File.
XML File:
<?xml version="1.0" encoding="utf-8"?>
<JMF SenderID="InkZone-Controller" Version="1.2">
<Command ID="cmd.00695" Type="Resource">
<ResourceCMDParams ResourceName="InkZoneProfile" JobID="K_41">
<InkZoneProfile ID="r0013" Class="Parameter" Locked="false" Status="Available" PartIDKeys="SignatureName SheetName Side Separation" DescriptiveName="Schieberwerte von DI" ZoneWidth="32">
<InkZoneProfile SignatureName="SIG1">
<InkZoneProfile Locked="False" SheetName="S1">
<InkZoneProfile Side="Front" />
</InkZoneProfile>
</InkZoneProfile>
</InkZoneProfile>
</ResourceCMDParams>
</Command>
<InkZoneProfile Separation="Cyan" ZoneSettingsX="0 0,005 " />
</JMF>
Code:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("C:\\test\\test.xml");
XmlNode root = xmlDoc.DocumentElement;
var parent = root.SelectSingleNode("/JMF/Command/ResourceCmdParams/InkZoneProfile/InkZoneProfile/InkZoneProfile/InkZoneProfile");
XmlElement IZP = xmlDoc.CreateElement("InkZoneProfile");
IZP.SetAttribute("Separation", x.colorname);
IZP.SetAttribute("ZoneSettingsX", x.colorvalues);
xmlDoc.DocumentElement.AppendChild(IZP);
xmlDoc.Save("C:\\test\\test.xml");
The var parent returns me null. I've debugged , and root and xmlDoc have on their inner text the XML Content.
But, a test made here(made by user #har07 , on the previous question:
SelectSingleNode returns null even with namespace managing
Worked without problems.
https://dotnetfiddle.net/vJ8h9S
What is the difference between those two ? They follow the same code basically, but one works and other doesn't.
When debugging i've found that root.InnerXml has the contents loaded on itself (same as XmlDoc.InnerXml ). But InnerXml doesn't implement a method to SelectSingleNode. I believe that if i save it to a string i'll probably lose indentation and etc.
Can someone tell me what is the difference or what is wrong ? Thanks !
XML Sample: https://drive.google.com/file/d/0BwU9_GrFRYrTUFhMYWk5blhhZWM/view?usp=sharing
SetAttribute don't auto escape string for you. Therefore it make your XML file invalid.
From MSDN about XmlElement.SetAttribute
Any markup, such as syntax to be recognized as an entity reference, is treated as literal text and needs to be properly escaped by the implementation when it is written out
Find in your code all line contain SetAttribute and use SecurityElement.Escape to escape the value.
For example: Change these lines:
IZP.SetAttribute("Separation", x.colorname);
IZP.SetAttribute("ZoneSettingsX", x.colorvalues);
To:
using System.Security;
IZP.SetAttribute("Separation", SecurityElement.Escape(x.colorname));
IZP.SetAttribute("ZoneSettingsX", SecurityElement.Escape(x.colorvalues));
If an attribute have name contains any of <>"'& you also have to escape it like the value.
Note:
You have to delete current xmls you create used the old code, because it is invalid, when you load it will cause exception.

C#: Get value from custom .config file

I'd like to get a value from this config file from within an MVC view. How is this achieved?
Thanks
UnsupportedBrowsers.config (projectRoot/config/..)
<UnsupportedBrowsers>
<Browser alias="Internet Explorer">
<Version>
<add key="ie6" value="IE6"/>
<add key="ie7" value="IE7"/>
<add key="ie8" value="IE8"/>
</Version>
</Browser>
</UnsupportedBrowsers>
First, it would be better to do it in the Controller rather than in the View.
Second, reading an XML file is an easy task, use XDocument class for example:
var xDoc = XDocument.Load("projectRoot\config\UnsupportedBrowsers.config");
var versionKeys = xDoc.Descendants("Version").First().Descendants();
foreach(var key in versionKeys)
{
//Do something with the retrived keys..
}
Side note:
In any case, you're better cache this object in order to avoid of I/O blockings if each new incoming request need to use it.

Pivotviewer's .cxml parsing

I'm trying to do very simple operations on a .cxml file. As you know it's basically an .xml file. This is a sample file I created to test the application:
<?xml version="1.0" encoding="utf-8"?>
<Collection xmlns:p="http://schemas.microsoft.com/livelabs/pivot/collection/2009" SchemaVersion="1.0" Name="Actresses" xmlns="http://schemas.microsoft.com/collection/metadata/2009">
<FacetCategories>
<FacetCategory Name="Nationality" Type="LongString" p:IsFilterVisible="true" p:IsWordWheelVisible="true" p:IsMetaDataVisible="true" />
</FacetCategories>
<!-- Other entries-->
<Items ImgBase="Actresses_files\go144bwo.0ao.xml" HrefBase="http://www.imdb.com/name/">
<Item Id="2" Img="#2" Name="Anna Karina" Href="nm0439344/">
<Description> She is a nice girl</Description>
<Facets>
<Facet Name="Nationality">
<LongString Value="Danish" />
</Facet>
</Facets>
</Item>
</Items>
<!-- Other entries-->
</Collection>
I can't get any functioning simple code like:
XDocument document = XDocument.Parse(e.Result);
foreach (XElement x in document.Descendants("Item"))
{
...
}
The test on a generic xml is working. The cxml file is correctly loaded in document.
While watching the expression:
document.Descendants("Item"), results
the answer is:
Empty "Enumeration yielded no results" string
Any hint on what can be the error? I've also add a quick look to get Descendants of Facet, Facets, etc., but there are no results in the enumeration. This obviously doesn't happen with a generic xml file I used for testing. It's a problem I have with .cxml.
Basically your XML defines a default namespace with the xmlns="http://schemas.microsoft.com/collection/metadata/2009" attribute:
That means you need to fully qualify your Descendants query e.g.:
XDocument document = XDocument.Parse(e.Result);
foreach (XElement x in document.Descendants("{http://schemas.microsoft.com/collection/metadata/2009}Item"))
{
...
}
If you remove the default namespace from the XML your code actually works as-is, but that is not the aim of the exercise.
See Metadata.CXML project under http://github.com/Zoomicon/Metadata.CXML sourcecode for LINQ-based parsing of CXML files.
Also see ClipFlair.Metadata project at http://github.com/Zoomicon/ClipFlair.Metadata for parsing one's CXML custom facets too
BTW, at http://ClipFlair.codeplex.com can checkout the ClipFlair.Gallery project for how to author ASP.net web-based forms to edit metadata fragments (parts of CXML files) and merge them together in a single one (that you then convert periodically to DeepZoom CXML with PAuthor tool from http://pauthor.codeplex.com).
If anyone is interested in doing nesting (hierarchy) of CXML collections see
http://github.com/Zoomicon/Trafilm.Metadata
and
http://github.com/Zoomicon/Trafilm.Gallery

Error parsing AppSettings value with a query string

In my AppSettings in web.config, I have something like this:
<appSettings>
<add key="ExternalSystemUrl" value="http://example.com/page.aspx?id={0}&action=eat&object=bacon" />
</appSettings>
However, it seems that when an ampersand (&) is included in an AppSettings value, ASP.NET throws the following error:
An error occurred while parsing EntityName
Why does this happen, and how can I include URLs like this in App.config?
Replace & with & (escape it):
<add
key="ExternalSystemUrl"
value="http://example.com/page.aspx?id={0}&action=eat&object=bacon" />
That's the common requirement for any valid XML file.
See Where can I get a list of the XML document escape characters?
You can Try using & instead.
In XML an ampersand tells the parser "the data immediately following this ampersand is an entity which needs to be translated." If the data immediately following is not a valid XML entity, then you get this error. If possible, use & for your ampersand within the XML.

How to update App.config using C#3.5 framework?

How to update in C#3.5 app.config file or Settings.settings file through C# code?
Please provide me the code related to C#3.5 framework support of classes but not with 2.0 framework classes in updating app.config file.
I messed with this issue on a project, and decided depending on circumstance to just use a simple XML config file of my own. The problem is app.config has application level and user level settings for a specific reason. The Code Project article mentioned by others here can get you there, but seems like a lot of work to me.
Easy way, create an XML file:
<?xml version="1.0" encoding="utf-8" ?>
<paths>
<path name="pathtofile1">
<fullpath>\\machine1\folder1\file.txt</fullpath>
</path>
<path name="pathtofile2">
<fullpath>\\machine2\folder2\file2.txt</fullpath>
</path>
</paths>
then use LINQ to get at a node:
XDocument doc = XDocument.Load(pathToXmlfile);
var filePath1 = from c in doc.Descendants("path")
where (string)c.Attribute("name") == "pathtofile1"
select (string)c.Element("fullpath").Value;
string thePath = filePath1.First();
Of course you don't have the built in typing, but this is an easy, generic approach you can use in a lot of situations such as in dll classes.
Now that you are using a 'regular' xml file, you can use the techniques mentioned here to update it. For example and this blog does a nice job.
Possible solution: Changing App.config at Runtime
Please check out this code:
You have to load the web.congif first:
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
Then you can modify or add it just like this:
if (config.AppSettings.Settings["YourTag"] == null)
{
config.AppSettings.Settings.Add("YourTag", "yourValue");
}
else
{
config.AppSettings.Settings["YourTag"].Value = "yourValue";
}
It's an XML file so you can use LINQ to XML to open the file
var appConfigPath = string.Format("{0}{1}.exe.config", Directory.GetCurrent(), Process.GetCurrentProcess().ProcessName);
var appConfig = XDocument.Parse(appConfigPath);
//have at it
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("..\\App.config");
XmlNode node = xmlDoc.SelectSingleNode("configuration/capabilities/single/add");// pass xpath of node
//node.Attributes[1].Value = MethodBase.GetCurrentMethod().Name;
node.Attributes[1].Value = TestContext.CurrentContext.Test.MethodName;
xmlDoc.Save("..\\App.config");
Please write in main methods, it is working for me.

Categories

Resources