static void responseCallback(IAsyncResult result)
        {
            var msg = new C2dmMessage();

            try
            {
                var asyncParam = result.AsyncState as C2dmAsyncParameters;
                msg = asyncParam.Message;

                try
                {
                    asyncParam.WebResponse = asyncParam.WebRequest.EndGetResponse(result) as HttpWebResponse;
                    processResponseOk(asyncParam);
                }
                catch (WebException wex)
                {
                    asyncParam.WebResponse = wex.Response as HttpWebResponse;
                    processResponseError(asyncParam);
                }
            }
            catch (Exception ex)
            {
                if (UnhandledException != null)
                {
                    UnhandledException(msg, ex);
                }
                else
                {
                    throw ex;
                }
            }
        }
        static void send(C2dmMessage msg, string googleLoginAuthorizationToken, string senderID, string applicationID)
        {
            C2dmMessageTransportResponse result = new C2dmMessageTransportResponse();

            result.Message = msg;

            var postData = msg.GetPostData();

            var webReq = (HttpWebRequest)WebRequest.Create(C2DM_SEND_URL);

            //webReq.ContentLength = postData.Length;
            webReq.Method      = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.UserAgent   = "C2DM-Sharp (version: 1.0)";
            webReq.Headers.Add("Authorization: GoogleLogin auth=" + googleLoginAuthorizationToken);

            webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new C2dmAsyncParameters()
            {
                WebRequest      = webReq,
                WebResponse     = null,
                Message         = msg,
                GoogleAuthToken = googleLoginAuthorizationToken,
                SenderId        = senderID,
                ApplicationId   = applicationID
            });
        }
 public static void Send(C2dmMessage msg, string googleLoginAuthorizationToken, string senderID, string applicationID)
 {
     try
     {
         send(msg, googleLoginAuthorizationToken, senderID, applicationID);
     }
     catch (Exception ex)
     {
         if (UnhandledException != null)
             UnhandledException(msg, ex);
         else
             throw ex;
     }
 }
 public static void Send(C2dmMessage msg, string googleLoginAuthorizationToken, string senderID, string applicationID)
 {
     try
     {
         send(msg, googleLoginAuthorizationToken, senderID, applicationID);
     }
     catch (Exception ex)
     {
         if (UnhandledException != null)
         {
             UnhandledException(msg, ex);
         }
         else
         {
             throw ex;
         }
     }
 }
        static void requestStreamCallback(IAsyncResult result)
        {
            var msg = new C2dmMessage();

            try
            {
                var asyncParam = result.AsyncState as C2dmAsyncParameters;
                msg = asyncParam.Message;

                if (asyncParam != null)
                {
                    var wrStream = asyncParam.WebRequest.EndGetRequestStream(result);

                    using (var webReqStream = new StreamWriter(wrStream))
                    {
                        var data = asyncParam.Message.GetPostData();
                        webReqStream.Write(data);
                        webReqStream.Close();
                    }

                    try
                    {
                        asyncParam.WebRequest.BeginGetResponse(new AsyncCallback(responseCallback), asyncParam);
                    }
                    catch (WebException wex)
                    {
                        asyncParam.WebResponse = wex.Response as HttpWebResponse;
                        processResponseError(asyncParam);
                    }
                }
            }
            catch (Exception ex)
            {
                if (UnhandledException != null)
                {
                    UnhandledException(msg, ex);
                }
                else
                {
                    throw ex;
                }
            }
        }
Beispiel #6
0
 /// <summary>
 /// Queues a new C2DM Message to be sent
 /// </summary>
 /// <param name="msg">Constructed C2dmMessage parameter</param>
 public void QueueMessage(C2dmMessage msg)
 {
     messages.Add(msg);
     //messages.Enqueue(msg);
 }
        static C2dmMessageTransportResponse send(C2dmMessage msg, string googleLoginAuthorizationToken, string senderID, string applicationID)
        {
            C2dmMessageTransportResponse result = new C2dmMessageTransportResponse();
            result.Message = msg;

            var postData = msg.GetPostData();

            var webReq = (HttpWebRequest)WebRequest.Create(C2DM_SEND_URL);
            //webReq.ContentLength = postData.Length;
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.UserAgent = "C2DM-Sharp (version: 1.0)";
            webReq.Headers.Add("Authorization: GoogleLogin auth=" + googleLoginAuthorizationToken);

            using (var webReqStream = new StreamWriter(webReq.GetRequestStream(), Encoding.ASCII))
            {
                webReqStream.Write(postData);
                webReqStream.Close();
            }

            try
            {
                var webResp = webReq.GetResponse() as HttpWebResponse;

                if (webResp != null)
                {
                    result.ResponseStatus = MessageTransportResponseStatus.Ok;

                    //Check for an updated auth token and store it here if necessary
                    var updateClientAuth = webResp.GetResponseHeader("Update-Client-Auth");
                    if (!string.IsNullOrEmpty(updateClientAuth) && C2dmMessageTransport.UpdateGoogleClientAuthToken != null)
                        UpdateGoogleClientAuthToken(updateClientAuth);

                    //Get the response body
                    var responseBody = "Error=";
                    try { responseBody = (new StreamReader(webResp.GetResponseStream())).ReadToEnd(); }
                    catch { }

                    //Handle the type of error
                    if (responseBody.StartsWith("Error="))
                    {
                        var wrErr = responseBody.Substring(responseBody.IndexOf("Error=") + 6);
                        switch (wrErr.ToLower().Trim())
                        {
                            case "quotaexceeded":
                                result.ResponseStatus = MessageTransportResponseStatus.QuotaExceeded;
                                break;
                            case "devicequotaexceeded":
                                result.ResponseStatus = MessageTransportResponseStatus.DeviceQuotaExceeded;
                                break;
                            case "invalidregistration":
                                result.ResponseStatus = MessageTransportResponseStatus.InvalidRegistration;
                                break;
                            case "notregistered":
                                result.ResponseStatus = MessageTransportResponseStatus.NotRegistered;
                                break;
                            case "messagetoobig":
                                result.ResponseStatus = MessageTransportResponseStatus.MessageTooBig;
                                break;
                            case "missingcollapsekey":
                                result.ResponseStatus = MessageTransportResponseStatus.MissingCollapseKey;
                                break;
                            default:
                                result.ResponseStatus = MessageTransportResponseStatus.Error;
                                break;
                        }

                        throw new MessageTransportException(wrErr, result);
                    }
                    else
                    {
                        //Get the message ID
                        if (responseBody.StartsWith("id="))
                            result.MessageId = responseBody.Substring(3).Trim();
                    }
                }
            }
            catch (WebException webEx)
            {
                var webResp = webEx.Response as HttpWebResponse;

                if (webResp != null)
                {
                    if (webResp.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        //401 bad auth token
                        result.ResponseCode = MessageTransportResponseCode.InvalidAuthToken;
                        result.ResponseStatus = MessageTransportResponseStatus.Error;
                        throw new InvalidAuthenticationTokenTransportException(result);
                    }
                    else if (webResp.StatusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        //First try grabbing the retry-after header and parsing it.
                        TimeSpan retryAfter = new TimeSpan(0, 0, 120);

                        var wrRetryAfter = webResp.GetResponseHeader("Retry-After");

                        if (!string.IsNullOrEmpty(wrRetryAfter))
                        {
                            DateTime wrRetryAfterDate = DateTime.UtcNow;

                            if (DateTime.TryParse(wrRetryAfter, out wrRetryAfterDate))
                                retryAfter = wrRetryAfterDate - DateTime.UtcNow;
                            else
                            {
                                int wrRetryAfterSeconds = 120;
                                if (int.TryParse(wrRetryAfter, out wrRetryAfterSeconds))
                                    retryAfter = new TimeSpan(0,0, wrRetryAfterSeconds);
                            }
                        }

                        //503 exponential backoff, get retry-after header
                        result.ResponseCode = MessageTransportResponseCode.ServiceUnavailable;
                        result.ResponseStatus = MessageTransportResponseStatus.Error;

                        throw new ServiceUnavailableTransportException(retryAfter, result);
                    }
                }
            }

            return result;
        }
 public static C2dmMessageTransportResponse Send(C2dmMessage msg, string googleLoginAuthorizationToken, string senderID, string applicationID)
 {
     return send(msg, googleLoginAuthorizationToken, senderID, applicationID);
 }
        static void responseCallback(IAsyncResult result)
        {
            var msg = new C2dmMessage();

            try
            {
                var asyncParam = result.AsyncState as C2dmAsyncParameters;
                msg = asyncParam.Message;

                try
                {
                    asyncParam.WebResponse = asyncParam.WebRequest.EndGetResponse(result) as HttpWebResponse;
                    processResponseOk(asyncParam);
                }
                catch (WebException wex)
                {
                    asyncParam.WebResponse = wex.Response as HttpWebResponse;
                    processResponseError(asyncParam);
                }
            }
            catch (Exception ex)
            {
                if (UnhandledException != null)
                    UnhandledException(msg, ex);
                else
                    throw ex;
            }
        }
        static void send(C2dmMessage msg, string googleLoginAuthorizationToken, string senderID, string applicationID)
        {
            C2dmMessageTransportResponse result = new C2dmMessageTransportResponse();
            result.Message = msg;

            var postData = msg.GetPostData();

            var webReq = (HttpWebRequest)WebRequest.Create(C2DM_SEND_URL);
            //webReq.ContentLength = postData.Length;
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.UserAgent = "C2DM-Sharp (version: 1.0)";
            webReq.Headers.Add("Authorization: GoogleLogin auth=" + googleLoginAuthorizationToken);

            webReq.BeginGetRequestStream(new AsyncCallback(requestStreamCallback), new C2dmAsyncParameters()
            {
                WebRequest = webReq,
                WebResponse = null,
                Message = msg,
                GoogleAuthToken = googleLoginAuthorizationToken,
                SenderId = senderID,
                ApplicationId = applicationID
            });
        }
        static void requestStreamCallback(IAsyncResult result)
        {
            var msg = new C2dmMessage();

            try
            {
                var asyncParam = result.AsyncState as C2dmAsyncParameters;
                msg = asyncParam.Message;

                if (asyncParam != null)
                {
                    var wrStream = asyncParam.WebRequest.EndGetRequestStream(result);

                    using (var webReqStream = new StreamWriter(wrStream))
                    {
                        var data = asyncParam.Message.GetPostData();
                        webReqStream.Write(data);
                        webReqStream.Close();
                    }

                    try
                    {
                        asyncParam.WebRequest.BeginGetResponse(new AsyncCallback(responseCallback), asyncParam);
                    }
                    catch (WebException wex)
                    {
                        asyncParam.WebResponse = wex.Response as HttpWebResponse;
                        processResponseError(asyncParam);
                    }
                }
            }
            catch (Exception ex)
            {
                if (UnhandledException != null)
                    UnhandledException(msg, ex);
                else
                    throw ex;
            }
        }
Beispiel #12
0
        private void messageTransportWork(object state)
        {
            var cancelToken = (CancellationToken)state;

            while (!cancelToken.IsCancellationRequested)
            {
                bool sentWaitNotice = false;

                //Check to see if we should be waiting
                while (DateTime.UtcNow < waitUntil && !cancelToken.IsCancellationRequested)
                {
                    //Check if we've sent notice that we're waiting this time yet or not
                    // and send notice if not
                    if (!sentWaitNotice && this.Waiting != null && !cancelToken.IsCancellationRequested)
                    {
                        sentWaitNotice = true;
                        this.Waiting(waitUntil);
                    }

                    for (int i = 0; i < 10; i++)
                    {
                        if (!cancelToken.IsCancellationRequested)
                        {
                            break;
                        }

                        System.Threading.Thread.Sleep(100);
                    }
                }

                C2dmMessage toSend = null;
                //if (messages.TryDequeue(out toSend))
                try
                {
                    if (cancelToken.IsCancellationRequested || (toSend = messages.Take(cancelToken)) == null)
                    {
                        continue;
                    }
                }
                catch (OperationCanceledException)
                {
                    continue;
                }

                try
                {
                    var result = C2dmMessageTransport.Send(toSend, this.googleAuthToken, this.SenderID, this.ApplicationID);

                    if (this.MessageSuccess != null)
                    {
                        this.MessageSuccess(result);
                    }

                    //Reset the retry
                    if (lastRetryAfter.TotalSeconds > 0)
                    {
                        lastRetryAfter = new TimeSpan(0, 0, 0);
                    }
                }
                catch (ServiceUnavailableTransportException suEx)
                {
                    //Enqueue the message again to resend later
                    QueueMessage(toSend);

                    //Backoff the last retry timespan + new one
                    lastRetryAfter += suEx.RetryAfter;

                    //Set the time to wait until
                    waitUntil = DateTime.UtcNow + lastRetryAfter;
                }
                catch (MessageTransportException mtEx)
                {
                    if (this.MessageFailure != null)
                    {
                        this.MessageFailure(mtEx);
                    }
                }
                catch (Exception ex)
                {
                    //TODO: Log Error
                }
            }
        }
Beispiel #13
0
 /// <summary>
 /// Queues a new C2DM Message to be sent
 /// </summary>
 /// <param name="msg">Constructed C2dmMessage parameter</param>
 public void QueueMessage(C2dmMessage msg)
 {
     messages.Add(msg);
     //messages.Enqueue(msg);
 }
        static C2dmMessageTransportResponse send(C2dmMessage msg, string googleLoginAuthorizationToken, string senderID, string applicationID)
        {
            C2dmMessageTransportResponse result = new C2dmMessageTransportResponse();

            result.Message = msg;

            var postData = msg.GetPostData();

            var webReq = (HttpWebRequest)WebRequest.Create(C2DM_SEND_URL);

            //webReq.ContentLength = postData.Length;
            webReq.Method      = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.UserAgent   = "C2DM-Sharp (version: 1.0)";
            webReq.Headers.Add("Authorization: GoogleLogin auth=" + googleLoginAuthorizationToken);

            using (var webReqStream = new StreamWriter(webReq.GetRequestStream(), Encoding.ASCII))
            {
                webReqStream.Write(postData);
                webReqStream.Close();
            }

            try
            {
                var webResp = webReq.GetResponse() as HttpWebResponse;

                if (webResp != null)
                {
                    result.ResponseStatus = MessageTransportResponseStatus.Ok;

                    //Check for an updated auth token and store it here if necessary
                    var updateClientAuth = webResp.GetResponseHeader("Update-Client-Auth");
                    if (!string.IsNullOrEmpty(updateClientAuth) && C2dmMessageTransport.UpdateGoogleClientAuthToken != null)
                    {
                        UpdateGoogleClientAuthToken(updateClientAuth);
                    }

                    //Get the response body
                    var responseBody = "Error=";
                    try { responseBody = (new StreamReader(webResp.GetResponseStream())).ReadToEnd(); }
                    catch { }

                    //Handle the type of error
                    if (responseBody.StartsWith("Error="))
                    {
                        var wrErr = responseBody.Substring(responseBody.IndexOf("Error=") + 6);
                        switch (wrErr.ToLower().Trim())
                        {
                        case "quotaexceeded":
                            result.ResponseStatus = MessageTransportResponseStatus.QuotaExceeded;
                            break;

                        case "devicequotaexceeded":
                            result.ResponseStatus = MessageTransportResponseStatus.DeviceQuotaExceeded;
                            break;

                        case "invalidregistration":
                            result.ResponseStatus = MessageTransportResponseStatus.InvalidRegistration;
                            break;

                        case "notregistered":
                            result.ResponseStatus = MessageTransportResponseStatus.NotRegistered;
                            break;

                        case "messagetoobig":
                            result.ResponseStatus = MessageTransportResponseStatus.MessageTooBig;
                            break;

                        case "missingcollapsekey":
                            result.ResponseStatus = MessageTransportResponseStatus.MissingCollapseKey;
                            break;

                        default:
                            result.ResponseStatus = MessageTransportResponseStatus.Error;
                            break;
                        }

                        throw new MessageTransportException(wrErr, result);
                    }
                    else
                    {
                        //Get the message ID
                        if (responseBody.StartsWith("id="))
                        {
                            result.MessageId = responseBody.Substring(3).Trim();
                        }
                    }
                }
            }
            catch (WebException webEx)
            {
                var webResp = webEx.Response as HttpWebResponse;

                if (webResp != null)
                {
                    if (webResp.StatusCode == HttpStatusCode.Unauthorized)
                    {
                        //401 bad auth token
                        result.ResponseCode   = MessageTransportResponseCode.InvalidAuthToken;
                        result.ResponseStatus = MessageTransportResponseStatus.Error;
                        throw new InvalidAuthenticationTokenTransportException(result);
                    }
                    else if (webResp.StatusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        //First try grabbing the retry-after header and parsing it.
                        TimeSpan retryAfter = new TimeSpan(0, 0, 120);

                        var wrRetryAfter = webResp.GetResponseHeader("Retry-After");

                        if (!string.IsNullOrEmpty(wrRetryAfter))
                        {
                            DateTime wrRetryAfterDate = DateTime.UtcNow;

                            if (DateTime.TryParse(wrRetryAfter, out wrRetryAfterDate))
                            {
                                retryAfter = wrRetryAfterDate - DateTime.UtcNow;
                            }
                            else
                            {
                                int wrRetryAfterSeconds = 120;
                                if (int.TryParse(wrRetryAfter, out wrRetryAfterSeconds))
                                {
                                    retryAfter = new TimeSpan(0, 0, wrRetryAfterSeconds);
                                }
                            }
                        }

                        //503 exponential backoff, get retry-after header
                        result.ResponseCode   = MessageTransportResponseCode.ServiceUnavailable;
                        result.ResponseStatus = MessageTransportResponseStatus.Error;

                        throw new ServiceUnavailableTransportException(retryAfter, result);
                    }
                }
            }

            return(result);
        }
 public static C2dmMessageTransportResponse Send(C2dmMessage msg, string googleLoginAuthorizationToken, string senderID, string applicationID)
 {
     return(send(msg, googleLoginAuthorizationToken, senderID, applicationID));
 }