How to send an emoji? - c#

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.

Related

Getting Error 400: Bad request at authenticate via Twitch.tv api

I am new here and I hope someone can help me. I try to connect to twitch.tv I am trying to get an oauth2 authentication on twitch.tv with a small C# program. I am using the twitch.tv authentication request. Here is my C# code:
var loginURL = "https://api.twitch.tv/kraken/oauth2/authorize?
response_type=code&"+
client_id="+ clientID+"
"&redirect_uri=http://localhost&"+
"state=TWStreamingStateAuthenticated";
this.richTextBox1.Text = loginURL;
string code = get_DownLoadString(loginURL);
this.richTextBox1.Text = code;
This is the part, which does not work. It gives me the Error 400: Bad Request.
WebRequest request = WebRequest.Create("https://api.twitch.tv/kraken/oauth2/token");
request.Method = "POST";
string postData = "client_id=" + clientID +
"&client_secret=" + clientSecret +
"&grant_type=authorization_code" +
"&redirect_uri=http://localhost" +
"&code=" + code +
"&state=TWStreamingStateAuthenticated";
ASCIIEncoding encoding = new ASCIIEncoding();
postData = HttpUtility.UrlEncode(postData);
byte[] byteArray = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream datatream = request.GetRequestStream();
datatream.Write(byteArray, 0, byteArray.Length);
datatream.Close();
WebResponse respone = request.GetResponse();
MessageBox.Show(((HttpWebResponse)respone).StatusDescription);
I hope someone can help me.
And here is the Get_DownloadString(string URL) Method.
private static string get_DownLoadString(string URL)
{
try
{
string temp = (new WebClient().DownloadString(URL));
return temp;
}
catch (WebException)
{
return null;
}
}
This code doesn't look right to me:
string postData = "client_id=" + clientID +
"&client_secret=" + clientSecret +
"&grant_type=authorization_code" +
"&redirect_uri=http://localhost" +
"&code=" + code +
"&state=TWStreamingStateAuthenticated";
ASCIIEncoding encoding = new ASCIIEncoding();
postData = HttpUtility.UrlEncode(postData);
byte[] byteArray = encoding.GetBytes(postData);
// ...
You are URL-encoding the entire post-data string. This has the effect of converting the & and = signs in the post data to %26 and %3d respectively. When the remote server receives this data, it will scan through it looking for the & and = signs in order to separate out the parameter names and values. Of course, it won't find any, so it will assume you have one big parameter name with no value. The server is probably expecting values for each of the six parameters you are attempting to send, but seeing values for none of them, and this may be why you are getting a 400 Bad Request error.
Instead of URL-encoding the whole string, URL-encode parameter values that may contain characters other than letters and numbers. I would try the following instead:
string postData = "client_id=" + HttpUtility.UrlEncode(clientID) +
"&client_secret=" + HttpUtility.UrlEncode(clientSecret) +
"&grant_type=authorization_code" +
"&redirect_uri=" + HttpUtility.UrlEncode("http://localhost") +
"&code=" + HttpUtility.UrlEncode(code) +
"&state=TWStreamingStateAuthenticated";
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(postData);
// ...
This way, the remote server will still see the & and = characters, and so will be able to pull out the parameter names and values. Because we've URL-encoded the client ID, client secret, URL and code, any characters they contain that may have meaning in a URL will not have that meaning and will be received by the remote server as intended.
Also, if you are still getting a 400 Bad Request error response, try reading the contents of the response stream, obtained by calling GetResponseStream() on the response. Often that will contain a message that will help you figure out what's gone wrong.
Having had a closer look at your code, it seems you have a misunderstanding about how OAuth authentication works. Your getDownload_String method will not get the access code you want, it will only get the HTML text of a Twitch login page.
This is how OAuth authentication works:
Your app sends the user to a login URL, to allow the user to log in to Twitch.
In the web browser, the user then enters their login credentials and submits the page to Twitch.
The Twitch API then responds by redirecting the user's web browser to the redirect URL, with a code appended. Your web app then reads this code out of the URL.
If your code is in a web app it will be able to respond to the URL redirected to in step 3. Alternatively, you may be able to use a WebBrowser control (Windows Forms, WPF) to handle the Twitch login, and handle a Navigating event. If the URL being navigated to begins with the redirect URL, grab the code out of the URL, cancel the navigation and hide the login web-browser control.
The presence of what appears to be a RichTextBox control, along with your comment about your code being a 'small C# application', makes me think that your code is a Windows Forms or WPF application. If this is the case, then you will need to either:
use a WebBrowser control as I described above,
replace your WinForms/WPF app with a web app, or
get in contact with Twitch to request the use of the password flow (which appears not to require a redirect), and use that instead.

.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

In C#, what is the right way to post attachments to Confluence REST API?

I am migrating from Confluence's SOAP API to using their REST API. I see there is support for adding attachments to a page (by doing a POST) but I am running into issues getting it to work (I am getting a 403: Forbidden Error message). I have other "get" items working fine through the rest api but doing an attachment post seems to keep failing.
Here is my current code (given a specific filename):
byte[] rawData = File.ReadAllBytes(filename);
var pageId = "11134";
var url = new Uri("http://example.com:9088/rest/api/content/" + pageId + "/child/attachment");
var requestContent = new MultipartFormDataContent();
var imageContent = new ByteArrayContent(rawData);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse(attachement.contentType);
requestContent.Add(imageContent, "file", attachement.fileName);
requestContent.Headers.Add("X-Atlassian-Token", "nocheck");
Can you see if I am doing anything wrong above?
403 status indicates that request is not authorized. In order to authorize a request you need to specify Authorization header. Confluence REST API supports Basic authorization scheme. For basic authentication you need to specify the following header with each request: Authorization: Basic username:password where username:password part should be Base64-encoded. You can use the following code in order to do this:
string userName;
string password;
string authorizationString = userName + ":" + password;
string encodedValue = Convert.ToBase64String(Encoding.ASCII.GetBytes(authorizationString));
string authorizationHeaderValue = "Basic " + encodedValue;
requestContent.Headers.Add("Authorization", authorizationHeaderValue);
According to this link you also should specify the following url parameter with each request: os_authType=basic.
HTTP basic authentication: (Authorization HTTP header) containing
'Basic username:password'. Please note however, username:password must
be base64 encoded. The URL must also contain the 'os_authType=basic'
query parameter.
Note: make sure to connect via https if using basic authentication;
From Confluence documentation (RTFM)
In order to protect against XSRF attacks, because this method accepts multipart/form-data, it has XSRF protection on it. This means you must submit a header of X-Atlassian-Token: nocheck with the request, otherwise it will be blocked.
Add this before the Post
httpClient.Headers.Add("X-Atlassian-Token", "nocheck");
Here is the way I prefer:
string url = "https://localhost:8080/confluence/rest/api/content/123456/child/attachment";
string filename = #"C:\temp\test.txt";
using (var client = new WebClient())
{
string authorizationString = username + ":" + password;
string encodedValue = Convert.ToBase64String(Encoding.ASCII.GetBytes(authorizationString));
client.Headers.Add("Authorization", "Basic " + encodedValue);
client.Headers.Add("X-Atlassian-Token", "nocheck");
byte[] result = client.UploadFile(url, filename);
string responseAsString = Encoding.Default.GetString(result);
}

'System.UriFormatException' in HyperLink

I have some strings like this:
www.example.com/sdWqaP
twitter.com/sdfks
and want to assign them to a HyperLink
var hyperlink = new Hyperlink
{
NavigateUri = new Uri(url),
TargetName = "_blank",
};
if url starts with http:// it works fine, otherwise throws a UriFormatException.
Update: urls like this www.google.com aren't valid http urls. isn't there a better way than var url = "http://" + "www.google.com"
You can use
var uri = new UriBuilder(s).Uri;
Reference: http://msdn.microsoft.com/en-us/library/y868d5wh(v=vs.110).aspx
public UriBuilder(
string uri
)
// If uri does not specify a scheme, the scheme defaults to "http:".
Scheme (http:// in your case) is mandatory part of Uri string. UriFormatException will be thrown if the scheme specified in uri string is not correctly formed according to Uri.CheckSchemeName() method.
[MSDN : Uri Constructor (String)].
I don't understand well what you mean "better safer way". Appending scheme in uri string is common practice anyway.
Check your URL is valid and then assign to the URL
For validating a URL check the below link
How to check whether a string is a valid HTTP URL?

URL Encoding and Decoding

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")));

Categories

Resources