Haris
Haris

Reputation: 721

How to escape &?

I am trying to run following query through Saleforce's REST client in my C# application,

Select Id, Name, Family FROM Product2 Where Name IN ('Connectivity - HMS','Database & Application Services', ....)

but getting following error:

('Connectivity - HMS','Database 
                              ^

ERROR at Row:1:Column:83 line 1:83 mismatched character '< EOF >' expecting '''

It works fine if I remove names with & in them.

I am using ForceClient to run the query:

var client = new ForceClient(_instanceUrl, _accessToken, _apiVersion);
Task<QueryResult<dynamic>> queryResult = client.QueryAsync<dynamic>(query);
queryResult.Wait();

I have tried many different things to replace & like Regex.Replace, &amp;, \\& but nothing worked.

The same query is working perfectly in Developer Console.

Upvotes: 0

Views: 876

Answers (1)

JayV
JayV

Reputation: 3271

In order to send the & character over a HTTP link to a server as part of the parameter value eg: 'Database & Application Services' it will need to be encoded.

In this case, as the call to the server is via a REST web service and REST services use the URL and the query string you should encode the query string to make sure all non-control characters that are part of the parameters are properly encoded.

Use one of the three methods shown below depending on your preferences or circumstances:

System.Uri.EscapeDataString
System.Web.HttpUtility.HtmlEncode
System.Web.Mvc.Url.Encode

If you are on the server side needing to decode what people have sent, then use:

Systen.Uri.UnescapeDataString
System.Web.HttpUtility.HtmlDecode

Finally, if you not inside of a Web based project, there is this alternative:

System.Net.WebUtility.UrlEncode
System.Net.WebUtility.UrlDecode

Upvotes: 1

Related Questions