public DAL.App.DTO.Notification AddNewNotification(DAL.App.DTO.Notification notification)
        {
            var domainNotification = NotificationMapper.MapToDomain(notification);
            var addedNotification  = RepoDbSet.Add(domainNotification).Entity;

            return(NotificationMapper.Map(addedNotification));
        }
Esempio n. 2
0
        public IActionResult Edit(int id)
        {
            var not = _dbContext.Notifications
                      .Find(id);

            var nots = _dbContext.Notifications
                       .Where(n => n.IsMuted == false)
                       .OrderBy(a => a.Date);

            List <NotificationInfoViewModel> notIVM = new List <NotificationInfoViewModel>();

            foreach (var item in nots)
            {
                notIVM.Add(NotificationMapper.Mapping(item));
            }

            NotificationViewModel model = new NotificationViewModel()
            {
                Notifications = notIVM,
                Id            = not.Id,
                FirstName     = not.FirstName,
                LastName      = not.LastName,
                Email         = not.Email,
                Phone1        = not.Phone1,
                Phone2        = not.Phone2,
                Date          = not.Date,
                Technology    = not.Technology
            };

            return(View("Index", model));
        }
Esempio n. 3
0
        public NotificationMapperTest()
        {
            _referenceDataRepositoryMock.Setup(repo => repo.GetTbServiceFromHospitalIdAsync(It.IsAny <Guid>()))
            .Returns((Guid guid) => Task.FromResult(_hospitalToTbServiceCodeDict[guid]));
            _referenceDataRepositoryMock.Setup(repo =>
                                               repo.GetTreatmentOutcomeForTypeAndSubType(
                                                   TreatmentOutcomeType.Died,
                                                   TreatmentOutcomeSubType.Unknown))
            .ReturnsAsync(new TreatmentOutcome
            {
                TreatmentOutcomeType    = TreatmentOutcomeType.Died,
                TreatmentOutcomeSubType = TreatmentOutcomeSubType.Unknown
            });
            _postcodeService.Setup(service => service.FindPostcodeAsync(It.IsAny <string>()))
            .ReturnsAsync((string postcode) => new PostcodeLookup {
                Postcode = postcode.Replace(" ", "").ToUpper()
            });

            // Needs to happen after the mocking, as the constructor uses a method from reference data repo
            var importLogger = new ImportLogger();

            _notificationMapper = new NotificationMapper(
                _migrationRepository,
                _referenceDataRepositoryMock.Object,
                importLogger,
                _postcodeService.Object);
            _importValidator = new ImportValidator(importLogger, _referenceDataRepositoryMock.Object);
        }
        Nancy.Response UpdateNotification(string id)
        {
            NotificationModel notification = null;

            // capture actual string posted in case the bind fails (as it will if the JSON is bad)
            // need to do it now as the bind operation will remove the data
            String rawBody = this.GetRawBody();

            try {
                notification = this.Bind <NotificationModel>();

                NotificationMapper not_mpr = new NotificationMapper();
                notification.Id = id;

                NotificationModel res = not_mpr.GetById(id);

                if (res == null)
                {
                    return(ErrorBuilder.ErrorResponse(this.Request.Url.ToString(), "GET", HttpStatusCode.NotFound, String.Format("A notification with Id = {0} does not exist", id)));
                }
                not_mpr.update(notification);

                Nancy.Response response = Response.AsJson(notification);
                response.StatusCode = HttpStatusCode.OK;

                string uri = this.Request.Url.SiteBase + this.Request.Path + "/" + notification.Id;
                response.Headers["Location"] = uri;

                return(response);
            } catch (Exception e) {
                String operation = String.Format("NotificationModule.UpdateBadge({0})", (notification == null) ? "No Model Data" : notification.Message);
                return(HandleException(e, operation));
            }
        }
        Nancy.Response AddNotification()
        {
            // capture actual string posted in case the bind fails (as it will if the JSON is bad)
            // need to do it now as the bind operation will remove the data
            String rawBody = this.GetRawBody();

            NotificationModel notification = this.Bind <NotificationModel>();

            // Reject request with an ID param
            if (notification.Id != null)
            {
                return(ErrorBuilder.ErrorResponse(this.Request.Url.ToString(), "POST", HttpStatusCode.Conflict, String.Format("Use PUT to update an existing notification with Id = {0}", notification.Id)));
            }

            // Save the item to the DB
            try {
                NotificationMapper not_mpr = new NotificationMapper();
                notification.CreateId();
                not_mpr.Add(notification);
                Nancy.Response response = Response.AsJson(notification);
                response.StatusCode = HttpStatusCode.Created;

                string uri = this.Request.Url.SiteBase + this.Request.Path + "/" + notification.Id;
                response.Headers["Location"] = uri;

                return(response);
            } catch (Exception e) {
                Console.WriteLine(rawBody);
                String operation = String.Format("NotificationModule.AddItem({0})", (notification == null) ? "No Model Data" : notification.Message);
                return(HandleException(e, operation));
            }
        }
        public async Task <DAL.App.DTO.Notification> FindByTrainingAndUserId(Guid userId, Guid trainingId)
        {
            var notification = RepoDbSet.AsQueryable()
                               .Where(n => n.AppUserId == userId && n.TrainingId == trainingId)
                               .FirstOrDefaultAsync();

            return(NotificationMapper.Map(await notification));
        }
        public async Task <DAL.App.DTO.Notification> UpdateNotification(DAL.App.DTO.Notification notification)
        {
            var domain = await RepoDbSet.FindAsync(notification.Id);

            domain.Recived = true;
            var addedNotification = RepoDbSet.Update(domain).Entity;

            return(NotificationMapper.Map(addedNotification));
        }
Esempio n. 8
0
        public ActionResult AddNotification([FromBody] NotificationModel notification)
        {
            _logger.LogInformation("Adding a new Notification");

            notification.CreatedOn = DateTime.UtcNow;
            var notificationData = NotificationMapper.SerializeNotification(notification);
            var newNotification  = _notificationService.CreateNotification(notificationData);

            return(Ok(newNotification));
        }
        public async Task <DTO.Notification> FirstOrDefaultAsync(Guid id, Guid?userId = null)
        {
            var query = RepoDbSet.Where(a => a.Id == id).AsQueryable();

            if (userId != null)
            {
                query = query.Where(a => a.AppUserId == userId);
            }

            return(NotificationMapper.Map(await query.FirstOrDefaultAsync()));
        }
Esempio n. 10
0
        private void Notify(WebSocketConnectionBase connection, DeviceNotification notification, Device device)
        {
            var user = (User)connection.Session["user"];

            if (user == null || !IsNetworkAccessible(device.NetworkID, user))
            {
                return;
            }

            connection.SendResponse("notification/insert",
                                    new JProperty("deviceGuid", device.GUID),
                                    new JProperty("notification", NotificationMapper.Map(notification)));
        }
        /// <summary>
        /// Registers all the notifications that are provided by the current application.
        /// </summary>
        public void RegisterProvidedNotifications()
        {
            var instance = m_Context.Resolve <TestNotifications>();

            var map = NotificationMapper <ITestNotificationSet> .Create();

            instance.OnNotify += map.From(t => t.OnNotify += null)
                                 .GenerateHandler();

            var collection = m_Context.Resolve <RegisterNotification>();

            collection(map.ToMap(), m_Subjects.Select(s => new SubjectGroupIdentifier(s, new Version(1, 0), "a")).ToArray());
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            SuggestionMapper.Map(modelBuilder);
            SuggestionVoteMapper.Map(modelBuilder);
            SuggestionCommentMapper.Map(modelBuilder);

            ItemMapper.Map(modelBuilder);
            ItemPropertyMapper.Map(modelBuilder);

            NotificationMapper.Map(modelBuilder);

            UserMapper.Map(modelBuilder);
            UserNotificationSettingMapper.Map(modelBuilder);
            UserNotificationMapper.Map(modelBuilder);
        }
        public void RenderMyNotifications(object sender, OpenReadCompletedEventArgs e)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(NotificationType[]));

            NotificationType[] notifications = serializer.ReadObject(e.Result) as NotificationType[];
            EnumMapper         mapper        = new EnumMapper("NotificationMappings.map");

            NotificationCollection.Clear();
            foreach (NotificationType type in notifications)
            {
                NotificationMapper.SetNotificationMessageForNotification(type, (NotificationEnum.Notifications)mapper.GetMappedValue(type.RawType));
                NotificationCollection.Add(type);
            }
            IsLoading = false;
            Visible   = "Collapsed";
        }
        public async Task <NotificationFilterDto> SearchNotifications(NotificationFilterDto model)
        {
            var expression = GetSearchExpressionNotifications(model);

            (var query, int totalCount) = await AuditUnitOfWork.NotificationRepository.GetPagedByFiltersAsync(
                model.PageNumber,
                model.jtPageSize.Value,
                expression,
                a => a.OrderByDescending(d => d.Date));

            model.Items = query.Select(notification => NotificationMapper.MapToDto(notification)).ToList();

            model.TotalCount = totalCount;

            return(model);
        }
        Nancy.Response DeleteNotification(string id)
        {
            try {
                NotificationMapper not_mpr      = new NotificationMapper();
                NotificationModel  notification = not_mpr.GetById(id);

                if (notification == null)
                {
                    return(ErrorBuilder.ErrorResponse(this.Request.Url.ToString(), "GET", HttpStatusCode.NotFound, String.Format("A notification with Id = {0} does not exist", id)));
                }

                not_mpr.delete(notification);

                return(HttpStatusCode.OK);
            } catch (Exception e) {
                return(HandleException(e, String.Format("\nNotificationModule.Delete({0})", id)));
            }
        }
Esempio n. 16
0
        public void InsertDeviceNotification(JObject notification)
        {
            if (notification == null)
            {
                throw new WebSocketRequestException("Please specify notification");
            }

            var notificationEntity = NotificationMapper.Map(notification);

            notificationEntity.Device = CurrentDevice;
            Validate(notificationEntity);

            DataContext.DeviceNotification.Save(notificationEntity);
            _messageManager.ProcessNotification(notificationEntity);
            _messageBus.Notify(new DeviceNotificationAddedMessage(CurrentDevice.ID, notificationEntity.ID));

            notification = NotificationMapper.Map(notificationEntity);
            SendResponse(new JProperty("notification", notification));
        }
Esempio n. 17
0
        public IActionResult Index()
        {
            var not = _dbContext.Notifications
                      .Where(n => n.IsMuted == false)
                      .OrderByDescending(a => a.Date);

            List <NotificationInfoViewModel> notIVM = new List <NotificationInfoViewModel>();

            foreach (var item in not)
            {
                notIVM.Add(NotificationMapper.Mapping(item));
            }

            NotificationViewModel model = new NotificationViewModel()
            {
                Notifications = notIVM,
                Date          = DateTime.Now
            };

            return(View(model));
        }
Esempio n. 18
0
        public NotificationMapperTest()
        {
            _caseManagerImportService
            .Setup(serv => serv.ImportOrUpdateLegacyUser(It.IsAny <string>(), It.IsAny <PerformContext>(), It.IsAny <int>()))
            .Returns(() => Task.CompletedTask);
            _referenceDataRepositoryMock.Setup(repo => repo.GetUserByUsernameAsync(It.IsAny <string>()))
            .Returns((string username) => Task.FromResult(_usernameToUserDict[username]));
            _referenceDataRepositoryMock.Setup(repo => repo.GetTbServiceFromHospitalIdAsync(It.IsAny <Guid>()))
            .Returns((Guid guid) => Task.FromResult(_hospitalToTbServiceCodeDict[guid]));
            _referenceDataRepositoryMock.Setup(repo => repo.GetAllTbServicesAsync())
            .Returns(() => Task.FromResult <IList <TBService> >(new List <TBService> {
                new TBService {
                    Code = WestonGeneralCode, PHECCode = PhecResult
                }
            }));
            _referenceDataRepositoryMock.Setup(repo =>
                                               repo.GetAllTreatmentOutcomes())
            .ReturnsAsync(ntbs_service.Models.SeedData.TreatmentOutcomes.GetTreatmentOutcomes().ToList);
            _referenceDataRepositoryMock.Setup(repo =>
                                               repo.GetTreatmentOutcomeForTypeAndSubType(It.IsAny <TreatmentOutcomeType>(), It.IsAny <TreatmentOutcomeSubType>()))
            .ReturnsAsync(ntbs_service.Models.SeedData.TreatmentOutcomes.GetTreatmentOutcomes()
                          .FirstOrDefault(o => o.TreatmentOutcomeType == TreatmentOutcomeType.Died && o.TreatmentOutcomeSubType == TreatmentOutcomeSubType.Unknown));
            _postcodeService.Setup(service => service.FindPostcodeAsync(It.IsAny <string>()))
            .ReturnsAsync((string postcode) => new PostcodeLookup {
                Postcode = postcode.Replace(" ", "").ToUpper()
            });

            // Needs to happen after the mocking, as the constructor uses a method from reference data repo
            _treatmentEventMapper =
                new TreatmentEventMapper(_caseManagerImportService.Object, _referenceDataRepositoryMock.Object);
            _notificationMapper = new NotificationMapper(
                _migrationRepository,
                _referenceDataRepositoryMock.Object,
                _importLoggerMock.Object,
                _postcodeService.Object,
                _caseManagerImportService.Object,
                _treatmentEventMapper);
            _importValidator = new ImportValidator(_importLoggerMock.Object, _referenceDataRepositoryMock.Object);
        }
        private object GetById(string id)
        {
            try
            {
                // create a connection to the PetaPoco orm and try to fetch and object with the given Id
                NotificationMapper not_mpr      = new NotificationMapper();
                NotificationModel  notification = not_mpr.GetById(id);

                if (notification == null)     // a null return means no object found
                // return a reponse conforming to REST conventions: a 404 error
                {
                    return(ErrorBuilder.ErrorResponse(this.Request.Url.ToString(), "GET", HttpStatusCode.NotFound, String.Format("A notification with Id = {0} does not exist", id)));
                }
                else
                {
                    // success. The Nancy server will automatically serialise this to JSON
                    return(Response.AsJson(notification));
                }
            } catch (Exception e) {
                return(HandleException(e, String.Format("NotificationModule.GetById({0})", id)));
            }
        }
        private object GetAll(string target)
        {
            try {
                // Create a connection to the PetaPoco ORM and try to fetch and object with the given Id
                NotificationMapper        not_mpr = new NotificationMapper();
                IList <NotificationModel> res     = null;

                // Get all objects or a filtered list by user
                if (target != null)
                {
                    res = not_mpr.GetByTarget(target);
                }
                else
                {
                    res = not_mpr.Get();
                }

                // Convert this into an array of JSON objects.
                return(Response.AsJson(res));
            } catch (Exception e) {
                return(HandleException(e, String.Format("NotificationModule.GetAll()")));
            }
        }
        /// <inheritdoc />
        /// <summary>
        /// Send Notification
        /// </summary>
        /// <param name="usersIds"></param>
        /// <param name="notification"></param>
        /// <returns></returns>
        public virtual async Task SendNotificationAsync(IEnumerable <Guid> usersIds, Notification notification)
        {
            if (notification == null)
            {
                throw new NullReferenceException();
            }
            try
            {
                var users = usersIds.ToList();
                if (!users.Any())
                {
                    return;
                }
                if (!notification.SendLocal && !notification.SendEmail)
                {
                    return;
                }
                var emails = new HashSet <string>();
                foreach (var userId in users)
                {
                    var user = await _userManager.UserManager.FindByIdAsync(userId.ToString());

                    if (user == null)
                    {
                        continue;
                    }
                    //send email only if email was confirmed
                    if (notification.SendEmail && user.EmailConfirmed)
                    {
                        emails.Add(user.Email);
                    }

                    if (!notification.SendLocal)
                    {
                        continue;
                    }
                    notification.Id     = Guid.NewGuid();
                    notification.UserId = userId;
                    var tenant = await _userManager.IdentityContext.Tenants.FirstOrDefaultAsync(x => x.Id.Equals(user.TenantId));

                    var response = await _dataService.Add <SystemNotifications>(_dataService.GetDictionary(notification), tenant.MachineName);

                    if (!response.IsSuccess)
                    {
                        _logger.LogError("Fail to add new notification in database");
                    }
                }
                if (notification.SendLocal)
                {
                    _hub.SendNotification(users, NotificationMapper.Map(notification));
                }
                if (notification.SendEmail)
                {
                    await _emailSender.SendEmailAsync(emails, notification.Subject, notification.Content);
                }
            }
            catch (Exception e)
            {
                _logger.LogCritical(e.Message);
            }
        }