Error parsing AppSettings value with a query string - c#

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.

Related

Match string that contain unknown text

I have a web service that I'm calling that returns a list of error messages. I'm then doing a foreach over this list, and matching based on the text of the error messages in a config file. However, some of the error messages returned from the web service contains some unknown data, such as a date, or a number.
How can I match this text, using C#? Would I have to split the string and try to match each individual word? How do I deal with an unknown variable such as a date or number when doing a ".Contains(...)"?
Here's an example:
Web service list might contain the following
"This is an example static error message"
"Another example static error message"
"This is an error message for employee 2"
"This is an error message dated 11/2/2017"
"Employee 3 does not work here anymore"
In my config file, I have the following:
<add errorText="This is an example static error message" field="N/A" />
<add errorText="Another example static error message" field="N/A" />
<add errorText="This is another example for employee **X**" field="N/A" />
<add errorText="This is an error message dated **X**" field="N/A" />
<add errorText="Employee **X** does not work here anymore" field="N/A" />
From your config files, you could build regular expressions as follows:
String configString = GetConfigString(3); // "This is another example for employee **X**"
String regexPattern = String.Concat("^", configString.Replace("**X**", ".+"), "$");
Boolean match = Regex.IsMatch("This is another example for employee John", regexPattern);
and then use such regex to match your text strings.
You could also build all of your regular expression patterns as soon as your application starts and cache them somewhere for future use:
String configStrings = GetConfigStrings();
String[] regexPatterns = new String[configStrings.Length];
for (Int32 i = 0; i < configStrings.Length; ++i)
regexPatterns[i] = String.Concat("^", configStrings[i].Replace("**X**", ".+"), "$");
Since you have a mixed type of possible string replacement within your framework, sticking to the .+ token is the better choice.
If course, it's up to you to eventually build a configuration file parsers and implement GetConfigString and GetConfigStrings methods (or only one, depending on the approach you want to use).
You can use Regex to match them:
Regex.IsMatch(message, "This is another example for employee .+")
Regex.IsMatch(message, "This is an error message dated .+")
If you don't like to take regex approach, like me, you can add the known error messages into a HashSet and keep them in memory and then lookup which error message matches the most with the error message on hand, like a match score.

Reading specific section of App.config

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;

API WiktionaryNET

I am trying to use the Wiktionary's API trying to know if some words are defined or not.
I have seen the open source's WiktionaryNET and they use this code:
In my console code:
var word = Wiktionary.Define("clean");
foreach (var def in word.Definition)
Console.WriteLine(def);
In the app.config:
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
I use the same things but the result is always "Definition.Count = 0"
Someone know, how can I use or set up to get results?
Thanks in advance for your help.
I'm the implementer of this library. Thanks for pointing this out. I'll try to explain what happened and what can you do if you really need this fixed right now.
The wiktionary response is in JSON format but it's terrible to parse. It's actually one single blub of text. What happened is that the JSON response from wiktionary was modified since the wiktionaryNET was implemented. It now contains an additional field. The wiktionaryNET parser mistakenly interprets this as the content it was supposed to parse in the first place. The result is an empty response from the library.
You can download the project from GitHub. Then go to WiktionaryJsonQuery.cs and modify the AddQuery statements to include the rawcontinue:
AddQuery("format=json");
AddQuery("rawcontinue"); // <-- add this line
AddQuery("action=query");
AddQuery("prop=revisions");
AddQuery("rvprop=content");
AddQuery("titles=" + word);
Build the project and add the resulting dll to your project.
Please note this is only in beta.

How to write an URI string in App.Config

I am making a Windows Service. The Service has to donwload something every night, and therefor I want to place the URI in the App.Config in case I later need to change it.
I want to write an URI in my App.Config. What makes it invalid and how should i approach this?
<appSettings>
<add key="fooUriString"
value="https://foo.bar.baz/download/DownloadStream?id=5486cfb8c50c9f9a2c1bc43daf7ddeed&login=null&password=null"/>
</appSettings>
My errors:
- Entity 'login' not defined
- Expecting ';'
- Entity 'password' not defined
- Application Configuration file "App.config" is invalid. An error occurred
You haven't properly encoded the ampersands in your URI. Remember that app.config is an XML file, so you must conform to XML's requirements for escaping (e.g. & should be &, < should be < and > should be >).
In your case, it should look like this:
<appSettings>
<add
key="fooUriString"
value="https://foo.bar.baz/download/DownloadStream?id=5486cfb8c50c9f9a2c1bc43daf7ddeed&login=null&password=null"
/>
</appSettings>
But in general, if you wanted to store a string that looked like "I <3 angle bra<kets & ampersands >>>" then do this:
<appSettings>
<add
key="someString"
value="I <3 angle bra<kets & ampersands >>>"
/>
</appSettings>
void StringEncodingTest() {
String expected = "I <3 angle bra<kets & ampersands >>>";
String actual = ConfigurationManager.AppSettings["someString"];
Debug.Assert.AreEqual( expected, actual );
}
& should work just fine, Wikipedia has a List of predefined entities in XML.
Try using: & in place of & in the url

Web.Config encoding problems

Wanted to let you know that I've tried to solve my problem before turning to the community for help.
I need to send a request with a couple of query parameters to a web service from which I should get an XML in the response which I need to parse and populate image source and image link with the values.
let's assume the the url for the website is:
domain.com/user=1&passwd=2&param=u
When i type this in a browser I could see the XML i should get as a response.
I place the value in appSettings in a web.Config file like so:
<appSettings>
<add key="GetImageUrl" value="http://domain.com/user=1&passwd=2&param=u"/>
</appSettings>
However, this would not compile because the compiler cannot understand '&' so I used the encoded version like this:
<appSettings>
<add key="GetImageUrl" value="http://domain.com/user=1&passwd=2&param=u"/>
</appSettings>
However, when I type this I see the XML with "Error" values which is one of the expected values to be returned if wrong parameters are sent.
How should I proceed?
Thank you very much!
Edit:
Wanted to let you know that I've also tried "&;amp;" and "%26"
The web.config file is an XML file, so you must encode & as &.
When reading the value in your program, you will get a &.
I don't know wha tyou mean by:
when I type this I see the XML with "Error" values which is one of the expected values to be returned if wrong parameters are sent
Where is this happening? Sending where?

Categories

Resources