URL Encoding and Decoding - c#

I want to pass URL and my code is:
MyUrl = "http://www.abc.co.in/Download.aspx?period=" + Server.UrlEncode
(DateTime.Now.ToString("dd-MMM-yyyy")) + "&ProductName="
+ Server.UrlEncode(productName) + "";
mail.Body += "Demo Download";
But still I'm getting output like:
http://www.abc.co.in/Download.aspx?period=12-Apr-2013&ProductName=Otja
So what is wrong with my code and how to decode it on download.aspx?

Use HttpUtility.UrlEncode from System.Web namespace.
HttpUtility.UrlEncode Method : MSDN Link

You have given a specific format for datetime which (dd-MMM-yy), there is nothing in this string which should be encoded by UrlEncode function.
What i am trying to say can be explained by trying the code below
Response.Redirect("~/Test.aspx" + Server.UrlEncode(DateTime.Now.ToString("dd:MMM:yyyy")));

Related

How to use UTF-16 Encoding in C# winform app

I am trying to use the Google translator for some sentence translation(English to Urdu also not working with Arabic) but I am stuck with a problem.
when i click button it returns some symbols.
i used this answer link
getting the translated language using google translator in winform apps
But it's not working as i require. I think the problem is with UTF Encoding.
UTF16 is not supported. I used Unicode but it's also not working.
I also have installed the desired language in my PC.
Any help is appreciated.
Thank you.
string input = "How are you";
string languagePair = "en|ur";
string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;
string result = webClient.DownloadString(url);
result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
result = result.Substring(result.IndexOf(">") + 1);
result = result.Substring(0, result.IndexOf("</span>"));
result = HttpUtility.HtmlDecode(result.Trim());
MessageBox.Show(result);

WebClient Passing Parameters With Space Issue

I want to download string by calling api in which i have to pass some parameters
which contains space like :
String myUrl = AppConstants.BASE_URL + AppConstants.getFileteredList + Name + "," + LastName;
WebClient wc = new WebClient();
Uri uri = new Uri(myUrl,UriKind.Absolute);
wc.DownloadStringAsync(uri);
wc.DownloadStringCompleted += wc_DownloadStringCompleted;
it looks like this
http://demo.com/Api/getFileteredList?data=abc%20xyz,abc%20xyz
but in wc_DownloadStringCompleted , e.result throws and exception like
The remote server returned an error: NotFound.
i have tried "Uri.EscapeUriString" and also tried to implement using "HttpWebRequest" but getting same error.
Please help me out this.
Thank You in advance.
I believe its just a Malformed URL. If you peek myUrl you would notice a missing ? or something probably.
Can you check and port more details in your question.

Non english characters in Kodi API

I am using the Kodi API, to control my htpc via asp.net.
Especialy the functio named "Playlist.Add".
The Json I send is like this:
{"jsonrpc":"2.0","method":"Playlist.Insert","params":{"playlistid":0,"position":0,"item":{"file":"smb://server/Ferry Corsten/Beautiful/Ferry Corsten - Beautiful (Extended).mp3"}},"id":1}
This is working fine. But when there are some none english characters in the string like this:
{"jsonrpc":"2.0","method":"Playlist.Insert","params":{"playlistid":0,"position":0,"item":{"file":"smb://server/01-Zum Geburtstag viel Glück.mp3"}},"id":1}
It is just throwing a "RequestCanceled" Exception.
My c# source is like this:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_url);
string authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(_username + ":" + _password));
webRequest.Headers["Authorization"] = "Basic " + authInfo;
webRequest.Method = "POST";
webRequest.UserAgent = "KodiControl";
webRequest.ContentType = "application/json";
webRequest.ContentLength = json.Length;
using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
The Exception is thrown at streamWriter.Flush().
So what do I have to do to send this request?``
I suggest you look into Kodi addon unicode paths
Following that guide will help you prevent common problems with non-latin characters in Kodi.
Python only works with unicode strings internally, converting to a particular encoding on output. (or input)". To make string literals unicode by default, add
from __future__ import unicode_literals
Addon path
path = addon.getAddonInfo('path').decode('utf-8')
.decode('utf-8') tells kodi to decode the given function using utf-8.
Kodi's getAddonInfo returns an UTF-8 encoded string and we decode it an unicode.
Browse dialog
dialog = xbmcgui.Dialog()
directory = dialog.browse(0, 'Title' , 'pictures').decode('utf-8')
dialog.browse() returns an UTF-8 encoded string which perhaps contains some non latin characters. Therefore decode it to unicode!

.Net Webmaster API is incorrectly encoding URLs (Google.Apis.Webmasters.v3)

I've been struggling to get the new API to work. I am often getting this error when executing a query:
Error parsing NaN value. Path '', line 0, position 0.
From investigation I think the .Net code is incorrectly encoding URLs in the request by leaving slashes (/) unencoded. This changes the requests URL path and causes a 404.
If you omit the http:// part from the {site} part of a request it works. e.g. domain.com not http://domain.com/
There is no work around if your use an https site. Nor can you make any requests that require you to pass a specific URL outside the home page, as it will need to include a slash (/).
This is how I have done it in Google Geocode API. Not sure if that will help you but hope you get the idea.
public static string Sign(string url, string keyString)
{
ASCIIEncoding encoding = new ASCIIEncoding();
// converting key to bytes will throw an exception, need to replace '-' and '_' characters first.
string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/");
byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey);
Uri uri = new Uri(url);
byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query);
// compute the hash
HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes);
byte[] hash = algorithm.ComputeHash(encodedPathAndQueryBytes);
// convert the bytes to string and make url-safe by replacing '+' and '/' characters
string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_");
// Add the signature to the existing URI.
return uri.Scheme + "://" + uri.Host + uri.LocalPath + uri.Query + "&signature=" + signature;
}
This issue is being tracked here:
https://github.com/google/google-api-dotnet-client/issues/534
It relates to using .Net 4.0, and can be fixed by upgrading to .Net 4.5

How to send an emoji?

How can I post an emoji? If I place it in url instead of +message+ I will get wrong url, because sign "&" makes url invalid and my message won't be send.
string url = "https://api.vk.com/method/messages.send?user_id=" + user_id + "&message=" + message + "&v=5.31&access_token=...";
♥ - &#9829
URL Encode you message by calling HttpUtility.UrlEncode (link):
string message = "&#9829";
message = HttpUtility.UrlEncode(message);
Console.WriteLine(message); // outputs %26%239829
This will cause your data to never make the URL invalid, but still be readable as &#9829 at the destination. You may have to reference System.Web in your project.

Categories

Resources