Trying to use a remotely hosted XML file for settings - c#

Apologies for the newbie question, I'm only on day 2 of my adventures with C#...
I'm trying to use a remotely hosted XML file to retrieve some basic settings for my program. I've managed to get it to download and parse the XML file into string variables, but I cannot work out how to make these variables available to the rest of my program.
Here is the code:
public static void getSetting()
{
try
{
XmlDocument xml = new XmlDocument();
xml.Load("http://www.domain.com/s/settings.xml");
XmlNodeList xnList = xml.SelectNodes("/Settings/Setting");
string strEnabled = ""; string strPort = "";
string strPac = ""; string strRules = ""; string strUpdateUrl = "";
foreach (XmlNode xn in xnList)
{
strEnabled = xn["Enabled"].InnerText;
strPort = xn["Port"].InnerText;
strPac = xn["Pac"].InnerText;
strRules = xn["Rules"].InnerText;
strUpdateUrl = xn["UpdateUrl"].InnerText;
}
}
catch (Exception e)
{
Console.WriteLine("Unable to download settings: " + e);
}
}
public static void useSettings()
{
//use the settings in here
}
I'd also appreciate any critique on my code as I'm still getting to grips with everything and realise that I'm probably not going about this the best way.

Related

Update XML with C# running from command line

Working with: visual studio and C#
I have function to update XML file, while running from the VS it's works and the XML is updated.
While running this function out from the VS for example command line or Jenkins the XML file doesn't update.
My code:
string XMLPath = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory())));
public void UpdateXML(string tag, string value)
{
XmlDocument doc = new XmlDocument();
string XMLFile = "";
try{
XMLFile = XMLPath + "\\Test.xml";
doc.Load(XMLFile);
XmlNode node = doc.SelectSingleNode(tag);
node.InnerText = value;
doc.Save(XMLFile);
}
catch (Exception e){}
}
public void Set_ConfigurationXML()
{
UpdateXML("Platform", "web");
}
Any suggestions?

Can't load XML from Resource/Drawable/

I've saved my Xml in Resource/Drawable/ . I put it here cause is the only place where it can stay without any error.
Any way this is the exception:
System.IO.FileNotFoundException: Could not find file "/sds".
How can I find the path?
Here is my code:
String conditionName = "";
XDocument xml = XDocument.Load("#drawable/LightConditions.xml");
foreach (XElement item in xml.Root.Elements("Condizione"))
{
if (item.Element("EV").Value == EV)
{
conditionName = item.Parent.Element("Nome").Value;
break;
}
//do something
}
You will want to place that .xml in the Assets folder and flag the build action as an AndroidAsset.
Then you can use the AssetManager to access it via a Stream:
string conditionName = "";
using (StreamReader sr = new StreamReader(this.Assets.Open("LightConditions.xml")))
{
XDocument xml = XDocument.Load(sr);
foreach (XElement item in xml.Root.Elements("Condizione"))
{
if (condizione.Element("EV").Value == EV)
{
conditionName = item.Parent.Element("Nome").Value;
break;
}
//do something
}
}
Consult the Xamarin.Android guide on Assets

C# crashes on save (doc.Save(PATH);)

This program crashes on debug and highlights the "doc.Save(PATH);" at the end of the code.
I am trying to save the variables cookieScore, additionAddition, and additionMultiplier into an XML file.
I am getting information about it from here "http://visualcsharptutorials.com/net-framework/writing-xml-file"
private XmlDocument doc;
string PATH = #"C:\sample.xml";
private void saveBtn_Click(object sender, EventArgs e)
{
doc = new XmlDocument();
if (!System.IO.File.Exists(PATH))
{
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
XmlComment comment = doc.CreateComment("This is saved game data");
XmlElement root = doc.CreateElement("data");
XmlElement data = doc.CreateElement("data");
XmlAttribute addition = doc.CreateAttribute("addition");
XmlElement additionNumber = doc.CreateElement("additionNumber");
XmlElement multiplicationNumber = doc.CreateElement("multiplicationNumber");
XmlElement cookieSave = doc.CreateElement("cookieSave");
addition.Value = "addition";
additionNumber.InnerText = additionAddition.ToString();
multiplicationNumber.InnerText = additionMultiplier.ToString();
cookieSave.InnerText = cookieScore.ToString();
doc.AppendChild(declaration);
doc.AppendChild(comment);
doc.AppendChild(root);
root.AppendChild(data);
data.Attributes.Append(addition);
data.AppendChild(cookieSave);
data.AppendChild(additionNumber);
data.AppendChild(multiplicationNumber);
doc.Save(PATH);
}
else
{
}
My guess is you're getting an access related exception because you're trying to write to the root of your C drive. Try writing to your desktop instead:
string PATH = #"C:\Users\[yourusername]\Desktop\sample.xml";
Another option would be to try to run your EXE as admin. If it works, then you know that's your problem.

Web scraper using HtmlAgilityPack

I am new to C# so this might be very obvious how to get this to work or way too complex for me but I am trying to setup and scrape a web page using the HtmlAgilityPack. Currently my code compiles but when I write the string I only get 1 result and it happens to be the last result from the li in the ul. The reason for the string split is so I can eventually output the title and description strings into a .csv for further use. I am just unsure what to do next thus, why I am asking for any help/understanding/ideas/thoughts/suggestions that can be offered. Thank you!
private void button1_Click(object sender, EventArgs e)
{
List<string> cities = new List<string>();
//var xpath = "//h2[span/#id='Cities']";
var xpath = "//h2[span/#id='Cities']" + "/following-sibling::ul[1]" + "/li";
WebClient web = new WebClient();
String html = web.DownloadString("http://wikitravel.org/en/Vietnam");
hap.HtmlDocument doc = new hap.HtmlDocument();
doc.LoadHtml(html);
foreach (hap.HtmlNode node in doc.DocumentNode.SelectNodes(xpath))
{
string all = node.InnerText;
//splits text between '—', '-' or ' ' into 2 parts
string[] split = all.Split(new char[] { '—', ' ', '-' }, StringSplitOptions.None);
string title;
string description;
int nodeCount;
nodeCount = node.ChildNodes.Count;
if (nodeCount == 2)
{
title = node.ChildNodes[0].InnerText;
description = node.ChildNodes[1].InnerText;
}
else if (nodeCount == 4)
{
title = node.ChildNodes[0].InnerText;
description = node.ChildNodes[1].InnerText + node.ChildNodes[2].InnerText;
}
else
{
title = "Error";
description = "The node cound was not 2 or 3. Check the div section.";
}
System.IO.StreamWriter write = new System.IO.StreamWriter(#"C:\Users\cbrannin\Desktop\textTest\testText.txt");
write.WriteLine(all);
write.Close();
}
}
}
One problem is that you're overwriting the output file each time through the loop. You probably want to do this:
using (StreamWriter write = new StreamWriter(#"filename"))
{
foreach (hap.HtmlNode node in doc.DocumentNode.SelectNodes(xpath))
{
// do your thing
write.WriteLine(all);
}
}
Also, have you single-stepped this to see if you're getting more than one HtmlNode from your SelectNode call?
Finally, I don't see where you're doing anything with the title or description. Were you planning to use those for something else?

System.IO exception coming while saving XML document in C#

After importing plenty of XML files into application i tried to do modifications on it by using XML document class, for this i created few methods to do modifications.
The thing is the starting method it's working fine and when comes to the second one it's displaying System.IO exception like "File is already using another process".
So any one help me out how can i solve this issue.
Sample code what i'm doing:
Method1(fileList);
Method2(fileList);
Method3(fileList);
private void Method1(IList<RenamedImportedFileInfo> fileList)
{
try
{
string isDefaultAttribute = Resource.Resources.ImportIsDefaultAttribute;
string editorsPath = editorsFolderName + Path.DirectorySeparatorChar + meterType;
string profilesPath = profileFolderName + Path.DirectorySeparatorChar + meterType;
string strUriAttribute = Resource.Resources.ImportUriAttribute;
foreach (RenamedImportedFileInfo renameInfo in fileList)
{
if (renameInfo.NewFilePath.ToString().Contains(editorsPath) && (renameInfo.IsProfileRenamed != true))
{
var xmldoc = new XmlDocument();
xmldoc.Load(renameInfo.NewFilePath);
if (xmldoc.DocumentElement.HasAttribute(isDefaultAttribute))
{
xmldoc.DocumentElement.Attributes[isDefaultAttribute].Value = Resource.Resources.ImportFalse;
}
XmlNodeList profileNodes = xmldoc.DocumentElement.GetElementsByTagName(Resource.Resources.ImportMeasurementProfileElement);
if (profileNodes.Count == 0)
{
profileNodes = xmldoc.DocumentElement.GetElementsByTagName(Resource.Resources.ImportBsMeasurementProfileElement);
}
if (profileNodes.Count > 0)
{
foreach (RenamedImportedFileInfo profileName in oRenamedImportedFileList)
{
if (profileName.NewFilePath.ToString().Contains(profilesPath))
{
if (string.Compare(Path.GetFileName(profileName.OldFilePath), Convert.ToString(profileNodes[0].Attributes[strUriAttribute].Value, CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) == 0)
{
profileNodes[0].Attributes[strUriAttribute].Value = Path.GetFileName(profileName.NewFilePath);
renameInfo.IsProfileRenamed = true;
break;
}
}
}
}
xmldoc.Save(renameInfo.NewFilePath);
xmldoc = null;
profileNodes = null;
}
}
oRenamedImportedFileList = null;
}
catch (NullReferenceException nullException) { LastErrorMessage = nullException.Message; }
}
Thanks,
Raj
You are probably opening the same file twice in your application. Before you can open it again, you have to close it (or leave it open and work on the same document without opening it again).
For help on how to implement this, please show us more code so we can give you advice.

Categories