Skip to content

Instantly share code, notes, and snippets.

@ducas
Created July 20, 2011 23:04
Show Gist options
  • Save ducas/1096140 to your computer and use it in GitHub Desktop.
Save ducas/1096140 to your computer and use it in GitHub Desktop.
TotalPimp C# Device Registrar
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using Newtonsoft.Json; // You'll need to add JSON.Net to your solution.
namespace TotalPimp
{
public class DeviceRegistrar
{
private const string channelUriKey = "TotalPimp.DeviceRegistrar.RegistrationId";
private const string deviceRegistrationIdKey = "TotalPimp.DeviceRegistrar.DeviceRegistrationId";
private const string registerUrl = "http://totalpimp.apphb.com/registration/register";
private const string unregisterUrl = "http://totalpimp.apphb.com/registration/register";
private const string postMethod = "POST";
private const string jsonContentType = "application/json";
public void TryRegisterDevice(Uri channelUri, string user, string deviceId, string token, Action<bool> callback)
{
PostJson<RegisterResult>(
registerUrl,
new RegisterRequest { registrationId = channelUri.ToString(), user = user, deviceId = deviceId, deviceType = "WindowsPhone", token = token },
r =>
{
if (r.id == 0)
{
callback(false);
return;
}
PersistRegistration(channelUri, r.id);
callback(true);
},
r => callback(false));
}
private static void PersistRegistration(Uri channelUri, int deviceRegistrationId)
{
AddOrChangeSetting(channelUriKey, channelUri);
AddOrChangeSetting(deviceRegistrationIdKey, deviceRegistrationId);
}
private static void AddOrChangeSetting(string key, object value)
{
var settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains(key))
{
settings[key] = value;
}
else
{
settings.Add(key, value);
}
settings.Save();
}
private static void PostJson<T>(string url, object data, Action<T> successCallback, Action<HttpWebResponse> errorCallback)
{
var request = WebRequest.CreateHttp(url);
request.Method = postMethod;
request.ContentType = jsonContentType;
request.BeginGetRequestStream(
req =>
{
WriteJsonToRequest(request, req, data);
request.BeginGetResponse(
resp =>
{
var response = GetHttpWebResponse(request, resp);
if (response.StatusCode == HttpStatusCode.OK)
successCallback(ReadJsonFromRequest<T>(response));
else
errorCallback(response);
}, null);
}, null);
}
private static HttpWebResponse GetHttpWebResponse(WebRequest request, IAsyncResult asyncResult)
{
try
{
return request.EndGetResponse(asyncResult) as HttpWebResponse;
}
catch (WebException ex)
{
return ex.Response as HttpWebResponse;
}
}
private static T ReadJsonFromRequest<T>(WebResponse response)
{
string json;
using (var reader = new StreamReader(response.GetResponseStream()))
{
json = reader.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(json);
}
private static void WriteJsonToRequest(WebRequest request, IAsyncResult asyncResult, object data)
{
using (var stream = request.EndGetRequestStream(asyncResult))
using (var writer = new StreamWriter(stream))
{
var serialized = JsonConvert.SerializeObject(data);
writer.Write(serialized);
writer.Flush();
}
}
public bool IsRegistered
{
get { return GetSetting(deviceRegistrationIdKey, -1) != -1; }
}
private static T GetSetting<T>(string key, T defaultValue = default(T))
{
T value;
var settings = IsolatedStorageSettings.ApplicationSettings;
return settings.TryGetValue(key, out value) ? value : defaultValue;
}
public void UnregisterDevice(string token)
{
var channelUri = GetSetting<Uri>(channelUriKey, null);
var deviceRegistrationId = GetSetting(deviceRegistrationIdKey, -1);
if (channelUri == null || deviceRegistrationId == -1) return;
PostJson<RegisterResult>(
unregisterUrl,
new UnregisterRequest { registrationId = channelUri.ToString(), id = deviceRegistrationId, token = token },
r => { },
r => { });
var settings = IsolatedStorageSettings.ApplicationSettings;
settings.Remove(channelUriKey);
settings.Remove(deviceRegistrationIdKey);
settings.Save();
}
// ReSharper disable InconsistentNaming
public class RegisterRequest
{
public string registrationId { get; set; }
public string user { get; set; }
public string deviceId { get; set; }
public string deviceType { get; set; }
public string token { get; set; }
}
public class RegisterResult
{
public int id { get; set; }
}
public class UnregisterRequest
{
public string registrationId { get; set; }
public int id { get; set; }
public string token { get; set; }
}
// ReSharper restore InconsistentNaming
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment