dynamically add values to resources (C#) - c#

I want to add values to the resources dynamically through codings(C#). My below coding runs without any error but the values are not getting added to the resource file.
protected void Button2_Click(object sender, EventArgs e)
{
using (ResXResourceWriter resx = new ResXResourceWriter("Resources.resx"))
{
resx.AddResource( "joth", "joth");
resx.Close();
}
}

protected void Button2_Click(object sender, EventArgs e)
{
using (ResXResourceWriter resx = new ResXResourceWriter("Resources.resx"))
{ resx.AddResource( "joth", "joth");
resx.Save();
resx.Close();
}
}

I tried the above it doesn't seem to work, I looked around and try editing the resx file like a xml file and it worked for me.
<data name="v13" xml:space="preserve">
<value>Test TEst</value>
</data>
Above is the structure of a single key/value pair in the resx file opened in nodepadd ++
XDocument doc = XDocument.Load(Server.MapPath(#"~\App_GlobalResources\myResource2.resx"));
XElement data = new XElement("data");
XNamespace ns = "xml";
data.Add(new XAttribute("name", "v13"));
data.Add(new XAttribute(XNamespace.Xml + "space", "preserve"));
data.Add(new XElement("value", "Test TEst"));
doc.Element("root").Add(data);
doc.Save(Server.MapPath(#"~\App_GlobalResources\myResource2.resx"));

Related

Cant get Innertexts from webpage using html agility pack xpath in c#

So this is my code guys.
Im trying to get the text inside a span and storage it locally. Im using html agility pack and trying to retrieve the text using xpath but the nodes dont retrieve anything and appear as null.
This is the page im trying to get the text from: https://siat.sat.gob.mx/app/qr/faces/pages/mobile/validadorqr.jsf?D1=10&D2=1&D3=15030267855_SDS150309FC7
Specifically the "Denominación o razón social" text.
namespace ObtencionDatosSatBeta
{
public partial class Form1 : Form
{
DataTable table;
public Form1()
{
InitializeComponent();
}
private void InitTable()
{
table = new DataTable("tabladedatosTable");
table.Columns.Add("Variable", typeof(string));
table.Columns.Add("Contenido", typeof(string));
//table.Rows.Add("Super Mario 64", "84%");
tabladedatos.DataSource = table;
}
private async void Form1_Load(object sender, EventArgs e)
{
InitTable();
HtmlWeb web = new HtmlWeb();
var doc = await Task.Factory.StartNew(() => web.Load("https://siat.sat.gob.mx/app/qr/faces/pages/mobile/validadorqr.jsf?D1=10&D2=1&D3=15030267855_SDS150309FC7"));
var nodes = doc.DocumentNode.SelectNodes("//*[#id=\"ubicacionForm: j_idt12:0:j_idt13: j_idt17_data\"]//tr//td//span");
var innerTexts = nodes.Select(node => node.InnerText);
}
private void tabladedatos_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
Any idea?
var nodes = doc.DocumentNode.SelectNodes("//*[#id=\"ubicacionForm: j_idt12:0:j_idt13: j_idt17_data\"]//tr//td//span");
The line of code above is the one that appears as null.
Use this Xpath which gets the first span under the element with the following ID: ubicacionForm:j_idt10:0:j_idt11:j_idt14_data
(//*[#id='ubicacionForm:j_idt10:0:j_idt11:j_idt14_data']//span)[1]
You can select the element using multiple different ways by copying the HTML in chrome (Ctrl + Option + J)
And then paste the HTML in Xpather where you can play around with your Xpath. Xpather.com

Edit and save element to XML file using Linq

I'm trying to make a small XML editor. It loads an XML file, displays all book titles (in my example file) in a listbox. Clicking on a title displays all information about the book in a textbox. If the information should be modified, the user can click on an Edit button, and the information can now be edited in a new textbox. Finally, the changes are saved and both textboxes cleared - and, if possible, the titles from the newly updated XML file should be reloaded into the listbox (screenshot).
The listbox and first textbox operations work fine, thanks to this post.
The problem arises when I try to send the XML values to the second textbox. Either changes aren't saved or, if they are, the rest of the XML file disappears.
I suppose that a solution might consist in adding the information (and its changes) to a new XML element and then deleting the old one, but so far, and I've been trying for a while now, I simply can't figure out how to do it. It's for the same reason, and I know it's bad style, my code stops short where the problem begins. I'd be glad if someone could help me out.
My example XML:
<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<books>
<book genre="autobiography">
<title>The Autobiography of Benjamin Franklin</title>
<author>Franklin, Benjamin</author>
<year>1981</year>
<price>8.99</price>
</book>
<book genre="novel">
<title>The Confidence Man</title>
<author>Melville, Herman</author>
<year>1967</year>
<price>11.99</price>
</book>
<book genre="philosophy">
<title>The Gorgias</title>
<author>Plato</author>
<year>1991</year>
<price>9.99</price>
</book>
</books>
And my .cs
private void btnLoadXML_Click(object sender, EventArgs e)
{
var xmlDoc = XDocument.Load("books03.xml");
var elements = from ele in xmlDoc.Elements("books").Elements("book")
where ele != null
select ele;
bookList = elements.ToList();
foreach (var book in bookList)
{
string title = book.Element("title").Value;
listBox1.Items.Add(title);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var book = bookList[listBox1.SelectedIndex];
textBox1.Text =
"Title: " + book.Element("title").Value + Environment.NewLine +
"Author: " + book.Element("author").Value + Environment.NewLine +
"Year: " + book.Element("year").Value + Environment.NewLine +
"Price: " + book.Element("price").Value;
}
private void btnEdit_Click(object sender, EventArgs e)
{
textBox2.Visible = true;
btnSaveClose.Visible = true;
}
}
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string searchName = "The Autobiography of Benjamin Franklin";
XElement book = doc.Descendants("book").Where(x => (string)x.Element("title") == searchName).FirstOrDefault();
XElement price = book.Element("price");
price.SetValue("10.00");
}
}
}

C# XDocument - Adding a Value to an existing xml

This is what i am using
private void dir_TextBox_TextChanged(object sender, EventArgs e)
{
string _DIR = dir_TextBox.Text.ToString();dir
XDocument _config = XDocument.Load(#"/ProgramData\app\appConfig.xml");
_config.Root.Element("root").Element("node1").Add(new XElement("value", _DIR));
_config.Save(#"/ProgramData\app\appConfig.xml");
}
I have an xml
<root>
<node1>
<value></value>
</node1>
</root>
and want to add
<root>
<node1>
<value>a string</value>
</node1>
</root>
I have tried several ways to do this but keep getting an error "Additional information: Object reference not set to an instance of an object."
Any help would be appreciated.
Thanks.
_config.Root has already got the "root" element.
And you have to set (update) a new value ("a string") to the existing element, "value" because your xml file already has the "value" element.
private void dir_TextBox_TextChanged(object sender, EventArgs e)
{
XDocument _config = XDocument.Load(#"/ProgramData\app\appConfig.xml");
_config.Root.Element("node1").Element("value").Value = "a string";
_config.Save(#"/ProgramData\app\appConfig.xml");
}

Saving Xml to a Document C#

Unlike what I've been able to find on here I wand to maintain syntax within my xml document, and serialization doesn't touch on that. I want to be able to add another "task" tag to the xml document...Loading the information isn't a problem, I've had to deal with that before... but this is.
Main Program:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.IO;
namespace ToDoList
{
public partial class Form1 : Form
{
string title; //the variable for the title textbox value to be stored in
string details; //the variable for the details textbox value to be stored in
string itemstr; //the variable for title and details to be merged in
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
optionsbtn.Text = "Options"; //make the options button's text options
var items = ToDochkbox.Items; //create a private "var" items symbolizing the Checkbox's items array
XDocument xmlDoc = XDocument.Load("tasksdoc.xml"); //load the xml document (in bin or release)
var q = from c in xmlDoc.Descendants("root") //go "within" the <root> </root> tag in the file
select (string)c.Element("task"); //find the first <task></task> tag
foreach (string N in q) //now cycle through all the <task></task> tags and per cycle save them to string "N"
{
items.Add(N); //add the item to the checkbox list
}
}
public void addbtn_Click(object sender, EventArgs e)
{
var items = ToDochkbox.Items; //create a private "var" items symbolizing the Checkbox's items array
title = Addtb.Text; //set the title string to equal the title textbox's contents
details = detailstb.Text; //set the details string to equal the detail textbox's contents
itemstr = title +" - " + details; //set a variable to equal the title string, a - with spaces on each end, and then the details string
items.Add(itemstr); //add the variable itemstr (above) to the the checkbox list
}
private void optionsbtn_Click(object sender, EventArgs e)
{
new options().Show();//show the options form
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
new options().Show();//show the options form
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
}
public void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
optionsbtn.Text = "Options"; //make the options button's text options
var items = ToDochkbox.Items; //create a private "var" items symbolizing the Checkbox's items array
XDocument xmlDoc = XDocument.Load("tasksdoc.xml"); //load the xml document (in bin or release)
var q = from c in xmlDoc.Descendants("root") //go "within" the <root> </root> tag in the file
select (string)c.Element("task"); //find the first <task></task> tag
foreach (string N in q) //now cycle through all the <task></task> tags and per cycle save them to string "N"
{
items.Add(N); //add the item to the checkbox list
}
}
}
}
And My XML Document:
<root>
<task>First Task - Create a Task</task>
</root>
The class that you could use to serialize:
public class MyClass
{
[XmlElement("task")]
public List<string> Tasks { get; set; }
}
Placing the XmlElementAttribute on a collection type will cause each element to be serialized without being placed a node for the list.
Xml with XmlElementAttribute:
<root>
<task>First Task - Create a Task</task>
<task>SecondTask - Create a Task</task>
<task>ThirdTask - Create a Task</task>
</root>
Xml without XmlElementAttribute:
<root>
<Tasks>
<Task>First Task - Create a Task</Task>
<Task>SecondTask - Create a Task</Task>
<Task>ThirdTask - Create a Task</Task>
</Tasks>
</root>
I answered another question about serializing lists in a similar way a few days ago. Check out his question and then the answer, it might be what you are trying to do.

How to insert data into an existing xml file in asp.net?

I'm using Visual Web Developer 2008 Express Edition and I need your assistance since I'm new to it. I'm trying to insert or write a data to my xml file so that I can display it into my xml control. Now, what I'm trying to do here is everytime the user enter a message into the textbox he has an option to save it so if he clicks the command button I want to save the text message from the textbox into any elements of my xml file. Let say, I want to insert it in the element of my xml file. How do I do it using C# or VB.Net codes? I have my xml file below and my C# code but the c# code doesn't work for me. I need the code for that either in c# or vb.net, either way will work for me.
Thank you very much and I greatly appreciate any help that could be shared.
myxmlfile.xml
<?xml version="1.0" encoding="utf-8" ?>
<comments>
<comment>
Your Comments Here: Please post your comments now. Thank you.
</comment>
<comment2>
Note: Please do not post any profane languages.
</comment2>
<comment3>
I don't like their service. It's too lousy.
</comment3>
<comment4>
Always be alert on your duty. Don't be tardy enough to waste your time.
</comment4>
</comments>
code
protected void Button1_Click(object sender, EventArgs e)
{
System.Xml.Linq.XDocument mydoc =
new System.Xml.Linq.XDocument(
new System.Xml.Linq.XDeclaration("1.0", "UTF-8", "yes"),
new System.Xml.Linq.XElement("comment",
new System.Xml.Linq.XComment(TextBox1.Text)));
mydoc.Save("myxmlfile.xml",System.Xml.Linq.SaveOptions .None);
}
#Joseph LeBrech and #AVD --Thank you very much for your reply. That code would add a new root element in myxmlfile so the problem is that the new root element is not showing on my xml control when the page is reloaded because the new root element is not included on my xslt file to show the myxmlfile on the xml control. I don't want to add a new root element on myxmlfile. I just want to insert the messages entered from the textbox into the existing element of myxmlfile which is the element so that it can be shown on the xml control where i intend to display the myxmlfile. I hope you can modify the code for me again. Thank you very for your help. I greatly appreciated it.
You have to specify the absolute file path using MapPath() to save the XML document and don't increment tag name like comment1,comment2.. etc.
Take a look at code-snippet:
protected void Button1_Click(object sender, EventArgs e)
{
string file = MapPath("~/comments.xml");
XDocument doc;
//Verify whether a file is exists or not
if (!System.IO.File.Exists(file))
{
doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new System.Xml.Linq.XElement("comments"));
}
else
{
doc = XDocument.Load(file);
}
XElement ele = new XElement("comment",TextBox1.Text);
doc.Root.Add(ele);
doc.Save(file);
}
EDIT: If you want to insert <comment> tag into existing xml document then no need to create XDocument. Just load the existing document and add a new element at the root.
protected void Button1_Click(object sender, EventArgs e)
{
string file = MapPath("~/myxmlfile.xml");
XDocument doc = XDocument.Load(file);
XElement ele = new XElement("comment",TextBox1.Text);
doc.Root.Add(ele);
doc.Save(file);
}
To add another <comment> tag inside <comment>:
XElement ele = new XElement("comment",TextBox1.Text);
doc.Root.Element("comment").Add(ele);
doc.Save(file);
To replace the text value of <comment> tag:
doc.Root.Element("comment").Value = TextBox1.Text;
//doc.Root.Element("comment").Value += TextBox1.Text; //append text
doc.Save(file);
XML document :
<?xml version="1.0" encoding="utf-8" ?>
<comments> <!-- Root Node -->
<comment>First Child</comment>
<comment> <!-- Second Child -->
<comment>Nested</comment>
</comment>
</comments>
myDoc.Element("comments").Add(new xElement("comment5") { Value = "put the value in here"});
Design the page like this.In button click event write the following
code
protected void btnInsert_Click(object sender, EventArgs e)
{
System.Xml.XmlDocument myXml = new System.Xml.XmlDocument();
myXml.Load(Server.MapPath("InsertData.xml"));
System.Xml.XmlNode xmlNode = myXml.DocumentElement.FirstChild;
System.Xml.XmlElement xmlElement = myXml.CreateElement("entry");
xmlElement.SetAttribute("Name", Server.HtmlEncode(txtname.Text));
xmlElement.SetAttribute("Location", Server.HtmlEncode(txtlocation.Text));
xmlElement.SetAttribute("Email", Server.HtmlEncode(txtemail.Text));
xmlElement.SetAttribute("Gender", Server.HtmlEncode(ddlgender.SelectedItem.Text));
myXml.DocumentElement.InsertBefore(xmlElement,xmlNode);
myXml.Save(Server.MapPath("InsertData.xml"));
BindData();
lbldisplay.Text = "Record inserted into XML file successfully";
txtname.Text = "";
txtlocation.Text = "";
txtemail.Text = "";
}
private void BindData()
{
XmlTextReader xmlReader = new XmlTextReader(Server.MapPath("InsertData.xml"));
xmlReader.Close();
}
and also put events tag in xml file.
Now run the application and check the output

Categories

Resources