I came across a very weird issue where in my querystirng had "++" as part of the text. but when i assign the query stirng value to a string ++ will become two spaces. How do i get exactly what is being passed as querystring?
I observed that the querystirng collection had "++" but when I do Request.QueryString["search"].ToString() "++" gone, I checked in Immediate window.
I use C# 2.0
URL: /default.aspx?search=test++
string t = Request.QueryString["search"].ToString();
You should use UrlEncode and UrlDecode
Those methods should be used any time you're inserting user inputted data into the query string.
'+' is reserved in query strings.
Within a query component, the
characters ";", "/", "?", ":", "#",
"&", "=", "+", ",", and "$" are
reserved.
Try using UrlEncode to encode your query strings.
A plus sign in a query string translates to a space. If you want an actual plus sign rather than a space, use %2B instead.
/default.aspx?search=test%2B%2B
If you're doing this in code, then you should be using UrlEncode to encode this portion of the query string.
I don't know that there's a way to get the exact text passed into the query. The HTTP standards basically say that a + is equivalent to a space character, so if you want to preserve the + you should encode the query string, as Chuck said.
The only solution I found was in this post HERE:
private string GetQueryStringValueFromRawUrl(string queryStringKey)
{
var currentUri = new Uri(HttpContext.Request.Url.Scheme + "://" +
HttpContext.Request.Url.Authority +
HttpContext.Request.RawUrl);
var queryStringCollection = HttpUtility.ParseQueryString((currentUri).Query);
return queryStringCollection.Get(queryStringKey);
}
Working on a ASP.Net 2.0 soluton, I had to do the following:
private string GetParameterFromRawUrl(string parameter)
{
var rawUrl = Request.RawUrl;
int indexOfParam = rawUrl.IndexOf(parameter);
int indexOfNextParam = rawUrl.IndexOf('&', indexOfParam);
string result;
if (indexOfNextParam < 1)
{
result = rawUrl.Substring(indexOfParam);
}
else
{
result = rawUrl.Substring(indexOfParam, (indexOfNextParam-indexOfParam));
}
return result;
}
Related
I have some Json files containing special character like this :
{
"someProperties" : "someValues",
"$ROOT_QUERY.searchResults({\"path\":\"/some/url\"}).features":
{
"propertyOtherA": "valueA",
"propertyOtherB": "null",
},
"$ROOT_QUERY.searchResults({\"path\":\"/some/url\"}).otherText":
{
"propertyOtherA": "valueA",
"propertyOtherB": "null",
}
}
How can I set the token path to get it ?
When I try the standard path, I get a Unexpected character exception
string path = "$ROOT_QUERY.searchResults({\\\"path\\\":\\\"" + request.RequestUri.PathAndQuery + "\\\"})";
var token = jObject.SelectToken("$." + path + ".features");
I also tried to replace string in Json, but the string.Contains method is not returning true, whereas it works fine in notepad.
I also tried simple Regex, but i've not succed to make it work.
My last idea is atomic Regex, but before entering to this hell, I'm trying to ask you if I can any chance to get it with a simplier way.
Thank you
You need to escape path using '[]' - note that .features should also be included:
var path = "['$ROOT_QUERY.searchResults({\"path\":\"" + request.RequestUri.PathAndQuery + "\"}).features']";
var token = jObject.SelectToken("$." + path);
Console.WriteLine(token);
You need to escape this entire path, because you have multiple "reserved" characters there: $, ., () (see this non-oficial documentation). See other escaping examples here.
demo.
I have a String I want to get the index of the "id:" i.e the id along with the double quotes.
How I am supposed to do so inside C# string.IndexOf function?
This will get the index of the string you want:
var idx = input.IndexOf("\"id:\"");
if you wanted to pull it out you'd do something like this maybe:
var idx = input.IndexOf("\"id:\"");
var val = input.Substring(idx, len);
where len is either a statically known length or also calculated by another IndexOf statement.
Honestly, this could also be done with a Regex, and if an example were available a Regex may be the right approach because you're presumably trying to get the actual value here and it's presumably JSON you're reading.
" is an escape sequence
If you want to use a double quotation mark in your string, you should use \" instead.
For example;
int index = yourstring.IndexOf("\"id:\"");
Remember, String.IndexOf method gets zero-based index of the first occurrence of the your string.
This is a simple approach: If you know double quote is before the Id then take index of id - 1?
string myString = #"String with ""id:"" in it";
var indexOfId = myString.IndexOf("id:") - 1;
Console.WriteLine(#"Index of ""id:"" is {0}", indexOfId);
Reading between the lines, if this is a JSON string, and you have .NET 4 or higher available, you can ask .NET to deserialize the string for you rather than parsing by hand: see this answer.
Alternatively you might consider Json.NET if you're working very heavily with JSON.
Otherwise, as others note, you need to escape the quotes, so for example:
text.IndexOf("\"id:\"")
text.IndexOf(#"""id:""")
or for overengineered legiblity:
string Quoted(string text)
{
return "\"" + text + "\""; // generates unnecessary garbage
}
text.IndexOf(Quoted("id:"))
So what I am trying to do is as follows :
example of a string is A4PC
I am trying to replace for example any occurance of "A" with "[A4]" so I would get and similar any occurance of "4" with "[A4]"
"[A4][A4]PC"
I tried doing a normal Replace on the string but found out I got
"[A[A4]]PC"
string badWordAllVariants =
restriction.Value.Replace("A", "[A4]").Replace("4", "[A4]")
since I have two A's in a row causing an issue.
So I was thinking it would be better rather than the replace on the string I need to do it on a character per character basis and then build up a string again.
Is there anyway in Linq or so to do something like this ?
You don't need any LINQ here - String.Replace works just fine:
string input = "AAPC";
string result = input.Replace("A", "[A4]"); // "[A4][A4]PC"
UPDATE: For your updated requirements I suggest to use regular expression replace
string input = "A4PC";
var result = Regex.Replace(input, "A|4", "[A4]"); // "[A4][A4]PC"
This works well for me:
string x = "AAPC";
string replace = x.Replace("A", "[A4]");
EDIT:
Based on the updated question, the issue is the second replacement. In order to replace multiple strings you will want to do this sequentially:
var original = "AAPC";
// add arbitrary room to allow for more new characters
StringBuilder resultString = new StringBuilder(original.Length + 10);
foreach (char currentChar in original.ToCharArray())
{
if (currentChar == 'A') resultString.Append("[A4]");
else if (currentChar == '4') resultString.Append("[A4]");
else resultString.Append(currentChar);
}
string result = resultString.ToString();
You can run this routine with any replacements you want to make (in this case the letters 'A' and '4' and it should work. If you would want to replace strings the code would be similar in structure but you would need to "look ahead" and probably use a for loop. Hopefully this helps!
By the way - you want to use a string builder here and not strings because strings are static which means space gets allocated every time you loop. (Not good!)
I think this should do the trick
string str = "AA4PC";
string result = Regex.Replace(str, #"(?<Before>[^A4]?)(?<Value>A|4)(?<After>[^A4]?)", (m) =>
{
string before = m.Groups["Before"].Value;
string after = m.Groups["After"].Value;
string value = m.Groups["Value"].Value;
if (before != "[" || after != "]")
{
return "[A4]";
}
return m.ToString();
});
It is going to replace A and 4 that hasn't been replaced yet for [A4].
This is what I tried:
string myURL= "http://mysite.com/articles/healthrelated";
String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);
I need to fetch "healthrelated" ie the text after the last slash in the URL. Now the problem is that my URL can also be like :
"http://mysite.com/articles/healthrelated/"
ie "a Slash" at the end of that text too. Now the last slash becomes the one AFTER "healthrelated" and so the result I get using
String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);
is empty string..
what should my code be like so I always get that text "healthrelated" no matter if there's a slash in the end or not. I just need to fetch that text somehow.
Try this.
var lastSegment = url
.Split(new string[]{"/"}, StringSplitOptions.RemoveEmptyEntries)
.ToList()
.Last();
Why don't you use Uri class of .NET and use segments property:
http://msdn.microsoft.com/en-us/library/system.uri.segments.aspx
What you can do in this situation is either using REGEX (which I'm not an expert on, but I'm shure other ppl here are ;) ) or a simple:
string[] urlParts = myURL.Split('/');
and take the last string in this array.
I feel kind of dumb posting this when this seems kind of simple and there are tons of questions on strings/characters/regex, but I couldn't find quite what I needed (except in another language: Remove All Text After Certain Point).
I've got the following code:
[Test]
public void stringManipulation()
{
String filename = "testpage.aspx";
String currentFullUrl = "http://localhost:2000/somefolder/myrep/test.aspx?q=qvalue";
String fullUrlWithoutQueryString = currentFullUrl.Replace("?.*", "");
String urlWithoutPageName = fullUrlWithoutQueryString.Remove(fullUrlWithoutQueryString.Length - filename.Length);
String expected = "http://localhost:2000/somefolder/myrep/";
String actual = urlWithoutPageName;
Assert.AreEqual(expected, actual);
}
I tried the solution in the question above (hoping the syntax would be the same!) but nope. I want to first remove the queryString which could be any variable length, then remove the page name, which again could be any length.
How can I get the remove the query string from the full URL such that this test passes?
For string manipulation, if you just want to kill everything after the ?, you can do this
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.IndexOf("?");
if (index >= 0)
input = input.Substring(0, index);
Edit: If everything after the last slash, do something like
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.LastIndexOf("/");
if (index >= 0)
input = input.Substring(0, index); // or index + 1 to keep slash
Alternately, since you're working with a URL, you can do something with it like this code
System.Uri uri = new Uri("http://www.somesite.com/what/test.aspx?hello=1");
string fixedUri = uri.AbsoluteUri.Replace(uri.Query, string.Empty);
To remove everything before the first /
input = input.Substring(input.IndexOf("/"));
To remove everything after the first /
input = input.Substring(0, input.IndexOf("/") + 1);
To remove everything before the last /
input = input.Substring(input.LastIndexOf("/"));
To remove everything after the last /
input = input.Substring(0, input.LastIndexOf("/") + 1);
An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:
To remove everything after the first /
input = input.Remove(input.IndexOf("/") + 1);
To remove everything after the last /
input = input.Remove(input.LastIndexOf("/") + 1);
Here's another simple solution. The following code will return everything before the '|' character:
if (path.Contains('|'))
path = path.Split('|')[0];
In fact, you could have as many separators as you want, but assuming you only have one separation character, here is how you would get everything after the '|':
if (path.Contains('|'))
path = path.Split('|')[1];
(All I changed in the second piece of code was the index of the array.)
The Uri class is generally your best bet for manipulating Urls.
To remove everything before a specific char, use below.
string1 = string1.Substring(string1.IndexOf('$') + 1);
What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!
But for a URL, I would use the built in .NET class to take of that.
Request.QueryString helps you to get the parameters and values included within the URL
example
string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();
so the customername variable should be equal to dave
regards
I second Hightechrider: there is a specialized Url class already built for you.
I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.
you can use .NET's built in method to remove the QueryString.
i.e., Request.QueryString.Remove["whatever"];
here whatever in the [ ] is name of the querystring which you want to
remove.
Try this...
I hope this will help.
You can use this extension method to remove query parameters (everything after the ?) in a string
public static string RemoveQueryParameters(this string str)
{
int index = str.IndexOf("?");
return index >= 0 ? str.Substring(0, index) : str;
}