Skip to content

Instantly share code, notes, and snippets.

@nakamura-to
Created November 28, 2012 07:22
Show Gist options
  • Save nakamura-to/4159599 to your computer and use it in GitHub Desktop.
Save nakamura-to/4159599 to your computer and use it in GitHub Desktop.
raw notification sample
using System.Diagnostics;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
// see http://msdn.microsoft.com/library/windows/apps/hh761488.aspx
namespace RowNotificatioinClient
{
class Program
{
private const string ChannelUri = "REPLACE!!!";
private const string ClientId = "REPLACE!!!";
private const string ClientSecret = "REPLACE!!!";
static void Main(string[] args)
{
Run();
Console.ReadKey();
}
static async void Run()
{
try
{
var token = await RequestOAuthTokenAsync();
await RequestNotificationAsync(token);
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
static async Task<string> RequestOAuthTokenAsync()
{
var parms = new List<KeyValuePair<String, String>>
{
new KeyValuePair<String, String>("grant_type", "client_credentials"),
new KeyValuePair<String, String>("scope", "notify.windows.com"),
new KeyValuePair<String, String>("client_id", ClientId),
new KeyValuePair<String, String>("client_secret", ClientSecret)
};
var client = new HttpClient();
var content = new FormUrlEncodedContent(parms);
var response = await client.PostAsync("https://login.live.com/accesstoken.srf", content);
var jsonContent = await response.Content.ReadAsStringAsync();
var tokenResponse = JsonConvert.DeserializeObject<TokenPayload>(jsonContent);
return tokenResponse.access_token;
}
static async Task RequestNotificationAsync(string accessToken)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", accessToken));
client.DefaultRequestHeaders.Add("X-WNS-Type", "wns/raw");
var message = "Hello: " + DateTime.Now;
var content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(message)));
var response = await client.PostAsync(ChannelUri, content);
await response.Content.ReadAsStringAsync();
}
}
public class TokenPayload
{
public String token_type;
public String access_token;
public String expires_in;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment