コード例 #1
0
        private async Task <IActionResult> Post(HttpRequest req)
        {
            // convert Postdata to BeaconDataModel
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            var    param       = JsonConvert.DeserializeObject <NotificationCreateParameter>(requestBody);

            if (string.IsNullOrWhiteSpace(param.Title) || string.IsNullOrWhiteSpace(param.Message))
            {
                return(new BadRequestObjectResult("Title or Message is missing"));
            }

            var now             = DateTime.UtcNow;
            var newNotification = new NotificationMessageModel();

            newNotification.Title   = param.Title;
            newNotification.Message = param.Message;
            newNotification.Created = now;
            newNotification.id      = Guid.NewGuid().ToString("N");
            var createResult = await Cosmos.Notification.CreateItemAsync(newNotification);

            var result = new NotificationCreateResult()
            {
                Message = createResult.Resource
            };

            return(new OkObjectResult(result));
        }
コード例 #2
0
        private static void SendPushNotificationUsingCSharpSDk()
        {
            NotificationCreateResult result = null;

            var client = new OneSignalClient("M2QwNDM1NTktNjc2Yi00OWY1LTg5ZjYtZjlhNzE2ZjJjMGFm");

            var options = new NotificationCreateOptions();

            options.AppId = new Guid("9423ab70-f216-4a77-a364-cdf74f40e4fb");
            //options.IncludedSegments = new List<string> { "All" };
            options.Contents.Add(LanguageCodes.English, "Hello world!");
            options.Headings.Add(LanguageCodes.English, "Hello!");
            options.IncludePlayerIds = new List <string> {
                "17135056-a51d-4b45-bc7c-731b4b3a79eb", "82828ec2-7a9b-46c6-a781-ab07fb2a5998"
            };
            options.Data = new Dictionary <string, string>();
            options.Data.Add("notificationType", "SimpleTextMessage");
            options.Data.Add("messageId", "03c2de5a-d08b-4b32-9723-d17034a64305");
            options.AndroidLedColor    = "FF0000FF";
            options.IosBadgeType       = IosBadgeTypeEnum.SetTo;
            options.IosBadgeCount      = 10;
            options.AndroidAccentColor = "FFFF0000";
            options.Priority           = 10;
            options.DeliverToAndroid   = false;
            try
            {
                result = client.Notifications.Create(options);
            }
            catch (Exception ex)
            {
            }
        }
コード例 #3
0
        public IPushOutput Send(IPushInput input)
        {
            OneSignalOutPut           oneSignalOutPut = new OneSignalOutPut();
            OneSignalInformation      information     = CreateInformation();
            OneSignalClient           client          = new OneSignalClient(information.ApiKey);
            NotificationCreateOptions options         = new NotificationCreateOptions
            {
                AppId = new Guid(information.AppId)
            };

            if (!string.IsNullOrEmpty(input.SubTitle))
            {
                options.Subtitle.Add(LanguageCodes.English, input.SubTitle);
            }
            options.Priority = input.Priority;
            options.Headings.Add(LanguageCodes.English, input.Title);
            options.IncludePlayerIds.Add(input.To);
            options.Contents.Add(LanguageCodes.English, input.Message);
            NotificationCreateResult result = client.Notifications.Create(options);

            if (result.Recipients == 3)
            {
                oneSignalOutPut.IsSuccess = true;
            }
            oneSignalOutPut.Message = $"{result.Id}-{result.Recipients}";
            return(oneSignalOutPut);
        }
コード例 #4
0
        public void PropertiesTest()
        {
            // preparation
            var model = new NotificationCreateResult();

            // model property access
            Helper.ModelTestHelper.PropetiesTest(model);
        }
コード例 #5
0
        public static async Task <string> OneSignalPushNotification(CreateNotificationModel request, Guid appId, string restKey)
        {
            OneSignalClient client = new OneSignalClient(restKey);
            var             opt    = new NotificationCreateOptions()
            {
                AppId            = appId,
                IncludePlayerIds = request.PlayerIds,
                SendAfter        = DateTime.Now.AddSeconds(10)
            };

            opt.Headings.Add(LanguageCodes.English, request.Title);
            opt.Contents.Add(LanguageCodes.English, request.Content);
            NotificationCreateResult result = await client.Notifications.CreateAsync(opt);

            return(result.Id);
        }
コード例 #6
0
        // Otra forma de hacerlo con el SDK
        public ActionResult Index_SDK()
        {
            var client = new OneSignalClient("Y2Y1MDFlZTktNjk3My00NTAxLWE3OTctYTAyN2ExNDQ1OTE0");

            var options = new OneSignal.CSharp.SDK.Resources.Notifications.NotificationCreateOptions()
            {
                AppId            = Guid.Parse("444ebbf4-2456-48b8-9b03-95bd9df4bb0d"),
                IncludedSegments = new List <string> {
                    "All"
                }
            };

            options.Contents.Add(LanguageCodes.Spanish, "Juan Perez aplicó a tu oferta");

            NotificationCreateResult ret = client.Notifications.Create(options);

            return(View());
        }
        public static async Task <string> OneSignalPushNotification(CreateNotificationModel request, Guid appId, string restKey)
        {
            var client = new OneSignalClient(restKey);
            var opt    = new NotificationCreateOptions()
            {
                AppId            = appId,
                IncludedSegments = new string[] { "Subscribed Users" }
            };

            opt.Headings.Add(LanguageCodes.English, request.Title);
            opt.Contents.Add(LanguageCodes.English, request.Content);

            try
            {
                NotificationCreateResult result = await client.Notifications.CreateAsync(opt);

                return(result.Id);
            }

            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #8
0
 public void CreateMethod()
 {
     // action
     var model = new NotificationCreateResult();
 }
コード例 #9
0
        /// <summary>
        /// Sends the specified communication from the Communication Wizard in Rock.
        /// </summary>
        /// <param name="communication">The communication.</param>
        /// <param name="mediumEntityTypeId">The medium entity type identifier.</param>
        /// <param name="mediumAttributes">The medium attributes.</param>
        /// <exception cref="System.NotImplementedException"></exception>
        public override void Send(Model.Communication communication, int mediumEntityTypeId, Dictionary <string, string> mediumAttributes)
        {
            using (var communicationRockContext = new RockContext())
            {
                // Requery the Communication
                communication = new CommunicationService(communicationRockContext)
                                .Queryable("CreatedByPersonAlias.Person")
                                .FirstOrDefault(c => c.Id == communication.Id);

                bool hasPendingRecipients;
                if (communication != null &&
                    communication.Status == Model.CommunicationStatus.Approved &&
                    (!communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value.CompareTo(RockDateTime.Now) <= 0))
                {
                    var qryRecipients = new CommunicationRecipientService(communicationRockContext).Queryable();
                    hasPendingRecipients = qryRecipients
                                           .Where(r =>
                                                  r.CommunicationId == communication.Id &&
                                                  r.Status == Model.CommunicationRecipientStatus.Pending &&
                                                  r.MediumEntityTypeId.HasValue &&
                                                  r.MediumEntityTypeId.Value == mediumEntityTypeId)
                                           .Any();
                }
                else
                {
                    hasPendingRecipients = false;
                }

                if (hasPendingRecipients)
                {
                    var    currentPerson    = communication.CreatedByPersonAlias?.Person;
                    var    globalAttributes = GlobalAttributesCache.Get();
                    string publicAppRoot    = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                    var    mergeFields      = Lava.LavaHelper.GetCommonMergeFields(null, currentPerson);

                    var personEntityTypeId        = EntityTypeCache.Get("Rock.Model.Person").Id;
                    var communicationEntityTypeId = EntityTypeCache.Get("Rock.Model.Communication").Id;
                    var communicationCategoryId   = CategoryCache.Get(Rock.SystemGuid.Category.HISTORY_PERSON_COMMUNICATIONS.AsGuid(), communicationRockContext).Id;

                    bool recipientFound = true;
                    while (recipientFound)
                    {
                        // make a new rockContext per recipient
                        var recipientRockContext = new RockContext();
                        var recipient            = Model.Communication.GetNextPending(communication.Id, mediumEntityTypeId, recipientRockContext);
                        if (recipient != null)
                        {
                            if (ValidRecipient(recipient, communication.IsBulkCommunication))
                            {
                                if (recipient.PersonAliasId.HasValue)
                                {
                                    try
                                    {
                                        var             mergeObjects = recipient.CommunicationMergeValues(mergeFields);
                                        var             message      = ResolveText(communication.PushMessage, currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);
                                        var             title        = ResolveText(communication.PushTitle, currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);
                                        var             sound        = ResolveText(communication.PushSound, currentPerson, communication.EnabledLavaCommands, mergeObjects, publicAppRoot);
                                        var             data         = ResolveText(communication.PushData, currentPerson, communication.EnabledLavaCommands, mergeFields, publicAppRoot);
                                        var             jsonData     = Newtonsoft.Json.JsonConvert.DeserializeObject <PushData>(data);
                                        var             url          = jsonData.Url;
                                        string          appId        = GetAttributeValue("AppId");
                                        string          restApiKey   = GetAttributeValue("RestAPIKey");
                                        OneSignalClient client       = new OneSignalClient(restApiKey);

                                        var options = new NotificationCreateOptions
                                        {
                                            AppId = new Guid(appId),
                                            IncludeExternalUserIds = new List <string> {
                                                recipient.PersonAliasId.ToString()
                                            }
                                        };

                                        options.Headings.Add(LanguageCodes.English, title);
                                        options.Contents.Add(LanguageCodes.English, message);
                                        options.Url = url;
                                        NotificationCreateResult response = client.Notifications.Create(options);

                                        bool failed = !string.IsNullOrWhiteSpace(response.Error);

                                        var status = failed ? CommunicationRecipientStatus.Failed : CommunicationRecipientStatus.Delivered;

                                        if (failed)
                                        {
                                            recipient.StatusNote = "OneSignal failed to notify devices";
                                        }
                                        else
                                        {
                                            recipient.SendDateTime = RockDateTime.Now;
                                        }

                                        recipient.Status = status;
                                        recipient.TransportEntityTypeName = this.GetType().FullName;
                                        recipient.UniqueMessageId         = response.Id;

                                        try
                                        {
                                            var historyService = new HistoryService(recipientRockContext);
                                            historyService.Add(new History
                                            {
                                                CreatedByPersonAliasId = communication.SenderPersonAliasId,
                                                EntityTypeId           = personEntityTypeId,
                                                CategoryId             = communicationCategoryId,
                                                EntityId            = recipient.PersonAlias.PersonId,
                                                Verb                = History.HistoryVerb.Sent.ConvertToString().ToUpper(),
                                                ChangeType          = History.HistoryChangeType.Record.ToString(),
                                                ValueName           = "Push Notification",
                                                Caption             = message.Truncate(200),
                                                RelatedEntityTypeId = communicationEntityTypeId,
                                                RelatedEntityId     = communication.Id
                                            });
                                        }
                                        catch (Exception ex)
                                        {
                                            ExceptionLogService.LogException(ex, null);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        recipient.Status     = CommunicationRecipientStatus.Failed;
                                        recipient.StatusNote = "OneSignal Exception: " + ex.Message;
                                    }
                                }
                            }

                            recipientRockContext.SaveChanges();
                        }
                        else
                        {
                            recipientFound = false;
                        }
                    }
                }
            }
        }