Asp.net, Syntax highlight code from file with google prettify - c#

In my page I will get the ID from link parameters, with that ID I will search the database for the file path, after reading the file and storing its contents I want to put its contents inside my <pre> tag... So I will have a literal in which the text for it will be:
Code.Text = "<pre>" + File Contents in string + "</pre>";
My question is how will I insert the contents there if I need to read the file line by line into an string array, unless I read it all into one string, BUT that will make the text look like one huge line in the page.
Also, is it going to conflict with literal syntax(?) definitions, since for quotes we have to do \" instead of " ...?

If you are working with literal control, you use the StringBiulder And Append properties becouse It let you put any HTML code from code behind.
Something like:
//Declare your String Builder
private StringBuilder stb = new StringBuilder();
And also you could have any proccess when you read the file, and split it by any char like \n
string readFile = //Any Method that you read you file string.
string[] tokens = readFile.Split('\n');
stb.Append("<pre>");
foreach (string s in tokens)
{
stb.Append( s + "<\br>");
}
stb.Append("</pre>");
finally you attach the Stringbuilder value to you Literal
YourLiteral.Text = stb.ToString();
I hope that help, and you won't have the value in one line. And remember the carring return need be in the string file to the split works.
Cheers

Related

how to check string value if table tag is available and implement regex

I have this string variable which composes a text and html tags. how do i perform regex only within the html table tag? is this possible?
string input = "Hello,\nTRAVEL DETAILS\n<table border=\"1\">\n<tr>\n<th align=\"center\">Initial Travel Date</th>\n<th align=\"center\">Reference Number</th>\n<th align=\"center\">First Name</th>\n<th align=\"center\">Surname</th>\n<th align=\"center\">Main Reason</th>\n<th align=\"center\">Client ID</th>\n</tr>\n<tr>\n<td align=\"center\">{TRV TRL INIT.trn}</td>\n<td align=\"center\">{TRV REF NO.trn}</td>\n<td align=\"center\">{TRV FIRST NM.trn}</td>\n<td align=\"center\">{TRV SURNAME.trn}</td>\n<td align=\"center\">Internal Meeting</td>\n<td align=\"center\">{TRV CLIEN ID.trn}</td>\n</tr>\n</table>"
string output = Regex.Replace(input, #"\t|\n|\r", "");
return output;
i only need to remove the "\n" inside the table element
You can use the WebBrowser control to parse the HTML string, get the table chunk and remove the new lines from there.
Or you can utilise IHTMLDocument, IHTMLDocument2, IHtmlDocument3 ... up to 8 to parse the HTML. You need to include Mshtml.dll in your project references though.
Or use a 3rd party HTML parser.
Do not try to manipulate the raw string unless you wanna write your own HTML parser.
i have found a way to eliminate the "\n" inside the table. but then it resulted for not using the regex. here's the updated codes
string input = emailMessage.Message.Replace("\n<tr>\n", "<tr>").Replace("</th>\n", "</th>").Replace("\n</tr>", "</tr>")
.Replace("</td>\n", "</td>").Replace("\n</table>", "</table>");
string output = input;
return output;
thank you to all of the comments and suggestions

Read a CSV file and writer into a file without " " using C#

I am trying to read a CSV file and stored all the values in the single list.CSV file contains credentials as uid(userid) and pass(password) and separated by','I have successfully read all the lines and write it in the file.but when it writes in the file, it write the value in between " "(double quotes) like as("abcdefgh3 12345678")what i want actually to remove this "" double quotes sign when i write it in to the files.i am pasting my code here:
static void Main(string[] args)
{
var reader = new StreamReader(File.OpenRead(#"C:\Desktop\userid1.csv"));
List<string> listA = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
listA.Add(values[1]);
}
foreach (string a in listA)
{
TextWriter tr = new StreamWriter(#"E:\newfiless",true);
tr.Write(a);
tr.Write(tr.NewLine);
tr.Close();
}
}
and the resulted output is like this:
"uid
pass"
"Martin123
123456789"
"Damian
91644"
but i want in this form:
uid
pass
Martin123
123456789
Damian
91644
Thanking you all in advance.
The original file clearly has quotes, which makes it a CSV file with only one colum and in that column there are two values. Not usual, but it happens.
To actually remove quotes you can use Trim, TrimEnd or TrimStart.
You can remove the quotes while reading, or while writing, in this case it doesn't really matter.
var line = reader.ReadLine().Trim('"');
This will remove the quotes while reading. Note that this assumes the CSV is of this "broken" variant.
tr.WriteLine(a.Trim('"'));
This will handle it on write. This will work even if the file is "correct" CSV having two columns and values in quotes.
Note that you can use WriteLine to add the newline, no need for two Write calls.
Also as others have commented, don't create a TextWriter in the loop for every value, create it once.
using (TextWriter tr = new StreamWriter(#"E:\newfiless"))
{
foreach (string a in listA)
{
tr.WriteLine(a.Trim('"'));
}
}
The using will take care of closing the file and other possible resources even if there is an exception.
I assume that all you need to read the input file, strip out all starting/ending quotation marks, then split by comma and write it all to another file. You can actually accomplish it in a one-liner using SelectMany, which will produce a "flat" collection:
File.WriteAllLines(
#"c:\temp\output.txt",
File
.ReadAllLines(#"c:\temp\input.csv")
.SelectMany(line => line.Trim('"').Split(','))
);
It's not quite clear from your example where quotation marks are located in the file. For a typical .CSV file some comma-separated field might be wrapped in quotation marks to allow commas to be a part of the content. If it's the case, then parsing will be more complex.
You can use
tr.Write(a.Substring(1, line.Length - 2));
Edited
Please use Trim
tr.Write(a.TrimEnd('"').TrimStart('"'));

Find and Delete Characters in String

My program reads registry key values and combines those values with the installation path. I also read the installation path from the registry.
i.e. String dllInstpath = installPath + rKey which equals to:
C:\Program Files (x86)\NSi\AutoStore Workflow 6\HpOXPdCaptureRes.dll
I then use FileVersionInfo on the string above to get the file information of HpOXPdCaptureRes.dll from it's install path and write all the values to a notepad.
My problem is the TRUE dll name does not have 'Res' in the file name. The registry only has the file name with 'Res' in the file name. What I need to do is read from a text file and find all 'Res' and remove them from the line of text within the notepad file.
So the output should look like this:
Current:
HpOXPdCaptureRes.dll
New:
HpOXPdCapture.dll
I have read online and I see the best way to do this is to use ReadAllLines and WriteAllLines. However I am not sure how to implement the find and replace. I have seen a lot of examples on how to remove spaces, invalid characters, etc., but I haven't been able to find an example for what I need.
Summary:
Read text file
Fine Res in all lines of text and remove
Retain current text file, i.e. remove Res and close file
Any help is greatly appreciated.
Thank you!
You can use File.ReadAllLines and File.WriteAllLines.
Example:
Read all the lines and replace the value you want on each line, then write the lines again
File.WriteAllLines("textFilePath",File.ReadAllLines("textFilePath").Select(line => line.Replace("Res.dll", ".dll")));
Just open the file and read all lines using 'File.ReadAllLines'. Then use Replace to remove the Res:
string[] lines = File.ReadAllLines("yourFileName");
var output = lines.Select(x => x.Replace("Res.dll", ".dll")).ToArray();
To later save them back you can use File.WriteAllLines:
File.WriteAllLines("yourFileName", output);
Read everything from file, replace all occurrences of 'res' and write to file:
String filename = "fileName";
StreamReader sr = new StreamReader(filename);
String content = sr.ReadToEnd();
sr.Close();
StreamWriter sw = new StreamWriter(filename);
sw.Write(content.Replace("res", ""));
sw.Close();
If the string you are replacing is guaranteed to be unique in the string - "res.dll" at the end of the string for instance - then you can use Replace method of the String class to do the replacement:
List<string> lines = File.ReadAllLines(sourceFile);
lines = lines.select(l => l.Replace("res.dll", ".dll").ToList();
Or if case sensitivity is an issue:
lines = lines.Select(l => l.Substring(l.Length - 7).ToLower() == "res.dll" ? l.Substring(0, l.Length - 7) + ".dll" : l).ToList();
For more complex cases you might need to use a regular expression to identify the section of the string to replace. Or you might want to split the string int path and filename, modify the filename and join it back together.

c# Rich text Format error in code

hoping you can help
I have the following code
List<string> comconfig = populate.resolveconfig(_varibledic, populate.GetVaribles[0].Substring(populate.GetVaribles[0].IndexOf("=") + 1)); //get the aray of strings
string config = ""; //create a empty otput string
config = #"\rtf1\ansi\deff0\deftab240 {\fonttbl {\f000 Monaco;} {\f001 Monaco;} } {\colortbl \red255\green255\blue255; \red000\green000\blue000; \red255\green255\blue255; \red000\green000\blue000; }";
config = config + #"\f96\fs20\cb3\cf2 \highlight1\cf0 "; // assigned rtf header to output string
foreach (var strings in comconfig) //loop though array adding to output string
{
config = config + strings + #"\par ";
}
config = config + "}"; //close of RTF code
So trying to create a RTF string that I can later display. comconfig is an array of strings with some RTF mark up for highlighting and stuff.
trouble is that if I use # then I get double \ which mess up the RTF, and if i dont use them, then the escape charatures mess up the code??
what is the best way to build up this string by adding a preformated RTF header and the aray of strings in the middle. it is displayed finaly in a RTF.textbox. or converted to a plain text string at the users request. I need to ignore the escape charatures with out messing up the RTF?
Cheers
Aaron
No, you don't get a double \. You're getting confuzzled by the debugger display of the string. It shows you what the string looks like if you had written it in C# without the #. Click the spy glass icon at the far right and select the Text Visualizer.

ASCII raw symbols to control a printer from a .txt file

A label printer is controled by sending a string of raw ASCII characters (which formats a label). Like this:
string s = "\x02L\r" + "D11\r" + "ySWR\r" + "421100001100096" + date + "\r" + "421100002150096" + time + "\r" + "421100001200160" + price + "\r" + "E\r";
RawPrinterHelper.SendStringToPrinter(printerName, s);
This hardcoded variant works well.
Now I want to put the control string to a .txt file and read it during runtime. Like this:
string printstr;
TextReader tr = new StreamReader("print.txt");
printstr = tr.ReadLine();
tr.Close();
But in this case printer prints nothing.
It seems, that StreamReader adds something else to this string
(If I put the read string to a MessageBox.Show(printstr); everything looks OK. Though, this way we can not see control characters added).
What could be a solution to this problem?
Your code calls tr.ReadLine() once, but it looks like you have multiple lines in that string.
Looks like a Zebra label printer, I've had the displeasure. The first thing you need to fix is the way you generate the print.txt file. You'll need to write one line for each section of the command string that's terminated with \r. For example, your command string should be written like this:
printFile.WriteLine("\x02L");
printFile.WriteLine("D11");
printFile.WriteLine("ySWR");
printFile.WriteLine("421100001100096" + date);
printFile.WriteLine("421100002150096" + time);
printFile.WriteLine("421100001200160" + price);
printFile.WriteLine("E");
printFile.WriteLine();
Now you can use ReadLine() when you read the label from print.txt. You'll need to read multiple lines to get the complete label. I added a blank line at the end, you could use that when you read the file to detect that you got all the lines that creates the label. Don't forget to append "\r" again when you send it to the printer.
It could be that the StreamReader is reading it in an Unicode format. By the way, you are reading in only just one line...you need to iterate the lines instead...Your best bet would be to do it this way:
string printstr;
TextReader tr = new StreamReader("print.txt",System.Text.Encoding.ASCII);
printstr = tr.ReadToEnd();
tr.Close();
Or read it as a binary file and read the whole chunk into a series of bytes instead, error checking is omitted.
System.IO.BinaryReader br = new System.IO.BinaryReader(new StreamReader("print.txt", System.Text.Encoding.ASCII));
byte[] data = br.ReadBytes(br.BaseStream.Length);
br.Close();
Edit:
After rem's comment I thought it best to include this additional snippet here...this follows on from the previous snippet where the variable data is referenced...
string sData = System.Text.Encoding.ASCII.GetString(data);
Hope this helps,
Best regards,
Tom.

Categories