I am getting data from a web service end point and place it into a list in a for each loop. The service gets it's data from a Wordpress website.
var list = new ItemList
(
(string)data.id.ToString(),
(string)data.name,
(string)subcategory
);
I then print this on the XAML page. The code works fine in that it successfully gets the data from the service and prints it on the page of my windows 8 app.
However in (string)data.name,, which is the name of the items, if the name contains a "&" it shows up in the app as $#038;. Also if a item name contains a "'", apostrophe s, it shows up as ’.
EG. D & G, shows up as D $#038; G
The "&" and "'" show up as these weird symbols.
How do I get rid of these and fix it so that they render correctly in the app.
I'm going to take the risk of giving you a wrong hint, because I guess you're talking about a Windows 8 Store App (XAML), thus you don't have access to every class on .NET, but...
What about decoding HTML entities?
Check this HttpUtility method: HtmlUtility.HtmlDecode.
Check WebUtility.HtmlDecode, which is on System.dll, thus available for Windows 8 Store Apps.
You'll need to add a reference to System.Web on your Visual Studio project.
It looks like the service is returning XML escaped entities. & means a character with a code of (decimal) 38 (which is &). ’ is similar and means a code of 8217 (which is ’).
You can decode these using System.Web.HttpUtility.HtmlDecode(inputString), but that requires a reference to System.Web. If you don't want to or cannot reference that, you can try something like this:
var xml = new XmlDocument();
xml.LoadXml("<x>" + inputString + "</x>");
var output = xml.InnerText;
Given Testing ’stuff" & things, it will return Testing ’stuff" & things.
I'd go with HtmlDecode() if you can, but absolutely try and avoid rolling your own decoder unless you have no other choice.
You can use WebUtility.HtmlDecode Method (String)
Or you can use if you don't want to add additional libraries.
public string Decode(string text)
{
var replacements = new Dictionary<string, char> {
{ "’", ''' },
// ...etc
}
var sb = new StringBuilder( text );
foreach( var c in replacements.Keys ) {
sb.Replace( c.ToString(), replacements[c] );
}
return sb.ToString();
}
Related
Adding triplets to GraphDB
SparqlRemoteEndpoint endpoint = new SparqlRemoteEndpoint(new Uri("http://localhost:7200/sparql"), "http://localhost:7200/");
SparqlResultSet results = endpoint.QueryWithResultSet("PREFIX : <http://www.example.org/> INSERT DATA {:test :test :hhrh }");
why does not it work?
StardogConnector stardog = new StardogConnector("http://localhost:7200", "test", "admin", "posw");
stardog.Begin();
string query = "PREFIX : <http://www.example.org/>SELECT * WHERE {:" + line[0] + " ?k :" + line[1] + "}";
stardog.Query(query);
stardog.Commit();
another way, same problem. Created a DB on a lokalka
Yes, I also came to this conclusion, I use GraphDB for the first time. Well, how can I implement it with a file? I wrote such code.
IGraph g = new Graph();
string sql = "PREFIX : <http://www.example.org/> INSERT DATA {:test :test :hhrh }";
g.LoadFromFile("t.n3");
Object results = g.ExecuteQuery(sql);
here comes such an error
VDS.RDF.Parsing.RdfParseException
HResult = 0x80131500
Message = [InsertKeywordToken at Line 1 Column 36 to Line 1 Column 42] Unexpected Token encountered - expected a BASE / PREFIX directive or a Query Keyword to start a Query
Source = dotNetRDF
Stack trace:
in VDS.RDF.Parsing.SparqlQueryParser.ParseInternal (SparqlQueryParserContext context)
in VDS.RDF.Parsing.SparqlQueryParser.ParseInternal (TextReader input)
in VDS.RDF.Parsing.SparqlQueryParser.ParseFromString (String queryString)
in VDS.RDF.GraphExtensions.ExecuteQuery (IGraph g, String sparqlQuery)
in algorAutoText.Program.Main (String [] args) in C: \ Users \ Denis \ source \ repos \ algorAutoText \ algorAutoText \ Program.cs: line 43
judging by mistake, I supposedly did not add BASE / PREFIX. But he is in the request
Update and delete queries come through the /statements endpoint,
i.e. /repositories/{repository_id}/statements.
You can see the RDF4J server REST API here:
http://docs.rdf4j.org/rest-api/#_the_rdf4j_server_rest_api
When you use the DELETE or INSERT keywords you are doing a SPARQL Update, not a Query. SPARQL separates Query and Update into two separate specifications and most triple stores implement them as two separate endpoints (e.g. for security reasons).
To do an update from dotNetRDF into a triple store you have two options.
You can work directly with the SPARQL update endpoint in which case you will need to check the documentation for your triple store to find out how to create the URL for that - see https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Updating-With-SPARQL#remote-updates for details.
Alternatively if your triple store is one of the ones supported by dotNetRDF (Stardog and Sesame/GraphDB both are), then there are convenience wrappers that make this a bit easier - for more information about this please refer to https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Triple-Store-Integration#update
I am trying to Encode a product SKU on our Product Filter Module.
The problem I am experiencing is that the Detailed Product View uses the following code to retrieve the appropriate product information. The problem arises when an SKU has a forward slash. For Example, BD1115/35 the code below only detects the first part.
var prodCode = Request.QueryString["sku"];
var decodeprodCode = HttpUtility.UrlDecode(prodCode);
It was suggested that I encode the URL. Now I am trying to do this with Mustache which is a templating engine. Look at {{StockCode}} after SKU. This does not work.
<img class='responsive productimage' src='{{ProductImage}}' alt='{{StockDescription}}' />
I had a look at this question: Using Request.QueryString, slash (/) is added to the last querystring when it exists in the first querystring
Update
I have created a new Object in the Backend which is called QueryStringSKU and I am encoding it before it is replaced with Mustache. So the SKU BDF5555/45 will render in the href as BDF5555%2F45.
The problem now comes in when I try to Decode the URL. The querystring is now showing BDF5555&45.
Somehow DotNetNuke is changing this or rewriting this and now it is still ignoring the 45 value which is part of the Stock Keeping Unit (SKU)
I ended up using this code:
string RawurlFromRequest = Request.RawUrl;
var cleanSKU = RawurlFromRequest.Split(new[] { "sku/" }, StringSplitOptions.None)[1];
var decodeprodCode = cleanSKU.Split(new[] { "&" }, StringSplitOptions.None)[0];
I'am having an issue with encoding as I retrieve informations such as customers names or orders info through webservice API. I'am using C# to manipulate the API, here is an example of the encoding problem :
1) Here is the value as seen in the MYSQL database (input source) : TestAcctééa --> We can see that the accent characters "éé" are well interpreted.
2) Here is the value as seen when I retrieve the information through the api : TestAcct????a --> We can see there is a problem, it does this with all the special characters (é, ç, ê,...). I cannot display the string correctly in the console and as I insert it in the target database (MSSQL), it keeps the questions marks in place of the special characters.
Here is my example code to get this particular information with the api :
filters filters = new filters();
WebserviceApi service = new WebserviceApi();
string login = service.login("******", "********");
string test = null;
List<customerCustomerEntity> customers = service.customerCustomerList(login, filters).ToList();
foreach (var customer in customers)
{
if(customer.email == "test#gmail.com")
{
test = customer.firstname;
}
}
MessageBox.Show(test);
I already tried different solutions from forums such as changing the encoding in C# or convert it but none has worked...
Btw, the encoding of the source database is UTF-8 Unicode (utf8).
Thank for your help.
I am using C# and ASP.NET for this.
We receive a lot of "strange" requests on our IIS 6.0 servers and I want to log and catalog these by domain.
Eg. we get some strange requests like these:
http://www.poker.winner4ever.example.com/
http://www.hotgirls.example.com/
http://santaclaus.example.com/
http://m.example.com/
http://wap.example.com/
http://iphone.example.com/
the latter three are kinda obvious, but I would like to sort them all into one as "example.com" IS hosted on our servers. The rest isn't, sorry :-)
So I am looking for some good ideas for how to retrieve example.com from the above. Secondly I would like to match the m., wap., iphone etc into a group, but that's probably just a quick lookup in a list of mobile shortcuts.I could handcode this list for a start.
But is regexp the answer here or is pure string manipulation the easiest way? I was thinking of "splitting" the URL string by "." and the look for item[0] and item[1]...
Any ideas?
You can use the following nuget Nager.PublicSuffix package. It uses the same data source that browser vendors use.
nuget
PM> Install-Package Nager.PublicSuffix
Example
var domainParser = new DomainParser(new WebTldRuleProvider());
var domainInfo = domainParser.Parse("sub.test.co.uk");
//domainInfo.Domain = "test";
//domainInfo.Hostname = "sub.test.co.uk";
//domainInfo.RegistrableDomain = "test.co.uk";
//domainInfo.SubDomain = "sub";
//domainInfo.TLD = "co.uk";
The following code uses the Uri class to obtain the host name, and then obtains the second level host (examplecompany.com) from Uri.Host by splitting the host name on periods.
var uri = new Uri("http://www.poker.winner4ever.examplecompany.com/");
var splitHostName = uri.Host.Split('.');
if (splitHostName.Length >= 2)
{
var secondLevelHostName = splitHostName[splitHostName.Length - 2] + "." +
splitHostName[splitHostName.Length - 1];
}
There may be some examples where this returns something other than what is desired, but country codes are the only ones that are 2 characters, and they may or may not have a short second level (2 or 3 characters) typically used. Therefore, this will give you what you want in most cases:
string GetRootDomain(string host)
{
string[] domains = host.Split('.');
if (domains.Length >= 3)
{
int c = domains.Length;
// handle international country code TLDs
// www.amazon.co.uk => amazon.co.uk
if (domains[c - 1].Length < 3 && domains[c - 2].Length <= 3)
return string.Join(".", domains, c - 3, 3);
else
return string.Join(".", domains, c - 2, 2);
}
else
return host;
}
This is not possible without a up-to-date database of different domain levels.
Consider:
s1.moh.gov.cn
moh.gov.cn
s1.google.com
google.com
Then at which level you want to get the domain? It's completely depends of the TLD, SLD, ccTLD... because ccTLD in under control of countries they may define very special SLD which is unknown to you.
I've written a library for use in .NET 2+ to help pick out the domain components of a URL.
More details are on github but one benefit over previous options is that it can download the latest data from http://publicsuffix.org automatically (once per month) so the output from the library should be more-or-less on a par with the output used by web browsers to establish domain security boundaries (i.e. pretty good).
It's not perfect yet but suits my needs and shouldn't take much work to adapt to other use cases so please fork and send a pull request if you want.
Use a regular expression:
^https?://([\w./]+[^.])?\.?(\w+\.(com)|(co.uk)|(com.au))$
This will match any URL ending with a TLD in which you are interested. Extend the list for as many as you want. Further, the capturing groups will contain the subdomain, hostname and TLD respectively.
uri.Host.ToLower().Replace("www.","").Substring(uri.Host.ToLower().Replace("www.","").IndexOf('.'))
returns ".com" for
Uri uri = new Uri("http://stackoverflow.com/questions/4643227/top-level-domain-from-url-in-c");
returns ".co.jp" for
Uri uri = new Uri("http://stackoverflow.co.jp");
returns ".s1.moh.gov.cn" for
Uri uri = new Uri("http://stackoverflow.s1.moh.gov.cn");
etc.
In JavaScript:
encodeURIComponent("©√") == "%C2%A9%E2%88%9A"
Is there an equivalent for C# applications? For escaping HTML characters I used:
txtOut.Text = Regex.Replace(txtIn.Text, #"[\u0080-\uFFFF]",
m => #"&#" + ((int)m.Value[0]).ToString() + ";");
But I'm not sure how to convert the match to the correct hexadecimal format that JS uses. For example this code:
txtOut.Text = Regex.Replace(txtIn.Text, #"[\u0080-\uFFFF]",
m => #"%" + String.Format("{0:x}", ((int)m.Value[0])));
Returns "%a9%221a" for "©√" instead of "%C2%A9%E2%88%9A". It looks like I need to split the string up into bytes or something.
Edit: This is for a windows app, the only items available in System.Web are: AspNetHostingPermission, AspNetHostingPermissionAttribute, and AspNetHostingPermissionLevel.
Uri.EscapeDataString or HttpUtility.UrlEncode is the correct way to escape a string meant to be part of a URL.
Take for example the string "Stack Overflow":
HttpUtility.UrlEncode("Stack Overflow") --> "Stack+Overflow"
Uri.EscapeUriString("Stack Overflow") --> "Stack%20Overflow"
Uri.EscapeDataString("Stack + Overflow") --> Also encodes "+" to "%2b" ---->Stack%20%2B%20%20Overflow
Only the last is correct when used as an actual part of the URL (as opposed to the value of one of the query string parameters)
HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode
You can add a reference to the System.Web assembly if it's not available in your project
I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this
c# CODE:
string a = "!##$%^&*()_+ some text here али мамедов баку";
a = System.Web.HttpUtility.UrlEncode(a);
a = a.Replace("+", "%20");
the result is:
!%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83
After you decode It with Javascript's decodeURLComponent();
you will get this:
!##$%^&*()_+ some text here али мамедов баку
Thank You for attention
System.Uri.EscapeUriString() didn't seem to do anything, but System.Uri.EscapeDataString() worked for me.
Try Server.UrlEncode(), or System.Web.HttpUtility.UrlEncode() for instances when you don't have access to the Server object. You can also use System.Uri.EscapeUriString() to avoid adding a reference to the System.Web assembly.
For a Windows Store App, you won't have HttpUtility. Instead, you have:
For an URI, before the '?':
System.Uri.EscapeUriString("example.com/Stack Overflow++?")
-> "example.com/Stack%20Overflow++?"
For an URI query name or value, after the '?':
System.Uri.EscapeDataString("Stack Overflow++")
-> "Stack%20Overflow%2B%2B"
For a x-www-form-urlencoded query name or value, in a POST content:
System.Net.WebUtility.UrlEncode("Stack Overflow++")
-> "Stack+Overflow%2B%2B"
You can use the Server object in the System.Web namespace
Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.
Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.