Replace not working when applied to an html string - c#

As an introduction, I have created a document using MS Word and then saved as html document.
From C# I am building an unordered html list (using MS Word format) and then add it to the html document by replacing a specific tag.
I have below string variable unorderedHtmlList initially initialized to empty string. Then I am concatenating html string and replacing some tags enclosed by "[[" and "]]" characters. For some reason when I apply the Replace it is not replacing the items [[fieldName]] and [[fieldValue]] by the new values. See code below:
string unorderedHtmlList = string.Empty;
foreach (System.Data.DataRow row in myDataTable.Rows)
{
string name = row["fieldName"].ToString();
string value = row["fieldValue"].ToString();
unorderedHtmlList += "<p style='margin-left:36.0pt;text-align:justify;text-indent:-18.0pt;" +
"line-height:125%;mso-list:l1 level1 lfo3'><![if !supportLists]><span" +
"style='font-size:10.5pt;line-height:125%;font-family:\"Arial\",sans-serif;" +
"mso-fareast-font-family:Arial;color:#222222'><span" +
"style='mso-list:Ignore'>-<span style='font:7.0pt \"Times New Roman\"'> " +
"</span></span></span><![endif]><span style='font-size:10.5pt;" +
"line-height:125%;font-family:\"Arial\",sans-serif;color:#222222'>[[fieldName]]" +
"</span><span style='font-size:10.5pt;line-height:125%;font-family:" +
"\"Helvetica\",sans-serif;color:#222222'>[[fieldValue]]</span><span" +
"style='font-size:10.5pt;line-height:125%;font-family:\"Arial\",sans-serif;" +
"color:#222222'><o:p></o:p></span></p>".Replace("[[fieldName]]", name).Replace("[[fieldValue]]", value);
}
Any ideas why Replace is not working?

You are concatanating the string and the replace operation is executed only on the last part.
"color:#222222'><o:p></o:p></span></p>".Replace("[[fieldName]]", name).Replace("[[fieldValue]]", value);
Try this:
unorderedHtmlList += ("<p style='margin-left:36.0pt;text-align:justify;text-indent:-18.0pt;" +
"line-height:125%;mso-list:l1 level1 lfo3'><![if !supportLists]><span" +
"style='font-size:10.5pt;line-height:125%;font-family:\"Arial\",sans-serif;" +
"mso-fareast-font-family:Arial;color:#222222'><span" +
"style='mso-list:Ignore'>-<span style='font:7.0pt \"Times New Roman\"'> " +
"</span></span></span><![endif]><span style='font-size:10.5pt;" +
"line-height:125%;font-family:\"Arial\",sans-serif;color:#222222'>[[fieldName]]" +
"</span><span style='font-size:10.5pt;line-height:125%;font-family:" +
"\"Helvetica\",sans-serif;color:#222222'>[[fieldValue]]</span><span" +
"style='font-size:10.5pt;line-height:125%;font-family:\"Arial\",sans-serif;" +
"color:#222222'><o:p></o:p></span></p>").Replace("[[fieldName]]", name).Replace("[[fieldValue]]", value);

Related

How To Show Icon In TreeView Node Using 2 Strings?

If I have a TreeView with the font to Segoa UI Emoji. I need to set a TreeView node icon using 2 strings but doesn't work. Also, what value can I use for the unicodeEndStr variable below if the unicode only has 4 digits like 2639 ?
// This code shows emoji icon in treeview node followed by a space and some text
string emoji = "\U0001F608" + " " + "Face Savoring Food";
EmojiTreeView.Nodes.Add(emoji);
// This code does not show emoji icon, just \U0001F608 followed by a space and some text
string unicodeStartStr = "\\U000"; // need double back slashes to compile
string unicodeEndStr = "1F608";
string emojiCodeStr = unicodeStartStr + unicodeEndStr;
string emojiStr = emojiCodeStr + " " + "Face Savoring Food";
EmojiTreeView.Nodes.Add(emojiStr);
First parse your combined Unicode string as hex(16-bit) number.
Then use char.ConverFromUtf32(str).ToString() to generate complete Unicode symbol.
Reference solution: Dynamic generate 8-Digit-Unicode to Character
public Form1()
{
InitializeComponent();
treeView1.Nodes.Add("\U0001F608" + " " + "Face Savoring Food");
// remove \u prefix
string unicodeStartStr = "000";
string unicodeEndStr = "1F608";
string emojiCodeStr = unicodeStartStr + unicodeEndStr;
int value = int.Parse(emojiCodeStr, System.Globalization.NumberStyles.HexNumber);
string result = char.ConvertFromUtf32(value).ToString();
string emojiStr = result + " " + "Face Savoring Food";
treeView1.Nodes.Add(emojiStr);
}
Worked result

Ident Tabs for Multiple New Line String Variable in Net Core

How do I ident a set of lines when writing to a file, with a tabs? I need to go through each line in the variable and create 8 spaces or two tabs for each line, when writing to the new file.
If the string was one line, it would be easy, with " " + test, however this has multiple lines.
public static string testLine=
"Line1" + Environment.NewLine +
"Line2" + Environment.NewLine +
"Line3" + Environment.NewLine +
"Line4" + Environment.NewLine +
using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath, true))
{
file.WriteLine(testLine);
String is composed of new line, line breaks enters, etc .
Is there any Microsoft Ident function library to support this?
Needs to handle multiple string variables in the future.
All you need to do is prefix the string with whitespace or a tab and replace all occurences off newlines with a newline and a suitable whitespace:
testLine = " " + testLine.Replace( Environment.NewLine, Environment.NewLine + " " );
You can explicitly handle an empty string to avoid indenting nothing:
testLine = String.IsNullOrEmpty(testLine) ? testLine : " " + testLine.Replace( Environment.NewLine, Environment.NewLine + " " );
Substitute "\t" for " " to insert a tab character.

Create a QR code from multiple textboxes and decode it back into the textboxes

I have created an application. This app contains the five textboxes id, name, surname, age and score.
When a user clicks the "okay button", these values are stores in an sql database.
Additionally, I want to store all of these information in an QR code. And when I decode it, the information should be shown in the textboxes respectively.
These are the references I am using so far.
using AForge.Video.DirectShow;
using Zen.Barcode;
using ZXing.QrCode;
using ZXing;
I can encode an ID number into a picture box, like so:
CodeQrBarcodeDraw qrcode = BarcodeDrawFactory.CodeQr;
pictureBox1.Image = qrcode.Draw(textBox1.Text, 50);
But I want all of the values in the textboxes to be storee in this QR code.
How can i do that?
The essence of the solution is, that you have to combine all the values from the textboxes into one string. To seperate them after decoding the QR code, you have to add a special character between the data values, that does not exist insinde the user input. After decoding the QR code, you can seperate the values by splitting the string at each occurance of the special character.
This is the quick and dirty way of doing that. If you want the QR code to be conformant to any specific format (like vcard), you have to reserach what it takes to compose the data for this format.
I expect your users cannot enter more than one line into the textboxes, so the newline character can be used as seperator character.
Encode all the information into one QR code.
var qrText = textBox1.Text + "\n" +
textBox2.Text + "\n" +
textBox3.Text + "\n" +
textBox4.Text + "\n" +
textBox5.Text;
pictureBox1.Image = qrcode.Draw(qrText, 50);
You can decode the QR code and assigning the data to the different textboxes again.
var bitmap = new Bitmap(pictureBox1.Image);
var lumianceSsource = new BitmapLuminanceSource(bitmap);
var binBitmap = new BinaryBitmap(new HybridBinarizer(source));
var reader = new MultiFormatReader();
Result result = null;
try
{
result = reader.Decode(binBitmap);
}
catch (Exception err)
{
// Handle the exceptions, in a way that fits to your application.
}
var resultDataArray = result.Text.Split(new char[] {'\n'});
// Only if there were 5 linebreaks to split the result string, it was a valid QR code.
if (resultDataArray.length == 5)
{
textBox1.Text = resultDataArray[0];
textBox2.Text = resultDataArray[1];
textBox3.Text = resultDataArray[2];
textBox4.Text = resultDataArray[3];
textBox5.Text = resultDataArray[4];
}
You can get this done by implementing below code :
"{" + '"' + "name" + '"' + ":" + '"' + txtName.Text + '"' + "," + '"' + "lname" + '"' + ":" + '"' + txtLname.Text + '"' + "," + '"' + "Roll" + '"' + ":" + '"' + txtRoll.Text + '"' + '"' + "class" + '"' + ":" + '"' + txtClass.Text + '"' + "}"
Result will be:
{"name":"Diljit","lname":"Dosanjh","Roll","2071","class":"BCA"}
Such that your QR scanner will recognize the data belong to its specific filed.

Prevent last key in string to have a comma

Having trouble figuring out how to prevent the last key in my array to not have a comma. Since its being exported to a .Json file the last key shouldn't have a ",".
I know you can detect it by using .Last();, but I can't seem to make that work. Any recommendations?
//Data Path
string dataPath = #"..\..\FileIOExtraFiles\DataFieldsLayout.txt";
string[] dataList = File.ReadAllLines(dataPath);
//save Data data
using (StreamWriter outStream = new StreamWriter(outputFolder + #"\CharacterStringData3.json"))
{
outStream.WriteLine("{");
for (int i = 0; i < dataFile.Length; i++)
{
string s = dataFile[i];
char last = s.Last();
if (s == "")
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
}
else
{
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\",");
}
}
outStream.WriteLine("}");
}
Output:
{
"data1":"item1",
"data2":item2",
"lastKey":item3",//trying to remove comma from last key in array.
}
As others have pointed out, it doesn't make sense that you are building json manually, but given that this is a question more about technique, here is one approach: you could change it to this:
var commaSuffix = (i == dataFile.Length - 1) ? "," : string.Empty;
outStream.WriteLine("\"" + dataList[i] + "\"" + " : \"" + s + "\"" + commaSuffix);
The suffix would be used on every iteration except the last.
Change this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \",");
To this
outStream.WriteLine("\"" + dataList[i] + "\"" + " : " + "\" \""+(i==dataFile.Length?",":""));
Instead of using outStream.WriteLine() at every step, store it in a string. Then you can remove the last comma from that string and write the whole string at once:
//Get last index of comma
int lastCommaIndex = outputString.LastIndexOf(',');
//Create new StringBuilder with everything before the last comma
StringBuilder sb = new StringBuilder(outputString.Substring(0,lastCommaIndex));
//Add everything after the last comma, or just add a closing brace
//sb.Append("}"); //This instead of next line
sb.Append(outputString.Substring(lastCommaIndex+1));
//Add contents of StringBuilder to the Stream
outSteam.WriteLine(sb);

How to obtain inner tags value in XML?

XDocument coordinates = XDocument.Load("http://feeds.feedburner.com/TechCrunch");
System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(DestFile);
XNamespace nsContent = "http://purl.org/rss/1.0/modules/content/";
string pchild = null;
foreach (var item in coordinates.Descendants("item"))
{
string link = item.Element("guid").Value;
//string content = item.Element(nsContent + "encoded").Value;
foreach (var child in item.Descendants(nsContent + "encoded"))
{
pchild = pchild + child.Element("p").Value;
}
StreamWriter1.WriteLine(link + Environment.NewLine + Environment.NewLine + pchild + Environment.NewLine);
}
StreamWriter1.Close();
If i use Commented line code (string content = item.Element(nsContent + "encoded").Value;) instead of inner for loop than it will fetch the value of <conten:encoded> element but it contains all links, images etc etc. And I want only text.
For that I have tried to use this filter (inner for loop) but its showing error :
Object reference not set to an instance of an object.
Please suggest me code so that I can store only text and remove all other links, <img> tags etc.
The content of item.Element(nsContent + "encoded").Value is html not xml. You should parse it accordingly, such as using Html Agility Pack
See the example below
string content = item.Element(nsContent + "encoded").Value;
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(new StringReader(content));
var text = String.Join(Environment.NewLine + Environment.NewLine,
doc.DocumentNode
.Descendants("p")
.Select(n => "\t" + System.Web.HttpUtility.HtmlDecode(n.InnerText))
);
Firstly, I would start by using a StringBuilder:
StringBuilder sb = new StringBuilder();
Then, I suspect that sometimes, the "child" doesn't have a "p" element, so you can check before using it:
foreach (var child in item.Descendants(nsContent + "encoded"))
{
if (child.Element("p") != null)
{
sb.Append(child.Element("p").Value);
}
}
StreamWriter1.WriteLine(link + Environment.NewLine + Environment.NewLine + sb.ToString() + Environment.NewLine);
Does that work for you?

Categories

Resources