public static int SendWinPhonePushNotification(string subscriptionUri, string xml, out com.progamma.IDVariant infoInde) { int returnCode = -1; string resultText = string.Empty; string notificationType = "toast"; if (xml.Trim().ToLower().Contains("<wp:tile>")) { notificationType = "token"; } try { resultText = SendWinPhonePushNotification(subscriptionUri, xml, notificationType); } catch (Exception ex) { //Errore generico returnCode = 199; resultText = "EXCEPTION: " + ex.Message; } //infoInde = resultText; infoInde = new com.progamma.IDVariant(); infoInde.set(new com.progamma.IDVariant(resultText)); return(returnCode); }
//com.progamma.IDVariant info) => su inde viene usato l'idvariant il parametro non va definito come di output public static int ParseResultPlain(string outputText, out com.progamma.IDVariant infoInde) { int returnCode = -1; string outInfo = outputText; if (outputText.ToLowerInvariant().StartsWith("gmcrror")) { //GMC server error returnCode = 200; } if (outputText.ToLowerInvariant().StartsWith("id")) { //id=0:1352894598679934%67edbc55f9fd7ecd returnCode = 0; outInfo = string.Empty; } if (outputText.ToLowerInvariant().StartsWith("error")) { //Error=InvalidRegistration int index = outputText.ToLowerInvariant().IndexOf("error=") + 6; string errorMessage = outputText.Substring(index, outputText.Length - index); returnCode = getErrorCode(errorMessage); outInfo = errorMessage; } if (outputText.ToLowerInvariant().Contains("registration_id")) { returnCode = 10; int index = outputText.ToLowerInvariant().IndexOf("registration_id=") + 16; outInfo = outputText.Substring(index, outputText.Length - index); } infoInde = new com.progamma.IDVariant(); infoInde.set(new com.progamma.IDVariant(outInfo)); //infoInde = outInfo; return(returnCode); }
public static int ParseResult(string inputRegIds, string rifRegId, string outputJson, out com.progamma.IDVariant infoInde) { //Errori su singoli invii: http://developer.android.com/guide/google/gcm/gcm.html#error_codes //Canonical id: http://developer.android.com/guide/google/gcm/adv.html#canonical : registration id multipli: rimpiazzare l'id di ritorno con l'id originario int returnCode = -1; string[] regIdsSpediti = inputRegIds.Split(','); int indexRefId = -1; for (int i = 0; i < regIdsSpediti.Length; i++) { if (regIdsSpediti[i].Equals(rifRegId)) { indexRefId = i; } } if (indexRefId == -1) { //Elemento non trovato nel gruppo dei regId inviati } //int indexRefId = regIdsSpediti.ToList().IndexOf(rifRegId); StringBuilder resultBuider = new StringBuilder(); //E' necessario accedere alle librerie che sono sul framework 4.0 tramite reflection perchè su inde la compilazione viene fatta solo al frk 2.0. Sul server deve cmq esserci il frk 4 Assembly WebExt = Assembly.LoadWithPartialName("System.Web.Extensions"); Object serializer = WebExt.CreateInstance("System.Web.Script.Serialization.JavaScriptSerializer", true, BindingFlags.CreateInstance, null, null, null, null); MethodInfo method = serializer.GetType().GetMethod("DeserializeObject", new Type[] { typeof(String) }); Dictionary <string, object> dict = (Dictionary <string, object>)method.Invoke(serializer, new Object[] { outputJson }); foreach (string strKey in dict.Keys) { if (strKey.Equals("error")) { //Errore su tutto l'invio //TODO: prevedere un invio di tentativi returnCode = 200; resultBuider.Append(outputJson); } else if (strKey.Equals("results")) { if (dict[strKey] is Array) { object[] results = (object[])(dict[strKey]); int index = 0; string messageId = string.Empty; string error = string.Empty; string canonicalId = string.Empty; foreach (Dictionary <string, object> resultItem in results) { if (index == indexRefId) { foreach (string keyresult in resultItem.Keys) { if (keyresult.Equals("message_id")) { messageId = resultItem[keyresult].ToString(); } if (keyresult.Equals("error")) { error = resultItem[keyresult].ToString(); } if (keyresult.Equals("registration_id")) { canonicalId = resultItem[keyresult].ToString(); } } if (!string.IsNullOrEmpty(error)) { returnCode = getErrorCode(error); resultBuider.Append(error); } else if (!string.IsNullOrEmpty(canonicalId)) { returnCode = 10; resultBuider.Append(canonicalId); } else if (!string.IsNullOrEmpty(messageId)) { returnCode = 0; resultBuider.Append(messageId); } } index++; } } } } infoInde = new com.progamma.IDVariant(); infoInde.set(new com.progamma.IDVariant(resultBuider.ToString())); return(returnCode); }
public static int SendMessage(string googleLoginAuthorizationToken, string registrationId, string messageText, out com.progamma.IDVariant info) { int ritorno = -1; string infoRitorno = string.Empty; info = new com.progamma.IDVariant(); StringBuilder sb = new StringBuilder(); string collapseKey = Guid.NewGuid().ToString("n"); ServicePointManager.ServerCertificateValidationCallback += delegate( object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return(true); }; HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(GoogleMessageUrl); webReq.Method = "POST"; webReq.KeepAlive = false; NameValueCollection postFieldNameValue = new NameValueCollection(); postFieldNameValue.Add(RegistrationIdParam, registrationId); postFieldNameValue.Add(CollapseKeyParam, collapseKey); postFieldNameValue.Add(DelayWhileIdleParam, "0"); postFieldNameValue.Add(DataPayloadParam, messageText); string postData = GetPostStringFrom(postFieldNameValue); byte[] byteArray = Encoding.UTF8.GetBytes(postData); webReq.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; webReq.ContentLength = byteArray.Length; webReq.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + googleLoginAuthorizationToken); Stream dataStream = webReq.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); try { HttpWebResponse webResp = webReq.GetResponse() as HttpWebResponse; #region checking response if (webResp != null) { ritorno = 0; //Check for an updated auth token and store it here if necessary string updateClientAuth = webResp.GetResponseHeader("Update-Client-Auth"); if (!string.IsNullOrEmpty(updateClientAuth)) { ritorno = 100; //Errore legato alla necessità di creare un nuovo tocken di autorizzazione } //Get the response body string responseBody = "Error="; try { responseBody = (new StreamReader(webResp.GetResponseStream())).ReadToEnd(); } catch { } //Handle the type of error if (responseBody.StartsWith("Error=")) { string wrErr = responseBody.Substring(responseBody.IndexOf("Error=") + 6); switch (wrErr.ToLower().Trim()) { case "quotaexceeded": infoRitorno = "Error: " + "Quota Exceeded"; ritorno = 101; //QuotaExceeded; break; case "devicequotaexceeded": infoRitorno = "Error: " + "Device Quota Exceeded"; ritorno = 102; //DeviceQuotaExceeded; break; case "invalidregistration": infoRitorno = "Error: " + "Invalid Registration"; ritorno = 103; //InvalidRegistration; break; case "notregistered": infoRitorno = "Error: " + "Not Registered"; ritorno = 104; //NotRegistered; break; case "messagetoobig": infoRitorno = "Error: " + "Message Too Big"; ritorno = 105; //MessageTooBig; break; case "missingcollapsekey": infoRitorno = "Error: " + "Missing CollapseKey"; ritorno = 106; //MissingCollapseKey; break; default: infoRitorno = "Error: " + "Generic Error"; ritorno = 107; //Error; break; } } else { //Get the message ID if (responseBody.StartsWith("id=")) { infoRitorno = "Message: " + responseBody.Trim(); } } } #endregion } catch (WebException webEx) { #region checking error HttpWebResponse webResp = webEx.Response as HttpWebResponse; if (webResp != null) { if (webResp.StatusCode == HttpStatusCode.Unauthorized) { //401 bad auth token ritorno = 108; infoRitorno = "Error: " + "InvalidAuthToken"; } else if (webResp.StatusCode == HttpStatusCode.ServiceUnavailable) { //First try grabbing the retry-after header and parsing it. TimeSpan retryAfter = new TimeSpan(0, 0, 120); string 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 ritorno = 109; infoRitorno = "ServiceUnavailable"; } } #endregion } info = new com.progamma.IDVariant(); info.set(new com.progamma.IDVariant(infoRitorno)); return(ritorno); }
/// <summary> /// Permette l'invio di un messaggio Toast attraverso WNS /// </summary> /// <param name="accessToken">Access tocken ottenuto dalla chiamata a GetWinStoreAccessToken </param> /// <param name="uri">Url ottenuto dalla registrazione del dispositivo</param> /// <param name="xml">Xml del messaggio da spedire</param> /// <param name="infoInde">Messaggio di ritorno esito operazione</param> /// <returns>Codice numerico esito operazione</returns> public static int SendWinStorePushNotification(string accessToken, string uri, string xml, out com.progamma.IDVariant infoInde) { int returnCode = -1; string resultText = string.Empty; try { byte[] contentInBytes = Encoding.UTF8.GetBytes(xml); HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest; request.Method = "POST"; // X-WNS-Type: wns/toast | wns/badge | wns/tile | wns/raw string notificationType = "wns/toast"; if (xml.Trim().ToLower().StartsWith("<tile")) { notificationType = "wns/tile"; } else if (xml.Trim().ToLower().StartsWith("<badge")) { notificationType = "wns/badge"; } request.Headers.Add("X-WNS-Type", notificationType); request.ContentType = "text/xml"; request.Headers.Add("Authorization", String.Format("Bearer {0}", accessToken)); using (Stream requestStream = request.GetRequestStream()) requestStream.Write(contentInBytes, 0, contentInBytes.Length); using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse()) { string error = webResponse.Headers["X-WNS-Error-Description"]; resultText = webResponse.StatusCode.ToString() + " | " + webResponse.Headers["X-WNS-NotificationStatus"]; if (!string.IsNullOrEmpty(error)) { resultText += " | " + error; } } } catch (WebException webException) { string exceptionDetails = webException.Response.Headers["WWW-Authenticate"]; if (exceptionDetails != null && exceptionDetails.Contains("Token expired")) { //Tocken expired, rinnovare il tocken e riprovare invio returnCode = 100; resultText = "EXCEPTION: Token expired"; } else { //Errore chiamata returnCode = 101; // Log the response resultText = "EXCEPTION: " + webException.Message; } } catch (Exception ex) { //Errore generico returnCode = 199; resultText = "EXCEPTION: " + ex.Message; } //infoInde = resultText; infoInde = new com.progamma.IDVariant(); infoInde.set(new com.progamma.IDVariant(resultText)); return(returnCode); }