private void OnQueryFeedback(object state) { TcpClient client = null; SslStream stream = null; var readBuffer = new byte[38]; Trace.TraceInformation("[{0}] Starting feedback query", this.AgentId); try { this.Connect(Settings.Apns.FeedbackHost, ref client, ref stream, 1); } catch (Exception ex) { Trace.TraceWarning("[{0}] Unable to query feedback service: {1}", this.AgentId, ex.Message); return; } if (!client.Connected) { return; } while (true) { int count = stream.Read(readBuffer, 0, readBuffer.Length); if (count < readBuffer.Length) { break; } uint time = (uint)FormattingExtensions.FromBytesNetworkOrder(readBuffer, 0); string token = FormattingExtensions.ToHexString(readBuffer, 6, 32); Trace.TraceInformation("[{0}] Feedback received: Time={1}, Token={2}", this.AgentId, time, token); try { this.Store.Unregister(this.Consumer.AppId, Platform.Apns, token, time); } catch (Exception ex) { Trace.TraceWarning("[{0}] Unable to unregister device: {1}", ex.Message); } } Trace.TraceInformation("[{0}] Feedback query ended", this.AgentId); }
protected override void OnNotify(NotificationEventArgs e) { if (_client == null || !_client.Connected) { Connect(Settings.Apns.GatewayHost, ref _client, ref _stream); _stream.BeginRead(_readBuffer, 0, _readBuffer.Length, OnRead, null); } var payloadJson = JsonConvert.SerializeObject(e.Payload); var payloadLength = Encoding.UTF8.GetByteCount(payloadJson); if (payloadLength > MaxPayloadLength) { throw new UndeliverableException("Payload too large."); } var buf = new byte[45 + payloadLength]; try { DeviceToken.Validate(Platform.Apns, e.DeviceToken); } catch (ValidationException) { throw new UndeliverableException("Invalid device token."); } FormattingExtensions.FromHexString(e.DeviceToken); buf[0] = 1; // command (always 1) (_curMessageId++).ToBytesNetworkOrder(buf, 1); // incrementing reference number e.Expiry.ToBytesNetworkOrder(buf, 5); // UNIX epoch expiry // token length and token buf[9] = 0; buf[10] = 32; // length (always 32) FormattingExtensions.FromHexString(e.DeviceToken, buf, 11); // payload length and payload ((short)payloadLength).ToBytesNetworkOrder(buf, 43); Encoding.UTF8.GetBytes(payloadJson, 0, payloadJson.Length, buf, 45); _stream.Write(buf); }