Adding double quotes to # string - c#

As far as i understood, a string with an # in required a set of double quotes to insert the quote in to the string?
I have tried that principle and to no avail. The following line works, but if i were to replace those strings with parameter values then i cant seem to get the correct compilation value
var node = doc.SelectSingleNode(#"//node[#label = ""Chemist Name""]/node[#label = ""John,Smith""]");
my attempt (of which i have tried several versions and ended up here, where i have now givn up !)
var node = doc.SelectSingleNode(#"//node[#label = " + ""+parentID+"" + "]/node[#label = " + ""+ name +"" + "]");
can anyone help me please?

Use single quotes:
var node = doc.SelectSingleNode
(#"//node[#label = 'Chemist Name']/node[#label = 'John,Smith']");
var node = doc.SelectSingleNode(
string.format(#"//node[#label = '{0}']/node[#label = '{1}']"
, parentID, name));

You are missing another double quote to close the string being appended and also # before each string containing "".
Try this:
var node =
doc.SelectSingleNode(#"//node[#label = """ + parentID + #"""]/node[#label = """ + name + #"""]");

var node = doc.SelectSingleNode(string.format(#"//node[#label = ""{0}""]/node[#label = ""{1}""]", parentId, name));

Write an extension method to extend string:
public static string Quote(this string input)
{
return string.Format(#"""{0}""", input);
}
And then use it as follows:
var node = doc.SelectSingleNode(#"//node[#label = " + parentID.Quote() + "]/node[#label = " + name.Quote() + "]");
Or simply:
var node = doc.SelectSingleNode(string.Format(#"//node[#label = {0}"]/node[#label = {1}"]",parentID.Quote(), name.Quote());

Related

C# extract data from csv

I have a CSV file like this:
field1,field2,field3,field4,...,fieldN
1,2,3,,...,N
and I want to extract exactly the 14th record of the second row.
I've tried this code:
string nomeFile = "externalSourceMsg " + this.DataSource.CodSorgEst + this.DataSource.CodIdSorgEst + ".csv";
string content = "Field1,Field2,Field3,Field4,Field5,Field6,Field7" + Environment.NewLine;
content += externalMessage.ToString();
content = content.Replace(',', ';');
int i = 0;
while (content){
int field;
if(i++ == 13)
field = content+i;
}
but it doesn't work. What did I do wrong?
Split the string and you can access fields by indexes.
string nomeFile = "externalSourceMsg " + this.DataSource.CodSorgEst + this.DataSource.CodIdSorgEst + ".csv";
string content = "Field1,Field2,Field3,Field4,Field5,Field6,Field7" + Environment.NewLine;
content += externalMessage.ToString();
content = content.Replace(',', ';');
// Split the string by your separator -> you will get an array filled with fields
string[] contentArr = content.Split(';');
// Access any field you'd like by indexes
var The14thField = contentArr[13];
Try:
// Read all lines and get the second (this can be done
// in more optimal way, just by reading two first lines)
var secondLine = File.ReadLines("Path")[1];
// Split byb comma and get 14th item in returned array
var entry = secondLine.Split(",")[13];

C# - Get All Words Between Chars

I have string:
string mystring = "hello(hi,mo,wo,ka)";
And i need to get all arguments in brackets.
Like:
hi*mo*wo*ka
I tried that:
string res = "";
string mystring = "hello(hi,mo,wo,ka)";
mystring.Replace("hello", "");
string[] tokens = mystring.Split(',');
string[] tokenz = mystring.Split(')');
foreach (string s in tokens)
{
res += "*" + " " + s +" ";
}
foreach (string z in tokenz)
{
res += "*" + " " + z + " ";
}
return res;
But that returns all words before ",".
(I need to return between
"(" and ","
"," and ","
"," and ")"
)
You can try to use \\(([^)]+)\\) regex get the word contain in brackets,then use Replace function to let , to *
string res = "hello(hi,mo,wo,ka)";
var regex = Regex.Match(res, "\\(([^)]+)\\)");
var result = regex.Groups[1].Value.Replace(',','*');
c# online
Result
hi*mo*wo*ka
This way :
Regex rgx = new Regex(#"\((.*)\)");
var result = rgx.Match("hello(hi,mo,wo,ka)");
Split method has an override that lets you define multiple delimiter chars:
string mystring = "hello(hi,mo,wo,ka)";
var tokens = mystring.Replace("hello", "").Split(new[] { "(",",",")" }, StringSplitOptions.RemoveEmptyEntries);

c# Windows Form, replace string in textbox (file content) with another string

I have a textbox that contains all of the lines of a loaded file.
It looks like this:
I am able to load a specific line of the file that contains a specific string using this in the app:
How would I be able to update the file/main textbox after I press the "Edit Module" button, if any of the textboxes would be changed .
For example, I would change Exam Weighting: "0.4" to Exam Weighting: "0.6", then press the "Edit Module" button which would edit the main textbox(file content). Which then would allow me to save the file with the updated content.
This is the code I am using to get a specific line from the file based on string from a textbox:
private void editModuleButton_Click(object sender, EventArgs e)
{
citation = editModuleComboBox.Text;
citationChange();
}
private void citationChange()
{
List<string> matchedList = new List<string>();
string[] linesArr = File.ReadAllLines(fileName);
//find matches
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
//output
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
}
If somebody with enough rep could insert the images to this post, that would be great. Thanks
This solution might not be the perfect, but should work for you. What you need to do is whenever the Edit Module button is pressed, create a new string based on the text fields and replace it with the original line. First declare a string variable private string ChangedString = ""; inside the class, then:
foreach (string s in matchedList)
{
string citationLine = s;
string[] lineData = citationLine.Split(',');
string Stream = lineData[0]; //Store this somewhere so that it can be accessed later
string Stage = lineData[1]; //Store this somewhere so that it can be accessed later
selectedModuleLabel.Text = lineData[2];
moduleTitleTextBox.Text = lineData[3];
creditsTextBox.Text = lineData[4];
semesterTextBox.Text = lineData[5];
examWeightingTextBox.Text = lineData[6];
examMarkTextBox.Text = lineData[7];
testWeightingTextBox.Text = lineData[8];
testMarkTextBox.Text = lineData[9];
courseworkWeightingTextBox.Text = lineData[10];
courseworkMarkTexbox.Text = lineData[11];
}
store Stream and Stage in any Textbox/ComboBox if you already haven't then replace them accordingly in the following line. Now in EditButton_Click [Click Event] write:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
Now replace this string with the original line.
Edit: As you would get the line number which is being edited, store it in a variable, let's say
int LineBeingEdited = 3 //Supposing line number three is being edited.
Then again in the same Click event you can write this:
ChangedString = Stream + "," + Stage + "," + selectedModuleLabel.Text + "," + moduleTitleTextBox.Text
+ "," + creditsTextBox.Text + "," + semesterTextBox.Text + "," + examWeightingTextBox.Text + ","
+ examMarkTextBox.Text + "," + courseworkWeightingTextBox.Text + "," + courseworkMarkTexbox.Text;
var lines = TextBox1.Lines;
lines[LineBeingEdited] = ChangedString;
TextBox1.Lines = lines;
EDIT 2: To get the line number I would suggest you to modify your for each loop to for loop. Also add a int variable to store the line number inside the class like : private int LineBeingEdited = 0;
Modify this for each :
foreach (string s in linesArr)
{
if (s.Contains(citation))
{
matchedList.Add(s); //matched
}
}
To for loop:
for (int a = 0; a < linesArr.Length; a++)
{
if (s.Contains(citation))
{
matchedList.Add(linesArr[a]); //matched
LineBeingEdited = a;
break; //breaks the loop when a match is found
}
}
The above method is being used, taking into consideration that there will always be a single match. LineBeingEdited will now have the line number and can be accessed from anywhere in the class

Extract text from <1></1> (HTML/XML-Like but with Number Tag)

So I have a long string containing pointy brackets that I wish to extract text parts from.
string exampleString = "<1>text1</1><27>text27</27><3>text3</3>";
I want to be able to get this
1 = "text1"
27 = "text27"
3 = "text3"
How would I obtain this easily? I haven't been able to come up with a non-hacky way to do it.
Thanks.
Using basic XmlReader and some other tricks to do wrapper to create XML-like data, I would do something like this
string xmlString = "<1>text1</1><27>text27</27><3>text3</3>";
xmlString = "<Root>" + xmlString.Replace("<", "<o").Replace("<o/", "</o") + "</Root>";
string key = "";
List<KeyValuePair<string,string>> kvpList = new List<KeyValuePair<string,string>>(); //assuming the result is in the KVP format
using (XmlReader xmlReader = XmlReader.Create(new StringReader(xmlString))){
bool firstElement = true;
while (xmlReader.Read()) {
if (firstElement) { //throwing away root
firstElement = false;
continue;
}
if (xmlReader.NodeType == XmlNodeType.Element) {
key = xmlReader.Name.Substring(1); //cut of "o"
} else if (xmlReader.NodeType == XmlNodeType.Text) {
kvpList.Add(new KeyValuePair<string,string>(key, xmlReader.Value));
}
}
}
Edit:
The main trick is this line:
xmlString = "<Root>" + xmlString.Replace("<", "<o").Replace("<o/", "</o") + "</Root>"; //wrap to make this having single root, o is put to force the tagName started with known letter (comment edit suggested by Mr. chwarr)
Where you first replace all opening pointy brackets with itself + char, i.e.
<1>text1</1> -> <o1>text1<o/1> //first replacement, fix the number issue
and then reverse the sequence of all the opening point brackets + char + forward slash to opening point brackets + forward slash + char
<o1>text1<o/1> -> <o1>text1</o1> //second replacement, fix the ending tag issue
Using simple WinForm with RichTextBox to print out the result,
for (int i = 0; i < kvpList.Count; ++i) {
richTextBox1.AppendText(kvpList[i].Key + " = " + kvpList[i].Value + "\n");
}
Here is the result I get:
This is far from bulletproof, but you could use a combination of split and Regex matching:
string exampleString = "<1>text1</1><27>text27</27><3>text3</3>";
string[] results = exampleString.Split(new string[] { "><" }, StringSplitOptions.None);
Regex r = new Regex(#"^<?(\d+)>([^<]+)<");
foreach (string result in results)
{
Match m = r.Match(result);
if (m.Success)
{
string index = m.Groups[1].Value;
string value = m.Groups[2].Value;
}
}
The most non-bulletproof example I can think of is if your text contains a "<", that would pretty much break this.

accessing data from database and displaying it in textbox

I am using this code for accessing data from database and displaying it in textboxes,but i am getting whole string columns in 1st textbox ,how do i split and display in respective textboxes,i am getting this exception Index was outside the bounds of the array. at this line of code txtOption2.Text = coldata[2];
public EditQuestionMaster(int qid_value)
{
InitializeComponent();
string columns = db.GetEditQuestions(qid_value);
string[] coldata=columns.Split('$');
txtQuestion.Text = coldata[0];
txtOption1.Text = coldata[1];
txtOption2.Text = coldata[2];
txtOption3.Text = coldata[3];
txtOption4.Text = coldata[4];
}
GetEditQuestions(qid_value) Code
public string GetEditQuestions(int qid)
{
string data = "";
try
{
string sql = "select QID,Question,Opt1,Opt2,Opt3,Opt4,AnsOp,Marks from Questions where QID IN(" + qid + ") ";
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
if (rs.Read())
{
data = rs[0].ToString() + "~" + rs[1].ToString() + "~" + rs[2].ToString() + "~" + rs[3].ToString() + "~" + rs[4].ToString() + "~" + rs[5].ToString() + "~" + rs[6].ToString() + "~" + rs[7].ToString() + "$";
}
}
catch (Exception err)
{
}
return data;
}
thank you in advance for any help
You appear to split the string by $ but you build the string up using ~ as the separator. You need to split the string by ~ to get the appropriate number of columns i.e.
string[] coldata = columns.Split("~")
You are seeing that error because you only have 2 items in coldata. Try debugging and view the length of the coldata array to see how many items it contains.
Change your code to use this split instead:
string[] coldata=columns.Split('~');
Looking at your code sample you just need to change:
string[] coldata=columns.Split('$');
To
string[] coldata=columns.Split('~');
As your columns are delimited by the ~ character.

Categories