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.
Related
I am developing an internal application which sends email to the users with the link to the training dcouments.
These documnets are placed in internal share drive, few of these documents have empty space in their names and thats causing the problem.
The path looks like \\Users\shared\Training\Database\Oracle\Docs\Oracle Database Admin.docx and i tried to replace empty space with %20 but still it doesn't work.. In the email link the path is trimmed to \\Users\shared\Training\Database\Oracle\Docs\Oracle
Public string GetMediaPath(int itemCode)
{
string path = _dbContext.TraningMedias.Where( s => s.ItemCode == itemCode).Select(a => a.Path).FirstOrDefault().ToString();
path.replace(" ", "%20");
return path;
}
I dont understand why the replace function is not working in this case.
Strings are immutable, and Replace returns a string, so try this:
path = path.Replace(" ", "%20");
To preserve the spaces in your link text, use an opening and closing chevron
Public string GetMediaPath(int itemCode)
{
string path = "<"+ _dbContext.TraningMedias.Where( s => s.ItemCode == itemCode).Select(a => a.Path).FirstOrDefault().ToString() + ">";
return path;
}
Try doing this:
The below code will remove all invalid filename characters from the path.
path =string.Concat(path.Split(Path.GetInvalidFileNameChars()));
Dont forget to include System.IO namespace.
Thanks
You can try url encode adn get rid off spaces and others speacial characters.
path= HttpUtility.UrlDecode(path);
Just convert the raw file path string to a proper URI, like this:
string fileUrl = new System.Uri("c:\\foo\\my document.docx").AbsoluteUri
which will give you this string:
"file:///c:/foo/my%20document.docx"
Look this
In your case:
path = Uri.EscapeUriString(path);
I'm using PushSharp to handle push notifications for iOS.
Everything went well until I realized the way I'm handling the push isn't too powerful:
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = device.DeviceIdentifier,
Payload = JObject.Parse("{\"aps\":{\"alert\" : {\"title\" : \"" + title
+ "\", \"body\" : \"" + body + "\"}, \"badge\":" + badgeCount + "}, " +
"\"entity_id\" : \"" + entityId + "\", \"category_id\" : \"" + categoryId + "\", \"sub_id\" : \"" + subId
+ "\"}")
});
Edit / Update One of the parameters I am trying is \t\ud83d\uddbc️\ (basically I wanted to pass in the unicode character of the picture frame emoji, so it can be rendered in the APNS alert). It is breaking currently.
I am sending that in C# like this: #"\t\ud83d\uddbc️\"
So as you can see, I'm rendering out the JSON Payload and this framework takes in a JObject. The problem, as I immediately assumed during my code review, is that if any of those parameters above (title, body, etc) end up being strings such as { or " or { etc that it will "break" the JSON because JObject can't parse that as valid JSON.
What do you think I should do in this case? Do I have to encode it and I suppose the only drawback would be I have backslashes or something in the encoding? Any recommendations to permit the user input (title and body can be free form text so anything is possible).
Thank you in advance for any advice!
EDIT
Thank you again Zero for your help.
var escapedString = JsonConvert.ToString(normalString);
saved the day. It's important to note that if you are using this, then escapedString should not be wrapped in ""'s since it will already be escaped (as he mentioned below).
As long as your variables are quoted (inside ") there's no need to escape braces ({ and })
As for breaking the quote (having ") inside variables, you could do something like this:
//Escapes quotes
param = param.Replace(#"""", #"\""");
You also need to escape the escape char itself \
//Escapes backslash
param = param.Replace(#"\", #"\\");
Also, here are all valid escapes.
If you're using Newtonsoft.Json they have a method to do this for you.
Example usage below or take a look here. Be aware this will add quotes to the string for you.
//Or use the return value inline with interpolation "$" or concatenation "+"
var escapedString = JsonConvert.ToString(normalString);
I'm trying to get the full path of a string as follow:
ksh /u01/Utilities/SSL_Certificates/TestCert_20170724.sh
but I'm having an issue and I'm getting
/u01/Utilities/SSL_Certificates/Tes
that's because is getting the 4 characters from ksh
how can I get the count starting from 0 to the first index of "/"
What I have is this:
string SSL_configuration_Path = ShellCommand.Substring(ShellCommand.IndexOf("/"), ShellCommand.LastIndexOf("/"));
Second parameter is how many characters.
Not which character is the last.
string SSL_configuration_Path = ShellCommand.Substring(
ShellCommand.IndexOf("/"),
ShellCommand.LastIndexOf("/") - ShellCommand.IndexOf("/"));
Not that this is a good solution, but it should explain what you're doing wrong and why it didn't work.
Try using Parh class which is specially designed for working with directories' and files' names:
string ShellCommand = "ksh /u01/Utilities/SSL_Certificates/TestCert_20170724.sh";
string path = Path.GetDirectoryName(ShellCommand
.Substring(line.IndexOfAny(new char[] {
Path.AltDirectorySeparatorChar,
Path.DirectorySeparatorChar })));
Console.WriteLine(path);
Outcome:
\u01\Utilities\SSL_Certificates
please, notice that you can use either / or \ as direcory separators and get the final result normalized (i.e. with Path.DirectorySeparatorChar seperator)
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 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;
}