Unterminated string constant error in asp.net - c#

Got this error while call the function
static public void DisplayAJAXMessage(Control page, string msg)
{
string myScript = String.Format("alert('{0}');", msg);
ScriptManager.RegisterStartupScript(page, page.GetType(), "MyScript", myScript, true);
}
Calling this function:
string sampledata = "Name :zzzzzzzzzzzzzzzz<br>Phone :00000000000000<br>Country :India";
string sample = sampledata.Replace("<br>", "\n");
MsgBox.DisplayAJAXMessage(this, sample);
I need to display Name,Phone and Country in next line.

Unterminated string constant means you've forgotten to close your string. You can't have an alert that runs over multiple lines. When the script is outputting to the browser, it's actually including the new lines.. not the "\n" like the javascript expects. That means, your alert call is going over multiple lines.. like this:
alert('Name :zzzzzzzzzzzzzzzz
Phone :00000000000000
Country :India');
..which won't work, and will produce the error you're seeing. Try using double backslash to escape the backslash:
string sample = sampledata.Replace("<br>", "\\n");

"\n" is a newline for C#, i.e. your js contains:
something('...blah foo
bar ...');
what you actually want is a newline in js:
something('...blah foo\nbar ...');
which you can do with:
string sample = sampledata.Replace("<br>", "\\n");
or:
string sample = sampledata.Replace("<br>", #"\n");

You need to escape/encode your string being consumed by JavaScript:
Escape Quote in C# for javascript consumption

Your Unterminated is not in C# is in Javascript generated code.

Related

Special character replacement from code of the apostrophe in a file name path

The problem I'm having is in regards to a file that is being generated on the server and the .NET code is invoking a Javascript method to download a file to the client, but it fails if the file name has an apostrophe (').
So for example:
If the ExportExcelFileName = "C:\HereIsMyFile.xls" it works fine.
However, if the
ExportExcelFileName = "C:\Here'sMyFile.xls"
it throws a failure to evaluate exception.
I tried adding [.Replace("'", "\\'")] and [.Replace("'", "%27")] but no luck...
string script = string.Format("DownLoadFile('{0}')", e.Result.ExportExcelFileName).Replace('\\', '/');
HtmlPage.Window.Eval(script);
I figured it out:
when I tried this:
string script = string.Format("DownLoadFile('{0}')", e.Result.ExportExcelFileName).Replace('\\', '/').Replace("'", "\\'");
HtmlPage.Window.Eval(script);
It was also replacing the single quotes in the javascript command of DownloadFile('{0}').
So I simply did the replacement first like so:
var escapedFileName = ((e.Result.ExportExcelFileName).Replace('\\', '/')).Replace("'", "\\'");
string script = string.Format("DownLoadFile('{0}')", escapedFileName);
HtmlPage.Window.Eval(script);
Would a simple method like this work?
private static string quoteReplace(string psString)
{
return psString.Replace("'", "");
}
Try using URI escaping for the file name:
Uri.EscapeDataString(filePathHere);. See Uri.EscapeDataString on MSDN.
Also see: If filename has single quote C# javascript does not get executed

printing some HTML in a string in Asp.net

i have some html content and i stored it in string variable and i want to print it directly.Is there any way in c# ?i have a javascript code which is not working
string emailbody="HTML i need to send";
Page.RegisterStartupScript("StatusMessage", "<SCRIPT LANGUAGE=\"JavaScript\">function printsheet(" + emailbody + "){var win = window.open('mywindow', 'left=0', 'top=0')var html = Zstring; win.document.open()win.document.write(html);win.print();}</Script>");
You have many ways to do that.
One way, make the string public
public string emailbody="HTML i need to send";
and on aspx page you render it as:
<%=emailbody%>
One other way is to use a Literal control and render it there. When you have UpdatePanel this is the only way.
Eg, you place the Literal on page, on the point you wish to render your text as:
<asp:Literal runat="server" id="txtRenderOnMe" />
and on code behind you type:
txtRenderOnMe.Text = "HTML i need to send";
Now, in your case the issue is that you render a string on the javascript code without the quotas as the other jesse point out on their comments.
string emailbody="HTML i need to send";
Page.RegisterStartupScript("StatusMessage", "<script language=\"JavaScript\">function printsheet('" + emailbody + "'){var win = window.open('mywindow', 'left=0', 'top=0')var html = Zstring; win.document.open()win.document.write(html);win.print();}</script>");

Format string to HTML in C#

So I am writing a game with Unity and I am sending players an email with all of their stats on how they played. The way I send the email is I format a string that has the html already written that replaces a specifier $_table to insert the data I need to send to a php script on my server that emails the user. All of this works.
I am having a problem though with sending links to images. Since I am doing this in a C# program I am having a hard time with <img src ="example.com/example.png"/> tags.
When it sends it sends it formated as <img src=\"example.com/example.png\"/> and doesn't show the image.
How can I send this string correctly in C#?
I have already tried " and using #"""" to format the string.
Any and all help is appreciated.
::Edit::
Updated for code.
So in my C# code I am reading from a txt file my base html. The problem is
when I am replacing with my table which has img tags in it.
I have a Email Function SendEmail which sends a form. In the form it has a
message parameter which is just a string. This form is sent to a php script
which sends to the email from the form.
//Unity Code
public static void SendEmail(string _email, string subject, string message)
{
if(CheckEmail(_email))//Checks if valid email form
{
WWWForm form = new WWWForm();
form.AddField("from", "example#example.com");
form.AddField("email", _email);
form.AddField("subject", subject);
form.AddField("message", message);
WWW web = new WWW("http://www.example.com/_email.php", form); //Unity class for various web functions
}
else
{
label.text = "Invalid Email";
}
}
The message I am sending is a table with img links which are referenced by string variables for readability.
public static string GetFormatedMetricTable(){
int time = 0;
string clockIcon = "<img src = "http://files.softicons.com/download/web-icons/web- grey-buttons-by-axialis-team/png/48x48/Clock.png"/>";
return "<table><tr><td>" + time + clockIcon + "</td></tr></table>";
}
The code above is reduced for this example but only content wise.
In my php code I am using a simple mail function to send the email from my smtp server.
The problem is in the string formatting of the double quote.
When viewed within the html code from the email I get /" which results in the images not showing.
Desired result http://subligaming.com/example.html
Note: Using Mono .Net
Here is my php code just incase.
<?php
$from = $_REQUEST['from'];
$name = $_REQUEST['name'];
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
// $newMessage = str_replace(""", '$_"', $message);
// $newerMessage = str_replace("$_", "", $newMessage);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: Subliminal Gaming <$from>\r\n";
mail($email, "$subject",
$message, $headers );
echo "Thank you for using our mail form";
?>
I am currently reading up on how the string literals work in php and that may be the problem but I do not know how to fix it. Any pointers?
Just try to use simple quotes in the html tag
<img src ='example.com/example.png'/>

How to make a function into a class or module in c#

I am just learning how to use classes in my projects. I have been working on a DataAccessClass.cs and am doing well (I think).
Taking a break from data access, I decided to try to make a void into a class. This void sends a message to the client as a javascript alert. It works well, but has to be included on each page. When I tried to make it a class, I was informed that my class does not contain a definition for ClientScript. I included all the "using" directives from the original page to no avail... Any hints or suggestions would be greatly appreciated.
The original code:
//------------------------------------------------------------------------------
//Name: SendErrorMessageToClient
//Abstract: show alert on client side
//------------------------------------------------------------------------------
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
Messages are sent into this void like this:
if (DataAccessClass.OpenSqlConnection(ref Conn, strConn, out strErrorMessage) == false)
{
string strErrorType = "Database Connection Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
Or this:
catch (Exception excError)
{
string strErrorType = "Unhandled Exception:";
string strErrorMessage = excError.Message;
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
You are receiving the error as 'Clientscript' is a property derived from a System.Web.UI.Page and by moving into a separate class file, you no longer have access to this property.
You could solve this by passing in the page as well, and amending the code to
protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage, Page page)
{
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";
page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}
ClientScript Property is part of the Page class that every ASPX page inherit from. Therefore you can not just use it from inside your class unless it (i.e. your class) has Page as its base class.
this. is for fields in your method in classes.
Why do you want to make this a class? It shouldn't be a class, it doesn't have any properties or fields, unless you can think of one. You do understand if you make it a class you would still have to intialize it on every page.
You could make it a static string method you would still have to include this on every page.
this.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
You'll need to pass the page into the function
SendErrorMessageToClient(Page page, string strErrorType, string strErrorMessage)
so that you can change
this.ClientScript...
to
page.ClientScript...
The reason being that ClientScript is part of the Page class
Or, possibly better, pass the ClientScript object, rather than page.
So your definition would look like
SendErrorMessageToClient(ClientScript clientScript, string strErrorType, string strErrorMessage) {
string strMessageToClient = "";
//Allow single quotes on client-side in JavaScript
strErrorMessage = strErrorMessage.Replace("'", "\\'");
strMessageToClient = String.Format("<script type='text/javascript' language='javascript'>alert('{0}\\n\\n{1}');</script>",
strErrorType, strErrorMessage);
clientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);
}

Why are backward slashes removed from querystring - ASP.NET & Javascript

I am trying to generate a URL that contains a UNC path as one of the query string variables. The URL will open in a pop up window when an ASP.NET button control is clicked by the user. When the clicks the button, the backwards slashes are removed from the UNC path causing the page to break.
The button renders correctly in the page source file with all the backward slashes.
Is there any way to prevent this?
Here is my source code:
Code behind:
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + url + #"')");
ASPX page
<script language="javascript" type="text\javascript">
function FullPop(Newurl) {
Win = window.open( Newurl,"Monitor", "fullscreen=0,toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=600,top=50,left=50");
Win.focus();
}
</script>
<asp:button id="MyButton" runat="server" cssclass="mycss" text="View Actual Target" />
Update
Server.UrlEncode does not work. Same behavior.
Update 1
Based on Daniel Lew's answer, I developed the following solution:
protected void Page_Load(object sender, EventArgs e)
{
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + this.EscapeforJavaScript(url) + #"')");
}
private string EscapeforJavaScript(string url)
{
return url.Replace(#"\", #"\\");
}
You have to URL encode the value that you put in the URL:
string url = "http://www.mysite.com/page.aspx?a=" + Server.UrlEncode(unc);
Edit:
To safely put the url in the Javascript code, you also have to encode the string for being a literal string:
MyButton.Attributes.Add("onclick", #"FullPop('" + url.Replace(#"\", #"\\").Replace("'", #"\'") + #"')");
(The javascript: protocol is only used when the Javascript is used as href for a link, not when you put code in an event like onclick.)
I don't know anything about asp.net, but I have had experience with problems when adding text straight into JavaScript before through templating. Have you tried escaping the backslashes on your url, to avoid this?
// Returns "\myservermyfoldermyfile.txt", due to escpaing the backslash.
alert("\\myserver\myfolder\myfile.txt");
// Returns correct value of "\\myserver\myfolder\myfile.txt"
alert("\\\\myserver\\myfolder\\myfile.txt");
You may want to try URLEncoding your string on your server side, using the following method:
public static string UrlFullEncode(string strUrl)
{
if (strUrl == null)
return "";
strUrl = System.Web.HttpUtility.UrlEncode(strUrl);
}
I'm not 100% sure it if will replace the backslashes, but it's worth a try.

Categories