Created
April 26, 2012 07:22
-
-
Save icleversoft/2497126 to your computer and use it in GitHub Desktop.
Sending Apple Push Notifications using C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int port = 2195; | |
String hostname = "gateway.sandbox.push.apple.com"; | |
//load certificate | |
string certificatePath = @"cert.p12"; | |
string certificatePassword = ""; | |
X509Certificate2 clientCertificate = new X509Certificate2(certificatePath, certificatePassword); | |
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate); | |
TcpClient client = new TcpClient(hostname, port); | |
SslStream sslStream = new SslStream( | |
client.GetStream(), | |
false, | |
new RemoteCertificateValidationCallback(ValidateServerCertificate), | |
null | |
); | |
try | |
{ | |
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, true); | |
} | |
catch (AuthenticationException ex) | |
{ | |
client.Close(); | |
return; | |
} | |
// Encode a test message into a byte array. | |
MemoryStream memoryStream = new MemoryStream(); | |
BinaryWriter writer = new BinaryWriter(memoryStream); | |
writer.Write((byte)0); //The command | |
writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte) | |
writer.Write((byte)32); //The deviceId length (big-endian second byte) | |
String deviceId = "DEVICEIDGOESHERE"; | |
writer.Write(ToByteArray(deviceId.ToUpper())); | |
String payload = "{\"aps\":{\"alert\":\"I like spoons also\",\"badge\":14}}"; | |
writer.Write((byte)0); //First byte of payload length; (big-endian first byte) | |
writer.Write((byte)payload.Length); //payload length (big-endian second byte) | |
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload); | |
writer.Write(b1); | |
writer.Flush(); | |
byte[] array = memoryStream.ToArray(); | |
sslStream.Write(array); | |
sslStream.Flush(); | |
// Close the client connection. | |
client.Close(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you
this work for me after finding below methods
`private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;