The spaces inside the URL - c#

I have created the yahoo weather API app using ASP.Net MVC 3 and when I tried to insert the postcode to the text field to find the correct xml, I wanted to leave gap for the standard UK postcode. Can you please help me to do that. The following code's model.PostCode represents the PostCode variable which has declared as string in model. This code is in the controller file.
private Boolean LookupWeather(ref RssModels model)
{
string WoeidUrl = "http://where.yahooapis.com/v1/places.q('" +
model.PostCode +
"')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--";
XDocument getWoeid = XDocument.Load(WoeidUrl);
try
{
model.Woied = (int)(from place in getWoeid.Descendants("place")
select place.Element("woeid")).FirstOrDefault();
return true;
}
catch
{
return false;
}
If you can please help me to get the URL like follows.
http://where.yahooapis.com/v1/places.q('mk10%202hn')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--
Thank you in advance.

Use UrlEncode
string WoeidUrl = "http://where.yahooapis.com/v1/places.q('"
+ UrlEncode(postCode)
+ "')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--";

All the browser is doing for that is replacing the space with %20, you can replicate this just by using Replace, try:
string postCode = model.PostCode.Replace(" ", "%20");
Then use it in your code above like so:
string WoeidUrl = "http://where.yahooapis.com/v1/places.q('"
+ postCode
+ "')?appid=EzZDnOXV34EzJpQ8mX8mc62cYk1Gu21DzUhsLr.4nQ2qz.xffZah.RNq8lObxA--";

Related

C# Print a specific string fom a website using HtmlAgilityPack

I need to get some text from a website we are using to get our data from. I finally found how, using HtmlAgilityPack and finding the Xpath I'm able to print out some text from the website.
But when I try to print the date and kind, which is coded like this:
<span class="span-line-break">zaterdag 05 december 2020</span> //Date
<span class="afvaldescr">Papier en karton</span> //Kind
I can't reach these two strings using my current code:
public string Postalcode = "6093DK";
public string Number = "2";
public string Add = "";
string url = "https://mijnafvalwijzer.nl/nl/" + Postalcode + "/" + Number + "/" + Add;
var web = new HtmlAgilityPack.HtmlWeb();
HtmlDocument doc = web.Load(url);
string when = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]/div/table[1]/tbody/tr/td[1]/a/p/span[1]")[0].InnerText;
string what = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]/div/table[1]/tbody/tr/td[1]/a/p/span[2]")[0].InnerText;
textBox1.Text = when;
textBox2.Text = what;
I figured that because the text is in a class I can not reach it.
Can someone help me find a more specific route to these strings?
The website is a Dutch garbadge calendar, don't mind it.
Browser inserts tbody for table element although it is not present in html. So here I just removed tbody from your XPath. In Chrome you can use network tab for viewing original response
string when = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]/div/table[1]/tr/td[1]/a/p/span[1]")[0].InnerText;
string what = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]/div/table[1]/tr/td[1]/a/p/span[2]")[0].InnerText;
You can also use shortened version of XPath using "//" and class selectors
string when = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]//table[1]//span[#class=\"span-line-break\"]")[0].InnerText;
string what = doc.DocumentNode.SelectNodes("//*[#id=\"december-2020\"]//table[1]//span[#class=\"afvaldescr\"]")[0].InnerText;

Single Quote Escape Character Formatting for JavaScript

I have a question that I feel will be simple to answer: I have the code
function ApplicantNameMatchedInitialPayment() {
var applicantName = '<%= ViewData["ApplicantName"] %>';
var fullName = applicantName.split(' ');
if (fullName.length == 2)
{
var firstName = fullName[0].toLowerCase();
var lastName = fullName[1].toLowerCase();
var nameOnCard = $("#name-on-card").val().toLowerCase();
if(nameOnCard.includes(firstName) & (nameOnCard.includes(lastName)))
{
return true;
}
}
return false;
}
I am trying to handle a case where my user enters their name with an apostrophe. When the ViewData Object is filled during live execution, the customer's name will show up in the 'applicantName' variable. The problem is that if I enter a name like "De'Leon", a JS error is thrown in the console because of an incorrect escape sequence.. and the string will not be read correctly. I want to take any string that is passed in from my C# Viewdata object and handle the apostrophes dynamically so that no errors are thrown and so that my javascript understands that everything should just be one string. A little help with the string formatting and escape character?
If you want to just escape apostrophes in JavaScript you could try to simply replace them with \’:
s = s.replace("'", "\'");
It won’t affect your further work with this string so if you write it to the console it will output a result without backslash:
var s = "De'Leon";
s = s.replace("'", "\'");
console.log(s); // > De'Leon
If you're using .NET version 4 or later, you can use HttpUtility.JavaScriptStringEncode.

How to get rid of unwanted spaces after using ToString() in C#?

This might be a problem with Session and not ToString(), I'm not sure.
I have two .aspx pages and I want to pass an IP address from a datatable from one page to the other. When I do this, spaces get added that I don't want. The simple version of the code is this:
first .aspx page
int num = DropDownList1.SelectedIndex;
DataView tempDV = SqlDataSource2.Select(DataSourceSelectArguments.Empty) as DataView;
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2];
Response.Redirect("test.aspx");
test.aspx page
string ipCamAdd = Session["camera"].ToString();
TextBox1.Text = "http://" + ipCamAdd + "/jpg/image.jpg?resolution=320x240";
what I want to print is
http ://ipadd/jpg/image.jpg?resolution=320x240
but what prints out is
http//ipaddress /jpg/image.jpg?resolution=320x240
how can I fix this?
Also, I asked this question hoping someone could tell me why this is happening as well. Sorry for the mistake.
Try this:
string ipCamAdd = Session["camera"].Trim().ToString();
For the valid concern, Session["camera"] could be null, add function such as the following to your code
static string ToSafeString(string theVal)
{
string theAns;
theAns = (theVal==null ? "" : theVal);
return theAns;
}
Then use:
string ipCamAdd = Session["camera"].ToSafeString().Trim();
You can use string.Replace if you just want to get rid of the spaces:
TextBox1.Text = "http://" + (ipCamAdd ?? "").Replace(" ", "") + "/jpg/image.jpg?resolution=320x240";
Trim the result before setting to session.
Session["camera"] = tempDV.Table.Rows[num].ItemArray[2].Trim();
Seems In SQL your data type is char(*) if you convert the data type to varchar and re enter data, you wont get any additional spaces

How to make filenames web safe using c#

This is not about encoding URLs its more to do with a problem I noticed where you can have a valid filename on IIS sucha as "test & test.jpg" but this cannot be downloaded due to the & causing an error. There are other characters that do this also that are valid in windows but not for web.
My quick solution is to change the filename before saving using a regex below...
public static string MakeFileNameWebSafe(string fileNameIn)
{
string pattern = #"[^A-Za-z0-9. ]";
string safeFilename = System.Text.RegularExpressions.Regex.Replace(fileNameIn, pattern, string.Empty);
if (safeFilename.StartsWith(".")) safeFilename = "noname" + safeFilename;
return safeFilename;
}
but I was wondering if there were any better built in ways of doing this.
Built-in I don't know about.
What you can do is, like you say, scan the original filename and generate a Web-safe version of it.
For such Web-safe versions, you can make it appear like slugs in blogs and blog categories (these are search engine-optimized):
Only lowercase characters
Numbers are allowed
Dashes are allowed
Spaces are replaced by dashes
Nothing else is allowed
Possibly you could replace "&" by "-and-"
So "test & test.jpg" would translate to "test-and-test.jpg".
Just looking back at this question since its fairly popular. Just though I would post my current solution up here with various overloads for anyone who wants it..
public static string MakeSafeFilename(string filename, string spaceReplace)
{
return MakeSafeFilename(filename, spaceReplace, false, false);
}
public static string MakeSafeUrlSegment(string text)
{
return MakeSafeUrlSegment(text, "-");
}
public static string MakeSafeUrlSegment(string text, string spaceReplace)
{
return MakeSafeFilename(text, spaceReplace, false, true);
}
public static string MakeSafeFilename(string filename, string spaceReplace, bool htmlDecode, bool forUrlSegment)
{
if (htmlDecode)
filename = HttpUtility.HtmlDecode(filename);
string pattern = forUrlSegment ? #"[^A-Za-z0-9_\- ]" : #"[^A-Za-z0-9._\- ]";
string safeFilename = Regex.Replace(filename, pattern, string.Empty);
safeFilename = safeFilename.Replace(" ", spaceReplace);
return safeFilename;
}
I think you are referring to the "A potentially dangerous Request.Path value was detected from the client (%)" error which Asp.Net throws for paths which include characters which might indicate cross site scripting attempts:
there is a good article on how to work around this:
http://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx
Here's the one I use:
public static string MakeFileNameWebSafe(string path, string replace, string other)
{
var folder = System.IO.Path.GetDirectoryName(path);
var name = System.IO.Path.GetFileNameWithoutExtension(path);
var ext = System.IO.Path.GetExtension(path);
if (name == null) return path;
var allowed = #"a-zA-Z0-9" + replace + (other ?? string.Empty);
name = System.Text.RegularExpressions.Regex.Replace(name.Trim(), #"[^" + allowed + "]", replace);
name = System.Text.RegularExpressions.Regex.Replace(name, #"[" + replace + "]+", replace);
if (name.EndsWith(replace)) name = name.Substring(0, name.Length - 1);
return folder + name + ext;
}
If you are not concerned to keep the original name perhaps you could just replace the name with a guid?

Problem with Index of in Substring array

ProfilePageList is the string array with each string containing pageID, PageName and PageContent separated by group of characters (#$%). This is a ASP.NET application using C#
foreach (string item in ProfilePageList)
{
string PageContent = ""; string PageName = ""; string PageID = "";
*** > This part is wrong. Help me here ***
PageID = item.Substring(0, item.IndexOf('#$%') + 2);
PageContent = item.Substring(item.IndexOf('#$%') + 1);
PageName = item.Substring(0, item.IndexOf('#$%'));
callsomefunction(PageID , PageName, PageContent);
}
Input string is Helloo#$%<p>How are you??</p>#$%74396
I dont understand how to use this substring. Can someone help me Please!! Thanks a lot in advance..
Have a look at these:
http://msdn.microsoft.com/en-us/library/system.string.substring(v=vs.71).aspx
and
http://csharp.net-informations.com/string/csharp-string-substring.htm
But I think what you're trying to do is something like this:
string[] substrings = inputString.Split("#$%");
Anyway, the data structure you are using -- cramming data into strings -- is rather convoluted. Why not just use proper objects?

Categories