Esempio n. 1
0
        public async Task <NotificationResultEN> PushTopupRequestIOs(string pPersonEmail, string pNickname, string pRequester, string pAmount, string pFirstName)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "IOS";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Constants.OneSignalURL);
                client.DefaultRequestHeaders.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_YVR_IOS);
                string url = string.Format("/api/v1/notifications");

                var filter = new
                {
                    field    = "tag",
                    key      = "userid",
                    relation = "=",
                    value    = pPersonEmail
                };
                var notificationContent = new
                {
                    app_id            = Constants.APPID_ONESIGNAL_YVR_IOS,
                    headings          = new { en = "¡Nueva solicitud de recarga!" },
                    contents          = new { en = String.Format("Hola {0}, {1} te ha pedido una recarga de {2} al número {3}. Revisa el listado de solicitudes de recarga.", pFirstName, pNickname, pAmount, pRequester, pAmount) },
                    content_available = true,
                    ios_badgeType     = "Increase",
                    ios_badgeCount    = 1,
                    category          = "",
                    collapse_id       = "",
                    filters           = new object[] { filter }
                };

                var           jsonPost = JsonConvert.SerializeObject(notificationContent);
                StringContent _content = new StringContent(jsonPost, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(url, _content);

                if (response.IsSuccessStatusCode)
                {
                    var result             = response.Content.ReadAsStringAsync().Result;
                    var notificationResult = JsonConvert.DeserializeObject <CreateResultOneSignal>(result);

                    if (notificationResult.errors == null && notificationResult.recipients > 0)
                    {
                        operationResult.CodeResult = "scheduled";
                        operationResult.Result     = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("PushTopupRequest: " + ex.Message);
            }

            return(operationResult);
        }
        public bool SendSMS(string pBody, string pTargetPhone)
        {
            bool result = false;

            try
            {
                TwilioClient.Init(Constants.TwilioAccountID, Constants.TwilioAuthToken);

                var to      = new PhoneNumber(pTargetPhone);
                var message = MessageResource.Create(
                    to,
                    from: new PhoneNumber("+1(305) 697-1696"),
                    body: pBody);

                var smsResult = message.Sid;

                result = (!String.IsNullOrEmpty(smsResult)) ? true : false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("SendSMS: " + ex.Message);
            }

            return(result);
        }
        public async Task <List <NotificationResultEN> > HandleDepositContent(CampaignEN pCampaign, string pUserEmail, string pFirstName, string pContent)
        {
            List <NotificationResultEN> operationResults = new List <NotificationResultEN>();

            try
            {
                var androidOperation = await onesignalClient.PushDepositNotificationAndroid(pCampaign, pUserEmail, pFirstName, pContent);

                var iosOperation = await onesignalClient.PushDepositNotificationIOs(pCampaign, pUserEmail, pFirstName, pContent);

                //var engagementOperation = await engagementClient.PushDepositNotification(pCampaign, pUserEmail, pFirstName, pContent);

                operationResults.Add(androidOperation);
                operationResults.Add(iosOperation);
                //operationResults.Add(engagementOperation);
            }
            catch (Exception ex)
            {
                operationResults = null;
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("HandleDepositContent: " + ex.Message);
            }

            return(operationResults);
        }
Esempio n. 4
0
        public async Task <NotificationResultEN> PushDepositNotificationAndroid(CampaignEN pCampaign, string pUserEmail, string pFirstName, string pContent)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Constants.OneSignalURL);
                client.DefaultRequestHeaders.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_YVR_ANDROID);
                string url = string.Format("/api/v1/notifications");


                OneSignalFilter filter = new OneSignalFilter();
                filter.field    = "tag";
                filter.key      = "userid";
                filter.relation = "=";
                filter.value    = (!SingleTestModeActive()) ? pUserEmail : ConfigurationManager.AppSettings["OneSignal_SingleUserTest_Android"].ToString();


                var notificationContent = new
                {
                    app_id      = Constants.APPID_ONESIGNAL_YVR_ANDROID,
                    headings    = new { en = pCampaign.NotificationTitle },
                    contents    = new { en = String.Format("Hola {0}. {1}", pFirstName, pContent) },
                    category    = "",
                    collapse_id = "",
                    filters     = new object[] { filter }
                };

                var           jsonPost = JsonConvert.SerializeObject(notificationContent);
                StringContent _content = new StringContent(jsonPost, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(url, _content);

                if (response.IsSuccessStatusCode)
                {
                    var result             = response.Content.ReadAsStringAsync().Result;
                    var notificationResult = JsonConvert.DeserializeObject <CreateResultOneSignal>(result);

                    if (notificationResult.errors == null && notificationResult.recipients > 0)
                    {
                        operationResult.CodeResult = "scheduled";
                        operationResult.Result     = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("PushDepositNotification: " + ex.Message);
            }

            return(operationResult);
        }
Esempio n. 5
0
        public bool SendSMS(string pBody, string pTargetPhone)
        {
            bool result = false;

            try
            {
                // API Key
                string key = ConfigurationManager.AppSettings["keynotificame"].ToString();

                // API Secret
                string secret = ConfigurationManager.AppSettings["secretnotificame"].ToString();

                // API Url
                string url = "https://notificame.claro.com.sv/api/rest/"; /* ej: http://<url>/api/ */

                sdk = new SmsApi(key, secret, url);

                Random id = new Random();

                var smsResult = sdk.Messages.SendToContact(pTargetPhone, pBody, id.Next().ToString());

                if (smsResult.ErrorCode == 200 || smsResult.ErrorCode == 50000 || smsResult.ErrorCode == 50001 || smsResult.ErrorCode == 503)
                {
                    result = true;
                }
                else
                {
                    result = false;
                }



                result = (!String.IsNullOrEmpty(smsResult.ToString())) ? true : false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("SendSMS: " + ex.Message);
            }

            return(result);
        }
        public String GetLocationByIpAddress(string pIpAddress)
        {
            string address = "";

            try
            {
                string requestURL = ConfigurationManager.AppSettings["IpLocationUrl"].ToString() + pIpAddress;

                WebRequest request = WebRequest.Create(requestURL);

                //Response
                WebResponse  response   = request.GetResponse();
                Stream       dataStream = response.GetResponseStream();
                StreamReader reader     = new StreamReader(dataStream);

                string responseStr = reader.ReadToEnd();

                var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                var jsonObject = serializer.Deserialize <Dictionary <string, string> >(responseStr);

                string city         = jsonObject["city"];
                string region_name  = jsonObject["region_name"];
                string country_name = jsonObject["country_name"];


                if (city != "" && region_name != "" && country_name != "")
                {
                    address = city + ", " + region_name + " - " + country_name;
                }

                reader.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("GetLocationByIpAddress: " + ex.Message);
            }

            return(address);
        }
        private StreamReader RequestLocation(string pUrl)
        {
            StreamReader reader = null;

            try
            {
                WebRequest request = WebRequest.Create(pUrl);

                //Response
                WebResponse response   = request.GetResponse();
                Stream      dataStream = response.GetResponseStream();
                reader = new StreamReader(dataStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("RequestLocation: " + ex.Message);
            }

            return(reader);
        }
Esempio n. 8
0
        public async Task <NotificationResultEN> CreateMassiveCampaignAndroidRGO(CampaignEN pCampaignContent)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Constants.OneSignalURL);
                client.DefaultRequestHeaders.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_RGO_ANDROID); //antes era OneSignalKey_Android_Yvr //TODO: REcomendacion: Cambiar nombre a RG!
                string url = string.Format("/api/v1/notifications");

                OneSignalFilter filter = new OneSignalFilter();

                if (RecarGOMassiveTestModeActive())
                {
                    filter.field    = "tag";
                    filter.key      = "userid";
                    filter.relation = "=";
                    filter.value    = ConfigurationManager.AppSettings["OneSignal_SingleUserTest_RGO_Android"].ToString();
                }
                else
                {
                    filter.field = "country";
                    filter.value = pCampaignContent.CountryISO2Code;
                }

                var notificationContent = new
                {
                    app_id      = Constants.APPID_ONESIGNAL_RGO_ANDROID,
                    headings    = new { en = pCampaignContent.NotificationTitle },
                    contents    = new { en = pCampaignContent.NotificationMessage },
                    big_picture = (pCampaignContent.ImageURL != null) ? pCampaignContent.ImageURL : null,
                    category    = "",
                    collapse_id = "",
                    filters     = new object[] { filter }
                };


                var           jsonPost = JsonConvert.SerializeObject(notificationContent);
                StringContent _content = new StringContent(jsonPost, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(url, _content);

                if (response.IsSuccessStatusCode)
                {
                    var result             = response.Content.ReadAsStringAsync().Result;
                    var notificationResult = JsonConvert.DeserializeObject <CreateResultOneSignal>(result);

                    if (notificationResult.errors == null)
                    {
                        operationResult.CodeResult = "scheduled";
                        operationResult.Result     = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("CreateMassiveCampaign: " + ex.Message);
            }
            return(operationResult);
        }
Esempio n. 9
0
        //------------------------ANDROID
        #region Android
        public NotificationResultEN PushSingleUserAndroid(string pTitle, string pMessage, string pImageURL, string pUserID)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            var request = WebRequest.Create(Constants.OneSignalNotifications) as HttpWebRequest;

            request.KeepAlive   = true;
            request.Method      = "POST";
            request.ContentType = "application/json; charset=utf-8";

            request.Headers.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_RGO_ANDROID);

            var serializer = new JavaScriptSerializer();
            var filter     = new
            {
                field    = "tag",
                key      = "userid",
                relation = "=",
                value    = pUserID
            };
            var notificationContent = new
            {
                app_id            = Constants.APPID_ONESIGNAL_RGO_ANDROID,
                headings          = new { en = pTitle },
                contents          = new { en = pMessage },
                content_available = true,
                category          = "",
                big_picture       = (pImageURL != null) ? pImageURL : null,
                collapse_id       = "",
                filters           = new object[] { filter }
            };



            var param = serializer.Serialize(notificationContent);

            byte[] byteArray = Encoding.UTF8.GetBytes(param);

            string responseContent = null;

            try
            {
                using (var writer = request.GetRequestStream())
                {
                    writer.Write(byteArray, 0, byteArray.Length);
                }

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    using (var reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseContent = reader.ReadToEnd();
                        var serializedResult = serializer.Deserialize <CreateResultOneSignal>(responseContent);

                        if (serializedResult.errors == null)
                        {
                            operationResult.Result     = true;
                            operationResult.CodeResult = "scheduled";
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                operationResult.Result     = false;
                operationResult.CodeResult = "error";
                Console.WriteLine(ex.InnerException);
                System.Diagnostics.Debug.WriteLine(new StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
                EventViewerLoggerSVC.LogError("PushSingleUserAndroid: " + ex.Message);
            }

            return(operationResult);
        }
Esempio n. 10
0
        public async Task <NotificationResultEN> CreateMassiveCampaignIOs(CampaignEN pCampaignContent)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "IOS";
            operationResult.Result      = false;
            operationResult.ServiceName = "OneSignal";

            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(Constants.OneSignalURL);
                client.DefaultRequestHeaders.Add("authorization", "Basic " + Constants.KEY_ONESIGNAL_YVR_IOS);
                string url = string.Format("/api/v1/notifications");

                #region Target Filter
                OneSignalFilter filter = new OneSignalFilter();

                if (MassiveTestModeActive())
                {
                    filter.field    = "tag";
                    filter.key      = "userid";
                    filter.relation = "=";
                    filter.value    = ConfigurationManager.AppSettings["OneSignal_SingleUserTest"].ToString();
                }
                else
                {
                    filter.field = "country";
                    filter.value = pCampaignContent.CountryISO2Code;
                }
                #endregion

                var attachment = new
                {
                    id = (pCampaignContent.ImageURL != null) ? pCampaignContent.ImageURL : null
                };

                var notificationContent = new
                {
                    app_id            = Constants.APPID_ONESIGNAL_YVR_IOS,
                    headings          = new { en = pCampaignContent.NotificationTitle },
                    contents          = new { en = pCampaignContent.NotificationMessage },
                    content_available = true,
                    ios_badgeType     = "Increase",
                    ios_badgeCount    = 1,
                    category          = "",
                    collapse_id       = "",
                    ios_attachments   = (pCampaignContent.ImageURL != null) ? attachment : null,
                    filters           = new object[] { filter }
                };



                var           jsonPost = JsonConvert.SerializeObject(notificationContent);
                StringContent _content = new StringContent(jsonPost, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(url, _content);

                if (response.IsSuccessStatusCode)
                {
                    var result             = response.Content.ReadAsStringAsync().Result;
                    var notificationResult = JsonConvert.DeserializeObject <CreateResultOneSignal>(result);

                    if (notificationResult.errors == null)
                    {
                        operationResult.CodeResult = "scheduled";
                        operationResult.Result     = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("CreateMassiveCampaign: " + ex.Message);
            }

            return(operationResult);
        }
Esempio n. 11
0
        public async Task <NotificationResultEN> CreateMassiveCampaign(CampaignEN pCampaignContent)
        {
            NotificationResultEN operationResult = new NotificationResultEN();

            operationResult.Platform    = "ANDROID";
            operationResult.Result      = false;
            operationResult.ServiceName = "Engagement";

            int engagementCampaignID = 0;

            try
            {
                var credentials = await ApplicationTokenProvider.LoginSilentAsync(Constants.TENANT_ID, Constants.CLIENT_ID, Constants.CLIENT_SECRET);

                engagementClient = new EngagementManagementClient(credentials)
                {
                    SubscriptionId = Constants.SUBSCRIPTION_ID
                };

                engagementClient.ResourceGroupName = Constants.RESOURCE_GROUP;
                engagementClient.AppCollection     = Constants.APP_COLLECTION_NAME;
                engagementClient.AppName           = Constants.APP_RESOURCE_NAME_ANDROID;

                #region Campaign Audience
                //Campaign audience
                CampaignAudience audience = new CampaignAudience();

                if (YVRMassiveTestModeActive())
                {
                    string userTest = ConfigurationManager.AppSettings["Engagement_SingleUserTest"].ToString();

                    Dictionary <string, Criterion> stringTagCriteria = new Dictionary <string, Criterion>();
                    stringTagCriteria.Add("StringTag", new StringTagCriterion("userid", userTest));
                    audience.Expression = "StringTag";
                    audience.Criteria   = stringTagCriteria;
                }
                else
                {
                    Dictionary <string, Criterion> locationCriteria = new Dictionary <string, Criterion>();
                    locationCriteria.Add("CarrierCountry", new CarrierCountryCriterion(pCampaignContent.CountryISO2Code));
                    audience.Expression = "CarrierCountry";
                    audience.Criteria   = locationCriteria;
                }
                #endregion

                NotificationOptions notificationOptions = new NotificationOptions();
                notificationOptions.BigPicture = (pCampaignContent.ImageURL != null) ? pCampaignContent.ImageURL : null;


                Campaign campaigne = new Campaign(
                    name: pCampaignContent.Title,
                    notificationTitle: pCampaignContent.NotificationTitle,
                    notificationMessage: pCampaignContent.NotificationMessage,
                    type: "text/plain",
                    deliveryTime: "any",
                    notificationType: "system",
                    pushMode: "one-shot",
                    title: pCampaignContent.NotificationTitle,
                    body: pCampaignContent.NotificationMessage,
                    actionButtonText: "ACEPTAR",
                    notificationOptions: (pCampaignContent.ImageURL != null) ? notificationOptions : null, //If imageURL is null or empty, sets an object's null value
                    audience: audience);

                CampaignStateResult campaignResultState = await engagementClient.Campaigns.CreateAsync(CampaignKinds.Announcements, campaigne);

                if (String.Equals(campaignResultState.State, "draft"))
                {
                    engagementCampaignID = campaignResultState.Id;

                    var campaignStatus = await engagementClient.Campaigns.ActivateAsync(CampaignKinds.Announcements, engagementCampaignID);

                    operationResult.CodeResult = campaignStatus.State;

                    if (!String.Equals(campaignStatus.State, "scheduled") || !String.Equals(campaignStatus.State, "in-progress"))
                    {
                        operationResult.Result = true;
                    }
                }
            }
            catch (ApiErrorException apiEx)
            {
                if (String.Equals(apiEx.Body.Error.Code, "Conflict"))
                {
                    operationResult.CodeResult = "conflict";
                }

                EventViewerLoggerSVC.LogError("CreateMassiveCampaign: " + apiEx.Message);
            }
            catch (Exception ex)
            {
                operationResult.CodeResult = "error";
                Console.WriteLine(ex.InnerException);
                EventViewerLoggerSVC.LogError("CreateMassiveCampaign: " + ex.Message);
            }

            return(operationResult);
        }