Ejemplo n.º 1
0
        async void _userManager_UserCreated(object sender, GenericEventArgs <User> e)
        {
            var notification = new NotificationRequest
            {
                UserIds = new List <string> {
                    e.Argument.Id.ToString("N")
                },
                Name        = "Welcome to Media Browser!",
                Description = "Check back here for more notifications."
            };

            await SendNotification(notification).ConfigureAwait(false);
        }
Ejemplo n.º 2
0
        async void _deviceManager_CameraImageUploaded(object sender, GenericEventArgs <CameraImageUploadInfo> e)
        {
            var type = NotificationType.CameraImageUploaded.ToString();

            var notification = new NotificationRequest
            {
                NotificationType = type
            };

            notification.Variables["DeviceName"] = e.Argument.Device.Name;

            await SendNotification(notification).ConfigureAwait(false);
        }
Ejemplo n.º 3
0
        private void CreateNotification(int handler, NotificationRequest request, AmsAddress target, AmsAddress sender)
        {
            var cycleTime  = TimeSpan.FromMilliseconds(100);
            var disposable = Observable.Timer(TimeSpan.FromMilliseconds(10), cycleTime)
                             .Select(_ => memory.GetData(request.IndexGroup, request.IndexOffset, request.Length))
                             .DistinctUntilChanged(new ByteEqualityComparer())
                             .Select(data => CreateNotificationStream(handler, data))
                             .SelectMany(data => SendNotification(target, sender, data))
                             .Subscribe()
            ;

            Notifications.Add(handler, disposable);
        }
 // This method will remove the NotificationRequest from litedb, returning if the deletion was successful and logging any errors.
 public bool RemoveRequest(NotificationRequest request)
 {
     try
     {
         ILiteCollection <NotificationRequest> collection = db.GetCollection <NotificationRequest>("notification_requests");
         return(collection.Delete(request._id));
     }
     catch (Exception e)
     {
         logger.LogError("Unable to delete document from LiteDB: " + e.Message);
         return(false);
     }
 }
        async void _userManager_UserLockedOut(object sender, GenericEventArgs <User> e)
        {
            var type = NotificationType.UserLockedOut.ToString();

            var notification = new NotificationRequest
            {
                NotificationType = type
            };

            notification.Variables["UserName"] = e.Argument.Name;

            await SendNotification(notification).ConfigureAwait(false);
        }
Ejemplo n.º 6
0
        public static BillPaymentNotificationResponse BillPaymentNotification(NotificationRequest notificationRequest)
        {
            BillPaymentNotificationResponse notificationResponse = new BillPaymentNotificationResponse();
            ErrorResponse errorResponse = validateCredentials(credentials);
            string        responseCode  = errorResponse.responseCode;

            if (errorResponse.responseCode != "00")
            {
                notificationResponse.responseCode = errorResponse.responseCode;
                notificationResponse.responseMsg  = errorResponse.responseMsg;
                return(notificationResponse);
            }

            if (notificationRequest == null)
            {
                notificationResponse.responseCode = "24";
                notificationResponse.responseMsg  = "Missing Notification Request Object";
                return(notificationResponse);
            }

            var    stringToHash = notificationRequest.rrr + notificationRequest.amountDebitted + notificationRequest.fundingSource + notificationRequest.debittedAccount + notificationRequest.paymentAuthCode + credentials.secretKey;
            string hashed       = SHA512(stringToHash);

            notificationRequest.hash = hashed;

            String jsonNotificationRequest = JsonConvert.SerializeObject(notificationRequest);

            credentials.transactionId = DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString();

            try
            {
                headers.Add(new Header {
                    header = "transactionId", value = credentials.transactionId
                });
                headers.Add(new Header {
                    header = "TXN_HASH", value = notificationRequest.hash
                });
                headers.Add(new Header {
                    header = "secretKey", value = credentials.secretKey
                });
                _header.headers = headers;

                var response = WebClientUtil.PostResponse(credentials.url, RemitaBillerUrl.Notification(), jsonNotificationRequest, _header);
                notificationResponse = JsonConvert.DeserializeObject <BillPaymentNotificationResponse>(response);
            }
            catch (Exception)
            {
                throw;
            }
            return(notificationResponse);
        }
Ejemplo n.º 7
0
        private void Save()
        {
            using (var context = new MasterDataContext())
            {
                if (!Validate(context))
                {
                    return;
                }

                var existingSupplier = context.Suppliers
                                       .Include(s => s.Contacts)
                                       .FirstOrDefault(s => s.Id == CurrentSupplier.Id);

                if (existingSupplier == null)
                {
                    context.Add(CurrentSupplier);
                }
                else
                {
                    context.Entry(existingSupplier).CurrentValues.SetValues(CurrentSupplier);
                    foreach (var contact in CurrentSupplier.Contacts)
                    {
                        var existingContact = existingSupplier.Contacts
                                              .FirstOrDefault(c => c.Id == contact.Id);

                        if (existingContact == null)
                        {
                            existingSupplier.Contacts.Add(contact);
                        }
                        else
                        {
                            context.Entry(existingContact).CurrentValues.SetValues(contact);
                        }
                    }

                    foreach (var contact in existingSupplier.Contacts)
                    {
                        if (!CurrentSupplier.Contacts.Any(c => c.Id == contact.Id))
                        {
                            context.Remove(contact);
                        }
                    }
                }

                context.SaveChanges();
                NotificationRequest.Raise(new Notification {
                    Content = "保存成功", Title = "提示"
                });
                IsEdit = true;
            }
        }
Ejemplo n.º 8
0
        private async Task <MessageProcessResponse> OnNotifyProcessAsync(InstanceNotificationMessage arg, CancellationToken stoppingToken)
        {
            if (stoppingToken.IsCancellationRequested)
            {
                using (LogContext.PushProperty("ClassName", this.GetType().FullName))
                    using (LogContext.PushProperty("Source", this.GetType().Name))
                    {
                        _logger.LogError("Cancellation was requested, stopping token.");
                    }

                return(MessageProcessResponse.Abandon);
            }

            using (var scope = _scopeFactory.CreateScope())
            {
                var notificationService = scope.ServiceProvider.GetRequiredService <INotificationService>();

                var notificationRequest = new NotificationRequest
                {
                    Text       = arg.Text,
                    CreatedAt  = arg.CreatedAt,
                    InstanceId = arg.InstanceId
                };

                switch (arg.Type)
                {
                case InstanceNotifyType.Critical:
                    notificationRequest.Type = NotificationType.Error;
                    break;

                case InstanceNotifyType.Error:
                    notificationRequest.Type = NotificationType.Warning;
                    break;

                default:
                    notificationRequest.Type = NotificationType.Info;
                    break;
                }

                var result = await notificationService.CreateEntityAsync(notificationRequest);

                if (result == null)
                {
                    return(MessageProcessResponse.Abandon);
                }
            }

            _logger.LogInformation("Instance Notification Message was created.");

            return(MessageProcessResponse.Complete);
        }
Ejemplo n.º 9
0
        public async Task <Response> SendNotification(
            string urlBase,
            string servicePrefix,
            string controller,
            string tokenType,
            string accessToken,
            string from,
            string to,
            string message)
        {
            try
            {
                var notificationRequest = new NotificationRequest
                {
                    From    = from,
                    To      = to,
                    Message = message,
                };

                var request = JsonConvert.SerializeObject(notificationRequest);
                var content = new StringContent(request, Encoding.UTF8, "application/json");
                var client  = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
                client.BaseAddress = new Uri(urlBase);
                var url      = string.Format("{0}{1}", servicePrefix, controller);
                var response = await client.PostAsync(url, content);

                if (!response.IsSuccessStatusCode)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = response.StatusCode.ToString(),
                    });
                }

                return(new Response
                {
                    IsSuccess = true,
                    Message = "Notification sent.",
                });
            }
            catch (Exception ex)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = ex.Message,
                });
            }
        }
        public async Task <Response> Post(NotificationRequest request, CancellationToken ct)
        {
            T GetModelFromPayload <T>() where T : class
            {
                var json = request.Payload.ToString();

                return(JsonSerializer.Deserialize <T>(json));
            }

            try
            {
                if (!Settings.EnableEmailSending)
                {
                    return(new FailedResponse((int)ResponseFailureCode.EmailSendingDisabled, "Email Sending is disabled."));
                }

                _notification.AdminEmail       = request.AdminEmail;
                _notification.EmailDisplayName = request.EmailDisplayName;
                switch (request.MessageType)
                {
                case MailMesageTypes.TestMail:
                    await _notification.SendTestNotificationAsync();

                    return(new SuccessResponse());

                case MailMesageTypes.NewCommentNotification:
                    var commentPayload = GetModelFromPayload <NewCommentPayload>();
                    _ = Task.Run(async() => await _notification.SendNewCommentNotificationAsync(commentPayload), ct);
                    return(new SuccessResponse());

                case MailMesageTypes.AdminReplyNotification:
                    var replyPayload = GetModelFromPayload <CommentReplyPayload>();
                    _ = Task.Run(async() => await _notification.SendCommentReplyNotificationAsync(replyPayload), ct);
                    return(new SuccessResponse());

                case MailMesageTypes.BeingPinged:
                    var pingPayload = GetModelFromPayload <PingPayload>();
                    _ = Task.Run(async() => await _notification.SendPingNotificationAsync(pingPayload), ct);
                    return(new SuccessResponse());

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, $"Error sending notification for type '{request.MessageType}'. Requested by '{User.Identity.Name}'");
                Response.StatusCode = StatusCodes.Status500InternalServerError;
                return(new FailedResponse((int)ResponseFailureCode.GeneralException, e.Message));
            }
        }
Ejemplo n.º 11
0
 private void ExecutedB(string uri) // GoToModifierProgrammation
 {
     if (Programmation == null)
     {
         NotificationRequest.Raise(new Notification {
             Content = "Choisir un programme", Title = "Notification"
         });
     }
     else
     {
         _regionManager.RequestNavigate("ContentRegion", uri);
         _eventAggregator.GetEvent <PassProgrammationEvent>().Publish(Programmation);
     }
 }
Ejemplo n.º 12
0
        public async Task <IActionResult> Create([FromBody] NotificationRequest notificationRequest)
        {
            try
            {
                var notf = new Notification
                {
                    TitleAr    = notificationRequest.TitleAr,
                    TitleEn    = notificationRequest.TitleEn,
                    BodyAr     = notificationRequest.BodyAr,
                    BodyEn     = notificationRequest.BodyEn,
                    ImageUrl   = notificationRequest.ImageUrl,
                    CreateDate = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss")
                };

                var status = await _notificationService.CreateNotificationAsync(notf);

                if (status == -1)
                {
                    return(Conflict(new ErrorResponse
                    {
                        message = "Dublicate Entry",
                        status = Conflict().StatusCode
                    }));
                }

                if (status == 1)
                {
                    _userNotificationCountService.WhenAddNewNotification();
                    var response = new
                    {
                        message = "Successfully Insert",
                        status  = Ok().StatusCode
                    };
                    return(Ok(response));
                }
                return(NotFound(new ErrorResponse
                {
                    message = "Not Found",
                    status = NotFound().StatusCode
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(new ErrorResponse
                {
                    message = ex.Message,
                    status = BadRequest().StatusCode
                }));
            }
        }
 public void AddNotification(AlertLevel level, string message, string identifer, NotificationRequest notificationCombiner)
 {
     Notification not = new Notification()
     {
         AlertLevel = level,
         Message = new List<string>(new []{message}),
         Identifer = identifer,
         DuplicateNotificationRequest = notificationCombiner
     };
     if (m_dicNotifications.ContainsKey(identifer))
         m_dicNotifications[identifer] = Notification.Combine(m_dicNotifications[identifer], not);
     else
         m_dicNotifications[identifer] = not;
 }
Ejemplo n.º 14
0
        protected virtual List <NotificationMessageContact> BuildTo(NotificationTemplate template,
                                                                    NotificationRequest request)
        {
            Check.NotNullWithBusinessException(request.To, $"Invalid ToAddress for template Id {template.Id}");

            var toList = new List <NotificationMessageContact>();

            foreach (var to in request.To)
            {
                toList.Add(new NotificationMessageContact(to.Name, to.Address));
            }

            return(toList);
        }
        public void RequestGenerics()
        {
            var request        = new NotificationRequest <EventArgsMock>();
            var eventArgs      = new EventArgsMock();
            var requestedEvent =
                Assert.Raises <EventArgsMock>(
                    h => request.Requested += h,
                    h => request.Requested -= h,
                    () => request.Raise(eventArgs));

            Assert.NotNull(requestedEvent);
            Assert.Equal(request, requestedEvent.Sender);
            Assert.Equal(eventArgs, requestedEvent.Arguments);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Criar Preferência de Notificação - Create Notification Preference
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public async Task <HttpStatusCode> CreateNotificationPreference(NotificationRequest body)
        {
            StringContent       stringContent = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
            HttpResponseMessage response      = await Http_Client.HttpClient.PostAsync("assinaturas/v1/users/preferences", stringContent);

            if (!response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();

                WirecardException.WirecardError wirecardException = WirecardException.DeserializeObject(content);
                throw new WirecardException(wirecardException, "HTTP Response Not Success", content, (int)response.StatusCode);
            }
            return(response.StatusCode);
        }
Ejemplo n.º 17
0
 public ViewAViewModel(IEventAggregator eventAggregator)
 {
     _eventAggregator = eventAggregator;
     ShowMessageCommand.Subscribe(() => {
         NotificationRequest.Raise(new Notification
         {
             Title   = "sample",
             Content = "new message"
         });
     });
     ClosingCommand.Subscribe(OnClosing);
     NavigateToViewBCommand.Subscribe(NavigateToViewB);
     Thread.Sleep(500);
 }
Ejemplo n.º 18
0
        async void _appHost_ApplicationUpdated(object sender, GenericEventArgs <PackageVersionInfo> e)
        {
            var type = NotificationType.ApplicationUpdateInstalled.ToString();

            var notification = new NotificationRequest
            {
                NotificationType = type
            };

            notification.Variables["Version"]      = e.Argument.versionStr;
            notification.Variables["ReleaseNotes"] = e.Argument.description;

            await SendNotification(notification).ConfigureAwait(false);
        }
Ejemplo n.º 19
0
        private async Task AddNotification(AddAdminNotification request)
        {
            var notification = new NotificationRequest
            {
                Date        = DateTime.UtcNow,
                Description = request.Description,
                Level       = request.Level,
                Name        = request.Name,
                Url         = request.Url,
                UserIds     = _userManager.Users.Where(i => i.Configuration.IsAdministrator).Select(i => i.Id.ToString("N")).ToList()
            };

            await _notificationManager.SendNotification(notification, CancellationToken.None).ConfigureAwait(false);
        }
 private void ExecutedB(string uri) // ModiferArtiste
 {
     if (Artiste == null)
     {
         NotificationRequest.Raise(new Notification {
             Content = "Choisir un artiste", Title = "Notification"
         });
     }
     else
     {
         _regionManager.RequestNavigate("ContentRegion", uri);
         _eventAggregator.GetEvent <PassArtisteEvent>().Publish(Artiste);
     }
 }
 // This method will add the NotificationRequest to litedb, returning if the insert was successful and logging any errors.
 public bool AddRequest(NotificationRequest request)
 {
     try
     {
         ILiteCollection <NotificationRequest> collection = db.GetCollection <NotificationRequest>("notification_requests");
         collection.Insert(request);
         return(true);
     }
     catch (Exception e)
     {
         logger.LogError("Unable to save document into LiteDB: " + e.Message);
         return(false);
     }
 }
Ejemplo n.º 22
0
        private Task SendNotification(NotificationRequest request,
                                      INotificationService service,
                                      IEnumerable <User> users,
                                      string title,
                                      string description,
                                      CancellationToken cancellationToken)
        {
            users = users.Where(i => IsEnabledForUser(service, i))
                    .ToList();

            var tasks = users.Select(i => SendNotification(request, service, title, description, i, cancellationToken));

            return(Task.WhenAll(tasks));
        }
Ejemplo n.º 23
0
 private void ExecutedA(string uri)
 {
     if (PutScene($"api/Scenes/{Scene.Id}"))
     {
         NotificationRequest.Raise(new Notification {
             Content = "Modifié", Title = "Notification"
         });
         if (uri != null)
         {
             _regionManager.RequestNavigate("ContentRegion", uri);
             _eventAggregator.GetEvent <RefreshEvent>().Publish(true); //Rafrachir la liste
         }
     }
 }
Ejemplo n.º 24
0
        protected virtual NotificationMessageSubject BuildSubject(NotificationTemplate template,
                                                                  NotificationRequest request)
        {
            if (template == null)
            {
                throw new ArgumentNullException(nameof(template));
            }

            return(new NotificationMessageSubject()
            {
                Charset = template.Charset,
                Content = template.Subject
            });
        }
        private Task AddNotification(AddAdminNotification request)
        {
            var notification = new NotificationRequest
            {
                Date        = DateTime.UtcNow,
                Description = request.Description,
                Level       = request.Level,
                Name        = request.Name,
                Url         = request.Url,
                UserIds     = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id.ToString("N")).ToList()
            };

            return(_notificationManager.SendNotification(notification, CancellationToken.None));
        }
Ejemplo n.º 26
0
        private void Button_Clicked(object sender, EventArgs e)
        {
            _tapCount++;

            var list = new List <string>
            {
                typeof(NotificationPage).FullName,
                _tapCount.ToString()
            };

            var serializer             = new ObjectSerializer <List <string> >();
            var serializeReturningData = serializer.SerializeObject(list);

            var request = new NotificationRequest
            {
                NotificationId = 100,
                Title          = "Test",
                Description    = $"Tap Count: {_tapCount}",
                BadgeNumber    = _tapCount,
                ReturningData  = serializeReturningData,
                Android        =
                {
                    IconName = "my_icon",
                    //AutoCancel = false,
                    //Ongoing = true
                },
            };

            // if not specified, default sound will be played.
            if (CustomSoundSwitch.IsToggled)
            {
                request.Sound = Device.RuntimePlatform == Device.Android
                    ? "good_things_happen"
                    : "good_things_happen.aiff";
            }

            // if not specified, notification will show immediately.
            if (UseNotifyTimeSwitch.IsToggled)
            {
                var notifyDateTime = NotifyDatePicker.Date.Add(NotifyTimePicker.Time);
                if (notifyDateTime <= DateTime.Now)
                {
                    notifyDateTime = DateTime.Now.AddSeconds(10);
                }
                request.NotifyTime = notifyDateTime;
            }

            NotificationCenter.Current.Show(request);
        }
Ejemplo n.º 27
0
        /// <inheritdoc />
        public void Show(NotificationRequest notificationRequest)
        {
            try
            {
                if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0) == false)
                {
                    return;
                }

                if (notificationRequest is null)
                {
                    return;
                }

                var userInfoDictionary = new NSMutableDictionary();

                userInfoDictionary.SetValueForKey(
                    string.IsNullOrWhiteSpace(notificationRequest.ReturningData)
                        ? NSString.Empty
                        : new NSString(notificationRequest.ReturningData), NotificationCenter.ExtraReturnDataIos);

                var content = new UNMutableNotificationContent
                {
                    Title    = notificationRequest.Title,
                    Body     = notificationRequest.Description,
                    Badge    = notificationRequest.BadgeNumber,
                    UserInfo = userInfoDictionary,
                    Sound    = UNNotificationSound.Default
                };
                if (string.IsNullOrWhiteSpace(notificationRequest.Sound) == false)
                {
                    content.Sound = UNNotificationSound.GetSound(notificationRequest.Sound);
                }

                var trigger =
                    UNCalendarNotificationTrigger.CreateTrigger(
                        GetNsDateComponentsFromDateTime(notificationRequest.NotifyTime), false);

                _notificationList.Add(notificationRequest.NotificationId.ToString());
                var request = UNNotificationRequest.FromIdentifier(notificationRequest.NotificationId.ToString(),
                                                                   content, trigger);

                UNUserNotificationCenter.Current.AddNotificationRequestAsync(request);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
        async Task <List <Notification> > GetNotificationList()
        {
            List <Notification> result = null;

            if (AppUtils.IsNetwork())
            {
                var request = new NotificationRequest
                {
                    PageNo = 1
                };
                _objProgress = new CustomProgress(this);
                var Authkey = StorageUtils <String> .GetPreferencesValue(DroidConstant.CurrentUser);

                var response = await _INotificationService.GetEventList(request, ServiceType.NotificationService, Authkey);

                _objProgress.DismissDialog();
                if (response != null)
                {
                    if (response.IsSuccess && response.Result != null)
                    {
                        result = response.Result;

                        if (result.Count == 0 && request.PageNo == 1)
                        {
                            AppUtils.ShowToast(this, response.Message);
                        }
                        else
                        {
                            notificatonAdatper.UpdateList(result);
                        }
                    }

                    else
                    {
                        AppUtils.ShowToast(this, response.Message);
                    }
                }
                else
                {
                    AppUtils.ShowToast(this, response.Message);
                }
            }
            else
            {
                AppUtils.ShowToast(this, Resources.GetString(Resource.String.network_error));
                _objProgress.DismissDialog();
            }
            return(result);
        }
        /// <summary>
        /// Handles the notification request.
        /// </summary>
        /// <param name="header">The header.</param>
        /// <param name="request">The request.</param>
        protected override void HandleNotificationRequest(MessageHeader header, NotificationRequest request)
        {
            base.HandleNotificationRequest(header, request);
            EnsureConnection();

            if (_requests.Any(x => x.Request.Uuid.EqualsIgnoreCase(request.Request.Uuid)))
            {
                // TODO: Should this be an error?
            }
            else
            {
                _headers[request.Request.Uuid] = header;
                _requests.Add(request);
            }
        }
Ejemplo n.º 30
0
        public Task Post(AddAdminNotification request)
        {
            // This endpoint really just exists as post of a real with sickbeard
            var notification = new NotificationRequest
            {
                Date        = DateTime.UtcNow,
                Description = request.Description,
                Level       = request.Level,
                Name        = request.Name,
                Url         = request.Url,
                UserIds     = _userManager.Users.Where(i => i.Policy.IsAdministrator).Select(i => i.Id).ToArray()
            };

            return(_notificationManager.SendNotification(notification, CancellationToken.None));
        }
        private void OnSearchForTransactionNuumber()
        {
            PsPlusCashFlow cashFlow = cashFlows.FirstOrDefault(c => c.InvestorCashFlow.PsPlusId == PsPlusTransactionNumber);

            if (cashFlow != null)
            {
                PsPlusCashFlows.MoveCurrentTo(cashFlow);
                return;
            }
            NotificationRequest.Raise(new Notification()
            {
                Title   = ApplicationNames.NotificationTitle,
                Content = $"Ein Cashflow mit der Transaktionsnummer {PsPlusTransactionNumber} wurde nicht gefunden."
            });
        }