How to read and update value in xml file via C sharp? - c#

I have the xml file is following manner :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Conn" providerName="System.Data.SqlClient"
connectionString="Data Source=machine_name; Initial Catalog=database_name; User ID=id; Password=password" />
</connectionStrings>
</configuration>
In above xml file i want to change the value of password.
Code i have tried is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using System.Xml.Linq;
namespace ConsoleApplication85
{
class Program
{
static void Main(string[] args)
{
XDocument xdoc = XDocument.Load(#"filepath.xml");
var element = xdoc.Elements("Password").Single();
element.Value = "new password";
xdoc.Save(#"filepath.xml");
}
}
}

The best way to change the application configuration is through the methods of the ConfigurationManager class, not through XmlDocument methods..
See this question:
Change connection string & reload app.config at run time

Related

How do I get SOAP xml file data using LINQ and display it in a form's text box? C#

How do I do it?
This is the SOAP XML file
<soapenv:Envelope xmlns:soapenv="http://www.w3.org/2001/12/soap-envelope" soapenv:encodingStyle="http://www.w3.org/2001/12/soap-encoding" >
<soapenv:Body xmlns:lle="http://www.aab.org/logevents" >
<lle:Events>
<lle:eventid>ID1</lle:eventid>
<lle:tweet>
<lle:text>This is some tweet in my day</lle:text>
<lle:location>
<lle:lat>66</lle:lat>
<lle:long>77</lle:long>
</lle:location>
<lle:datetimestamp>datetimestamp</lle:datetimestamp>
</lle:tweet>
</lle:Events>
</soapenv:Body>
</soapenv:Envelope>
And this is my C# code, it doesn't display anything in the text box, I have tried adding the "lle:" in front of "Event" and its Descendants like:
.Descendants("lle:Events")
select events.Element("lle:eventid").Value;
but apparently it doesn't work, and there's lots of errors, so I changed it back
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace Xmltest
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
XDocument xmlDocument = new XDocument();
IEnumerable<string> id = from events in XDocument.Load(#"C:\Users\Jack\source\repos\xmltest\Xmltest\XmlFile.xml")
.Descendants("Events")
select events.Element("eventid").Value;
this.txtBox1.Text = id.FirstOrDefault();
}
}
}
but it worked perfectly fine with normal xml file below
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Customers>
<Customer ID="101">
<Name>Robert</Name>
<Mobile>9820098200</Mobile>
<Location>Bangladesh</Location>
<Address>XYZ</Address>
</Customer>
<Customer ID="102">
<Name>Kate</Name>
<Mobile>983452342</Mobile>
<Location>Japan</Location>
<Address>ABC</Address>
</Customer>
<Customer ID="103">
<Name>Catherine</Name>
<Mobile>123456785</Mobile>
<Location> London</Location>
<Address>CDE</Address>
</Customer>
<Customer ID="10004">
<Name>Richard</Name>
<Mobile>899990012</Mobile>
<Location>France</Location>
<Address>MNO</Address>
</Customer>
</Customers>
I believe that's because you are using strings to refer to element. You should use XName, e.g. instead of "Events" or "eventid" use:
var events = XName.Get("Events", "http://www.aab.org/logevents");
var eventId = XName.Get("eventid", "http://www.aab.org/logevents");
You can use below powershell snippet for a quick test:
$x = [System.Xml.Linq.XDocument]::Load("C:\Users\Jack\source\repos\xmltest\Xmltest\XmlFile.xml")
$evtName = [System.Xml.Linq.XName]::Get("Events", "http://www.aab.org/logevents")
$idName = [System.Xml.Linq.XName]::Get("eventid", "http://www.aab.org/logevents")
$x.Descendants($evtName).Element($idName).Value | Write-Host
You have to handle the Xml Namespace. You can do this by querying with XName, instead of with a string:
using System;
using System.Linq;
using System.Xml.Linq;
public class Program
{
public static void Main()
{
var inXml = #"<soapenv:Envelope xmlns:soapenv=""http://www.w3.org/2001/12/soap-envelope"" soapenv:encodingStyle=""http://www.w3.org/2001/12/soap-encoding"" >
<soapenv:Body xmlns:lle=""http://www.aab.org/logevents"" >
<lle:Events>
<lle:eventid>ID1</lle:eventid>
<lle:tweet>
<lle:text>This is some tweet in my day</lle:text>
<lle:location>
<lle:lat>66</lle:lat>
<lle:long>77</lle:long>
</lle:location>
<lle:datetimestamp>datetimestamp</lle:datetimestamp>
</lle:tweet>
</lle:Events>
</soapenv:Body>
</soapenv:Envelope>";
var eventIdsXName = XName.Get("eventid", "http://www.aab.org/logevents");
var eventIds = XDocument.Parse(inXml)
.Descendants(eventIdsXName)
.Select(i => i.Value);
foreach(var eventId in eventIds){
Console.WriteLine($"Value: {eventId}");
}
}
}
Output:
Value: ID1
See:
https://dotnetfiddle.net/IEdwz1

How to fetch specific data from XML using C#

I'm trying to fetch specific data from a Xml file to display in a textbox. My Xml file name as "test.xml" has following code
<?xml version="1.0" encoding="utf-8" ?>
<Body>
<Context>
<PageNo>a87</PageNo>
<Verse>"Do it right"</Verse>
</Context>
</Body>
My C# code is below: Edited to reflect recent chnages
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace learn2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pageid1();
}
private void pageid1()
{
textBox1.Clear();
XmlDocument doc = new XmlDocument();
doc.Load("C:\\test.xml");
var pagenoNodeList = doc.SelectNodes("Body/Context/PageNo");
var pageNoNode = pagenoNodeList[0]; // To select the first node
var text = pageNoNode.InnerText; // Gets the text value inside the node
textBox1.Text = text;
} }
}
I highly appreciate any help. Thanks
You need to identify the node you are looking for, as SelectNodes returns a System.Xml.XmlNodeList, and then get the value of InnerText:
var pagenoNodeList = doc.SelectNodes("Body/Context/PageNo");
var pageNoNode = pagenoNodeList[0]; // To select the first node
var text = pageNoNode.InnerText; // Gets the text value inside the node
textBox1.Text = text;

Custom config file elements in ASP.NET: `Property is not a ConfigurationElement'

I'm attempting to implement my first go-around of reading custom configuration elements from an ASP.NET web.config file. It seems pretty simple to me, yet I'm receiving a run-time `Property is not a ConfigurationElement' error. Here's my code:
The web.config file sections:
<?xml version="1.0" encoding="utf-8" ?>...
<configuration>
...
<section name="appConfig" type="ParticipationManagement.AppConfig" allowDefinition="Everywhere" allowLocation="true" requirePermission="false" />
</configSections>
...
<appConfig>
<startRecertVFC>2/15</startRecertVFC>
</appConfig>
</configuration>
The handler:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
namespace ParticipationManagement
{
public class AppConfig : ConfigurationSection
{
[ConfigurationProperty("startRecertVFC", IsRequired = false)]
public DateTime RecertVFCStart
{
get
{
string start = (string)this["startRecertVFC"];
string year = DateTime.Now.Year.ToString();
DateTime start_date;
if (DateTime.TryParse(start + "/" + year, out start_date))
{
return start_date;
}
else
{
return DateTime.Today;
}
}
set
{
this["startRecertVFC"] = value;
}
}
}
}
And my invocation in page code:
protected void Page_Init(object sender, EventArgs e)
{
...
AppConfig config = (AppConfig)System.Configuration.ConfigurationManager.GetSection("appConfig");
RecertVFCStart = config.RecertVFCStart;
}
Seems very clean and straight-forward to me, but I'm getting that troubling error at runtime and I cannot narrow it down since I have no experience with this.
Sorry in advance: I see plenty of other posts about this but all seem to address more advanced/complex issues than what I'm trying to accomplish, which is nothing more than embedding a few app-specific values in an external file...
Change your config setting like an example shown below
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="appConfig" type="ParticipationManagement.AppConfig" allowDefinition="Everywhere" allowLocation="true" requirePermission="false"/>
</configSections>
<appConfig startRecertVFC="5/1/2015 8:30:52 AM" />
</configuration>
Try to make the following change in AppConfig file
string start = this["startRecertVFC"].ToString();
Let us know if this solves your problem

Handling File Naming Convention from Configuration File

I have attempting to implement a file naming convention in my program. For example I have a configuration file such as below:
MyConfig.conf
# File naming convention for output-file
[Field1][Field3][Field2]
'FieldX' corresponds with string within the program - so for example a program would read the configuration file and format the strings as follows in the program:
Field1Value Field2Value Field3Value
Are there any preferred ways to do this kind of thing in C#?
Easiest way I can think of is to use app settings. The app settings contain the string format that you need. Then you just use that string format.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _16852548
{
class Program
{
static void Main(string[] args)
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string field1Value = "Filename";
string field2Value = ".";
string field3Value = "txt";
string fileFormat = appSettings["FileNameFormat"];
Console.WriteLine(string.Format(fileFormat, field1Value, field2Value, field3Value));
}
}
}
Then the config file can be:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="FileNameFormat" value="{0}{2}{1}"/> <!-- follow string.Format syntax -->
</appSettings>
</configuration>

System.Web.Mvc.HtmlHelper' does not contain a definition for CheckBox

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
namespace secondMvc.MyControls
{
public static class CheckBoxList
{
public static MvcHtmlString CheckListBox(this HtmlHelper helper, string Name, Dictionary<Int32, string> citiesList, bool IsVertical, string cssClass)
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("<div >"));
foreach (var item in citiesList)
{
sb.Append(helper.CheckBox(item.Value, true, new { #class = cssClass, value = item.Key }));
sb.Append(helper.Label("RadioButtonItems", item.Value));
sb.Append(" ");
if (IsVertical) sb.Append("<br>");
}
sb.Append("</div> ");
return MvcHtmlString.Create(sb.ToString());
}
}
}
System.Web.Mvc.HtmlHelper'does not contain a definition forCheckBoxand no extension method'CheckBox'accepting a first argument of type'System.Web.Mvc.HtmlHelper'` could be found (are you missing a using directive or an assembly reference?)
i change web.config like this:
<configuration>
<appSettings>
</appSettings>
<connectionStrings>
</connectionStrings>
<pages>
<namespaces>
<add namespace="secondMvc.MyControls"/>
</namespaces>
</pages>
<system.web>
<compilation>
<assemblies>
<add assembly="secondMvc.MyControls" />
</assemblies>
</compilation>
</system.web>
</configuration>
but i have same error.
any idea?
Add using System.Web.Mvc.Html to your file containing the CheckBoxList static class. It is inside this namespace that extension method such as CheckBox are defined. The web.config namespaces section is completely ignored when compiling C# code. They are used by views. And note that Razor views use the ~/Views/web.config file, not ~/web.config, so make sure you have added the secondMvc.MyControls namespace to the correct web.config if you want your custom extension method to be resolved in views.

Categories