C# alternative for javascript escape function - asp.net

what is an alternative for javascript escape function in c# for e.g suppose a string:"Hi Foster's i'm missing /you" will give "Hi%20Foster%27s%20i%27m%20missing%20/you" if we use javascript escape function, but what is the alternative for c#. i have searched for it but no use.

You can use:
string encoded = HttpUtility.JavaScriptStringEncode(str);
Note: You need at least ASP.NET 4.0 to run the above code.

var unescapedString = Microsoft.JScript.GlobalObject.unescape(yourEscapedString);
var escapedString = Microsoft.JScript.GlobalObject.escape(yourUnescapedString);

The best solution I've seen is mentioned on this blog - C#: Equivalent of JavaScript escape function by Kaushik Chakraborti. There is more to escaping javascript than simply url-encoding or replacing spaces with entities.

Following is the escape function implementation that you will find in Microsoft.JScript.dll...
[NotRecommended("escape"), JSFunction(JSFunctionAttributeEnum.None, JSBuiltin.Global_escape)]
public static string escape(string str)
{
string str2 = "0123456789ABCDEF";
int length = str.Length;
StringBuilder builder = new StringBuilder(length * 2);
int num3 = -1;
while (++num3 < length)
{
char ch = str[num3];
int num2 = ch;
if ((((0x41 > num2) || (num2 > 90)) &&
((0x61 > num2) || (num2 > 0x7a))) &&
((0x30 > num2) || (num2 > 0x39)))
{
switch (ch)
{
case '#':
case '*':
case '_':
case '+':
case '-':
case '.':
case '/':
goto Label_0125;
}
builder.Append('%');
if (num2 < 0x100)
{
builder.Append(str2[num2 / 0x10]);
ch = str2[num2 % 0x10];
}
else
{
builder.Append('u');
builder.Append(str2[(num2 >> 12) % 0x10]);
builder.Append(str2[(num2 >> 8) % 0x10]);
builder.Append(str2[(num2 >> 4) % 0x10]);
ch = str2[num2 % 0x10];
}
}
Label_0125:
builder.Append(ch);
}
return builder.ToString();
}
Code taken from Reflector.

The best solution I've seen is mentioned on this blog - C#: Equivalent of JavaScript escape function by Kaushik Chakraborti. There is more to escaping javascript than simply url-encoding or replacing spaces with entities.
I noticed another solution in the comments in KodeSharp article that may be better. The comment says it is more compatible with UTF-8 and does not require the reference to JScript. Is this better?
(Dependent on System.Web.Extensions.dll)
using System.Web.Script.Serialization;
JavaScriptSerializer serialiser = new JavaScriptSerializer();
serialiser.Serialize("some \"string\"")

string myString = "Hello my friend";
myString = myString.Replace(" ", "%20");
This would replace all " " with "%20".
Is this what you wanted?

You can try this
Uri.EscapeDataString(Obj);

Related

Is it Possible to Perform Addition in a Regex?

Assuming the placeholder $2 is populated with an integer, is it possible to increment it by 1?:
var strReplace = #"$2";
Regex.Replace(strInput, #"((.)*?)", strReplace);
You can use a callback version of Regex.Replace with a MatchEvaluator, see examples at:
http://msdn.microsoft.com/en-us/library/cft8645c.aspx
http://www.dotnetperls.com/regex-replace
Here's an example (ideone):
using System;
using System.Text.RegularExpressions;
class Program
{
static string AddOne(string s)
{
return Regex.Replace(s, #"\d+", (match) =>
{
long num = 0;
long.TryParse(match.ToString(), out num);
return (num + 1).ToString();
});
}
static void Main()
{
Console.WriteLine(AddOne("hello 123!"));
Console.WriteLine(AddOne("bai bai 11"));
}
}
Output:
hello 124!
bai bai 12
In standard (CS theoretic) regular expressions, it is impossible with a regular expression.
However, Perl and such have extensions to Regular Expressions, which has implications for their behaviour, and I am not familiar enough with them to definitely say that the extended regexes will not do it, but I'm fairly sure that this behaviour is not possible with a regex.
It's not possible with a standard regular expression but you can if you write a custom MatchEvaluator.
string str = "Today I have answered 0 questions on StackOverlow.";
string pattern = #"\w*?(\d)";
var result = Regex.Replace(str, pattern,
m => (int.Parse(m.Groups[0].Value)+1).ToString() );
Console.WriteLine(result);
Today I have answered 1 questions on StackOverlow.

CKEditor to Send Emails with ASP.NET [vb] - Issues with Special Characters

I have a standard HTML page with an CKEditor on it wrapped in a form.
The form submits (POSTS) to Send_Emails.aspx
Send_Emails.aspx reads the content of the FCKEditor into a variable
Dim html As String = Request.Form("ck_content")
Then it sends an email.
Problem
Characters such as:
 -> this seems to show as a special character for blank spaces/carriage returns
’ -> this seems to show as apostrophe's
Can you reccomend some methods to cleanze my post data of these non-standard characters?
Thanks
I figured out how to strip unwanted characters by using this function:
function removeMSWordChars(str) {
var myReplacements = new Array();
var myCode, intReplacement;
myReplacements[8216] = 39;
myReplacements[8217] = 39;
myReplacements[8220] = 34;
myReplacements[8221] = 34;
myReplacements[8212] = 45;
for(c=0; c<str.length; c++) {
var myCode = str.charCodeAt(c);
if(myReplacements[myCode] != undefined) {
intReplacement = myReplacements[myCode];
str = str.substr(0,c) + String.fromCharCode(intReplacement) + str.substr(c+1);
}
}
return str;
}

Function to convert "camel case" type text to text with spaces in between? ie: HelloWorld --> Hello World

Anyone know of a nice efficient function that could convert, for example:
HelloWorld --> Hello World
helloWorld --> Hello World
Hello_World --> Hello World
hello_World --> Hello World
It would be nice to be able to handle all these situations.
Preferably in in VB.Net, or C#.
I don´t know if this is the most efficient way. But this method works fine:
EDIT 1: I have include Char.IsUpper suggestion in the comments
EDIT 2: included another suggestion in the comments: ToCharArray is superfluous because string implements enumerable ops as a char too, i.e. foreach (char character in input)
EDIT 3: I've used StringBuilder, like #Dan commented.
public string CamelCaseToTextWithSpaces(string input)
{
StringBuilder output = new StringBuilder();
input = input.Replace("_", "");
foreach (char character in input)
{
if (char.IsUpper(character))
{
output.Append(' ');
}
if (output.Length == 0)
{
// The first letter must be always UpperCase
output.Append(Char.ToUpper(character));
}
else
{
output.Append(character);
}
}
return output.ToString().Trim();
}
There are some other possibilities you might want to cater for - for instance, you probably don't want to add spaces to abbreviations/acronyms.
I'd recommend using:
Private CamelCaseConverter As Regex = New Regex("(?<char1>[0-9a-z])(?<char2>[A-Z])", RegexOptions.Compiled + RegexOptions.CultureInvariant)
Public Function CamelCaseToWords(CamelCaseString As String) As String
Return CamelCaseConverter.Replace(CamelCaseString, "${char1} ${char2}")
End Function
'Gives:
'CamelCase => Camel Case
'PIN => PIN
What it doesn't do is uppercase the first letter of the first word, but you can look at the other examples for ways of doing that, or maybe someone can come up with a clever RegEx way of doing it.
Sounded fun so I coded it the most important part is the regex take a look at this site for more documentation.
private static string BreakUpCamelCase(string s)
{
MatchCollection MC = Regex.Matches(s, #"[0-9a-z][A-Z]");
int LastMatch = 0;
System.Text.StringBuilder SB = new StringBuilder();
foreach (Match M in MC)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch, M.Index + 1 - LastMatch));
LastMatch = M.Index + 1;
}
if (LastMatch < s.Length)
{
SB.AppendFormat("{0} ", s.Substring(LastMatch));
}
return SB.ToString();
}

remove last two string char!

The following code:
If checkboxList.Items(i).Selected Then
.Fields("DESC1").Value += checkboxList.Items(i).Text + ", "
End If
should produce output such as "A, B, C,(space)", which will then be bound to a dynamically created GridView. I would like to remove the last two-char string, that is ",(space)". How can I do this?
Take a look at String.Join, which may do what you want, without the need to manipulate the final two characters.
I wouldn't add them on in the first place :) try
If checkboxList.Items(i).Selected Then
if .Fields("DESC1").Value Is System.DbNull.Value then
.Fields("DESC1").Value = checkboxList.Items(i).Text
else
.Fields("DESC1").Value += ", " + checkboxList.Items(i).Text
End If
End If
For info, string concatenation is expensive. It looks (from the i and from the results) like you should really be using a StringBuilder; some rough pseudo-code (in C#, but trivial to translate to VB.Net):
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i < checkboxList.Items.Count ; i++) {
if(checkboxList.Items[i].Selected) {
if(sb.Length > 0) sb.Append(", "); // add separator
sb.Append(checkboxList.Items[i].Text); // add text
}
}
someOjb.Fields("DESC1") = sb.ToString(); // use result
You can use .TrimEnd(", ".ToCharArray()) on the string, or you can use SubString:
strLetters.Substring(0, strLetters.Length - 2)
It seems you just want to get "A, B, C" from "A, B, C, ". A bit of simple string manipulation should do the job:
Dim input = "A, B, C, "
Dim result = input.Substring(0, input.LastIndexOf(","))
This is more versatile than simply removing the last two characters, since it looks for the last comma, which is what I believe you are after.
Of course, the fact that you're adding on these two chars in the first place sounds a bit dodgy. I'd need to see more context to show how this can be avoided, however.
use
.Fields("DESC1").Value += checkboxList.Items(i).Text + ", "
. Fields("DESC1").Value = .Fields("DESC1").Value.TrimRight(new []{',',' '});
PS:- sorry if it is not valid vb syntax :)
There is also just "Remove":
string k = "okay";
string s = k.Remove(k.Length - 2, 2);
This will remove all trailing , and/or [space]:
.Fields("DESC1").Value = .Fields("DESC1").Value.TrimRight(", ".ToCharArrray())
var selectedValues = checkboxList.Items
.Where(i => i.Selected)
.Select(i => i.Fields("DESC1").Value);
var result = String.Join(", ", selectedValues);
Does VB have a ternary if operator?
If checkboxList.Items(i).Selected Then
.Fields("DESC1").Value += checkboxList.Items(i).Text + (i == checkboxList.Items.Length-1 ? "" : ", ")
End If

Formatting JSON in ASP.NET HttpResponse

I'm sending back a bunch of image tags via JSON in my .ashx response.
I am not sure how to format this so that the string comes back with real tags. I tried to HtmlEncode and that sort of fixed it but then I ended up with this stupid \u003c crap:
["\u003cimg src=\"http://www.sss.com/image/65.jpg\" alt=\"\"\u003e\u003c/li\u003e","\u003cimg src=\"http://www.xxx.com/image/61.jpg\" alt=\"\"\u003e\u003c/li\u003e"]
What the heck is \u003c ?
here's my code that created the JSON for response to my .ashx:
private void GetProductsJSON(HttpContext context)
{
context.Response.ContentType = "text/plain";
int i = 1;
...do some more stuff
foreach(Product p in products)
{
string imageTag = string.Format(#"<img src=""{0}"" alt=""""></li>", WebUtil.ImageUrl(p.Image, false));
images.Add(imageTag);
i++;
}
string jsonString = images.ToJSON();
context.Response.Write(HttpUtility.HtmlEncode(jsonString));
}
the toJSON is simply using the helper method outlined here:
http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx
\u003c is an escaped less-than character in unicode (Unicode character 0x003C).
The AJAX response is fine. When that string is written to the DOM, it will show up as a normal "<" character.
You are returning JSON array. Once parsed using eval("("+returnValue+")") it is in readily usable condition.
EDIT: This code is from jquery.json.js file:
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
var meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
$.quoteString = function(string)
// Places quotes around a string, inteligently.
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
{
if (escapeable.test(string))
{
return '"' + string.replace(escapeable, function (a)
{
var c = meta[a];
if (typeof c === 'string') {
return c;
}
c = a.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}) + '"';
}
return '"' + string + '"';
};
Hope this gives you some direction to go ahead.
all you need to do is to use javascript eval function to get a pure HTML (XML) markup on the front end.
i.e. in a ajax call to a webservice, this can be the success handler of tha call,
the service returns a complex html element:
...
success: function(msg) {$(divToBeWorkedOn).html(**eval(**msg**)**);alert(eval(msg));},
...

Resources