Issue with string in c#? - c#

I am creating a string in c#.
string jsVersion = #"function getContent() {
var content = " + "\"" + documentString + "\"" + #"
return content;
}";
The documentString variable contains a huge string which have line breaks also. Now in javascript when i load this string the content variable does not contains a valid string (because of line breaks).
Now how can i create a string which is valid even if there is line breaks ?

You can use HttpUtility.JavaScriptStringEncode

Can you use string.format instead of concatenation in this fashion?
An example:
string jsVersion = string.format("function getContent() {var content = '{0}'return content; }",documentString);

This will replace your line breaks with <br/>:-
stringToDecode.replace(/\n/, '<br />')

If you want to get rid of the line breaks just remove # from the sting.
# acts a verbatim for your string and therefor adds the line breaks you entered with your declaration.
string jsVersion = "function getContent() {
var content = " + "\"" + documentString + "\"" + "
return content;
}";
should do the trick.

Related

How do I use an illegal character?

public void CreateCertificate()
{
File.Create($"
{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear +
" Certificates- " + certType + "\""}{myFileName}.ppt", 1 ,
FileOptions.None);
}
So I need the backslash between certype and filename to show it belongs within the folder and not next to. It says its an illegal character but how would I get the file in the folder without it?
Based on the code that you wrote the file path that will be generated is (based on my own substitutions for the variables):
String thisYear = "2019";
String certType = "UnderGrad";
String myFileName = "myfile";
String fileToCreate = $"{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear + " Certificates- " + certType + "\""}{myFileName}.ppt";
Debug.Print(fileToCreate);
Will give you this output:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad"myfile.ppt
If you notice there is a " before the filename part of myfile.ppt - This is where the Illegal Character comes from.
If you use this code fragment to generate the path:
String basePath = #"C:\Users\Director\Documents\TestCertApp\TestSub\";
String certificateFolder = $"{thisYear} Certificates- {certType}";
String correctFilePath = Path.Combine(basePath, certificateFolder, $"{myFileName}.ppt");
Debug.Print(correctFilePath);
This will result in the output of:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad\myfile.ppt
This version has a \ where the previous code had a " and is no longer illegal, but conforms to the requirement that you wrote the files being in the folder.
Something else to note:
You may want to use Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); to get the path to the MyDocuments folder of the user.
Well, the short answer is that you cannot use an illegal character in a path or file name. Otherwise it wouldn't be illegal. :)
But it seems that the problem here is that you though you were adding a backslash (\) character, when really you were adding a double quote (") character. So if everything else is ok, you can just replace "\"" with "\\" and it should work.
Part of the problem is also that you're doing some strange combination of string interpolation, and it makes the code really hard to read.
Instead you can use just string interpolation to simplify your string (I had to use concatenation below to prevent horizontal scrolling, but you could remove it):
string filePath = $#"C:\Users\Director\Documents\TestCertApp\TestSub\{thisYear} " +
$#"Certificates- {certType}\{myFileName}.ppt";
But even better would be to use the Path.Combine method, along with some variables, to make the intent very clear:
var rootDir = #"C:\Users\Director\Documents\TestCertApp\TestSub"
var fileDir = $"{thisYear} Certificates- {certType}"
var fileName = "{myFileName}.ppt";
var filePath = Path.Combine(rootDir, fileDir, fileName);

Losing quotes or getting extra \ sign arround string

Here is something pretty basic for c# String class.
//I get string error as input parameter
string error = "Hello World!";
string eventHandlerStr = "onmouseover = 'ShowError(" + "event" + ", \"" + error + "\")'";
// result is "onmouseover = 'ShowError(event, \"Hello World!"\)'"
How to get result without \ around "Hello World!"? And I need quotes arround Hello World!
If I do this:
string eventHandlerStr = "onmouseover = 'ShowError(" + "event" + ", " + error + ")'";
I get Hello World! without quotes.
I tried even removing \ character with String.Remove method but \ stayed there after removing.
Try verbatim string -> #
Here you are everything you need:
https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
UPDATE 2018/06/07
New documentation from MS:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim (second point)
Cache from WebArchive for original link: https://web.archive.org/web/20170730011023/https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
Can you try this?
string format = #"onmouseover = 'ShowError(event, ""{0}"")'";
string error = "HelloWorld";
string pqr = string.Format(format, error);

How to give url properly to anchor tag in asp.net using jquery?

I have written jquery in .net application as
Function UploadComplete(sender, args) {
var filename = args.get_fileName();
var contentType = args.get_contentType();
var folder = "~/Uploads/";
var text = "Size of " + filename + " is " + args.get_length() + " bytes";
if (contentType.length > 0) {
text += "and content type is '" + contentType + "'.";
text += "<a href='" + folder + filename + "'" + filename + "</a>";
}
document.getElementById('lblStatus').innerText = text;
}
Now my issue is I am not able to give path accurately in the line
text += "<a href='" + folder + filename + "'" + filename + "</a>";
Please help me!!!
A few issues to sort out:
1) "~/"
"~/" as a relative path is for use server-side in .Net. Javascript (really your browser) does not know what to do with that URL.
As a little trick, you can inject an application root URL using this Razor code #(Url.Content("~/")) but that means your function needs to be in a razor page and not a separate JS file.
If your JS is "elsewhere", inject the path as a Javascript variable (e.g. window.rootUrl = "#(Url.Content("~/"))") using a small script section on the page.
2) Missing '>'
You are missing a closing > in your generated anchor.
3) innerHTML, not innerText
You need to set the innerHTML property, or you will get raw text. You will probably need to tweak the formatting of the output (line breaks or spans/paragraphs) to make it look pretty (e.g. you have no space before the anchor at the moment).
Put it all together and you get something like:
function UploadComplete(sender, args) {
var filename = args.get_fileName();
var contentType = args.get_contentType();
var folder = '#(Url.Content("~/"))Uploads/';
var text = 'Size of ' + filename + ' is ' + args.get_length() + ' bytes';
if (contentType.length > 0) {
text += 'and content type is "' + contentType + '". ';
text += '' + filename + '';
}
document.getElementById('lblStatus').innerHTML = text;
}
As I said in comment, I strongly recommend using the single quote as a string delimiter in jQuery/JavaScript so that any HTML strings have double-quotes on attributes.
4) jQuery?
You tagged the question with jQuery too, which would shorten the last line to:
$('#lblStatus').html(text);
Apologies for any typos, I typed all this off the top of my head and did not verify it.

String.Replace Not modifying my String

I am trying to save a number of images and I'd like to use the DateTime to have distinct and identifiable Filenames.
So I create a String with the correct Path, add the datetime to it and remove the spaces, dots and colons.
String imagePath = "D:\\Patienten\\" + username;
imagePath += "\\"+DateTime.Now.ToString();
Console.WriteLine("WithFilename: " + imagePath);
imagePath.Replace(" ", "");
Console.WriteLine("Without \" \" : " + imagePath);
imagePath.Replace(".", "");
Console.WriteLine("Without \".\": " + imagePath);
imagePath.Replace(":", "");
Console.WriteLine("Output format: " + imagePath);
imagePath += ".png";
image.Save(imagePath);
According to the console output the String doesnt change at all.
Meaning all the Output Strings from Console.Writeline are identical.
I am using c# in visual Studio Express 2010 in case that makes a difference.
Can anyone find an Error here?
Thanks in advance!
Strings are immutable, the modified string will be a new string that is returned from the function
e.g.
imagePath = imagePath.Replace(" ", "");
Why strings are immutable
Why not just use DateTime.ToString() with a format and drop the dividers using that? Would be more efficient than performing several String.Replace() yourself:
string imagePath = "D:\\Patienten\\" + username + "\\" + DateTime.Now.ToString("yyyyMMdd hhmmssfff") + ".png";
You should use:
imagePath = imagePath.Replace(" ", ""); You should assign returned value
From the documentation (emphasis mine):
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
It is supposed to work like that. Use
imagePath = imagePath.Replace(" ", "");
instead.

String woes in C# - having a . next to a "

I have the following string:
string text = #"" + reportName + "<br/><br/>";
When this string gets written to my page, it looks like this:
DR - 3: Debt Payment History
Can someone help explain why the period id being escaped? I'm fumbling with how to escape this properly.
Thanks.
I'm not sure exactly what your output should look like but
String.Format and escaping are your friend.
string text = String.Format("<a href='http://raustdsx0700.real.local:7782/analytics/saw.dll?PortalPages&PortalPath={0}&Page={1}&P0=1&P1=eq&P2=Project.\"Project Name\"'' target='_blank'>{1}</a><br/><br/>",dashboardURL,reportName);
If you are intent on using quotes in your URL, then use single-quotes for your tag attributes.
string text = "<a href='http://raustdsx0700.real.local:7782/analytics/saw.dll?PortalPages&PortalPath=" + dashboardURL + "&Page=" + reportName + "&P0=1&P1=eq&P2=Project.\"Project Name\"' target='_blank'>" + reportName + "</a><br/><br/>";
Or better, url-escape the quote (%22):
string text = "<a href='http://raustdsx0700.real.local:7782/analytics/saw.dll?PortalPages&PortalPath=" + dashboardURL + "&Page=" + reportName + "&P0=1&P1=eq&P2=Project.%22Project Name%22' target='_blank'>" + reportName + "</a><br/><br/>";
You need to urlencode your string, check this out: http://msdn.microsoft.com/en-us/library/zttxte6w.aspx

Categories

Resources