Exemple #1
0
        public async Task <IActionResult> AddMarker(Marker marker)
        {
            var list    = _slaMarkerService.GetSlaMarkers().ToList();
            var polygon = PolygonCheckerService.IsInPolygon(list, marker.latitude, marker.longitude);

            if (polygon == true)
            {
                // SignalR event
                var signalNotification = new NotificationDto
                {
                    Title       = "Too many markers!",
                    Description = "You can not create a marker here",
                    Type        = "Notify",
                    CreatedAt   = DateTime.UtcNow.ToString()
                };
                await _hubNotificationContext.Clients.All.SendAsync("GetNewNotification", signalNotification);

                return(Conflict());
            }

            var markerItem = await _repository.AddAsync(marker);

            // SignalR event
            await _hubContext.Clients.All.SendAsync("GetNewMarker", markerItem);

            return(Ok(markerItem));
        }
Exemple #2
0
        public async Task <ProjectUserDto> CreateProjectUserAsync(ProjectUserDto projectUser)
        {
            UserEntity userEntity = await _userStorage.FindAsync(u => u.Id == projectUser.UserId);

            if (userEntity == null)
            {
                throw new ProjectUserException(ExceptionMessage.InvalidUserId);
            }

            ProjectEntity project = await _projectStorage.FindAsync(p => p.Id == projectUser.ProjectId);

            ProjectUserEntity projectUserEntity = _mapper.Map <ProjectUserEntity>(projectUser);

            // if there are currently no members on the project,
            // default first member to project owner
            projectUserEntity.IsOwner = project.ProjectUsers.Count == 0;

            // Remove user if project collaborator exist
            await _projectCollaboratorSuggestionStorage.DeleteAllAsync(pcs => pcs.ProjectId == projectUser.ProjectId && pcs.UserId == projectUser.UserId);

            var createdProjectUser = await _projectUserStorage.CreateAsync(projectUserEntity);

            var createdProjectUserDto = _mapper.Map <ProjectUserDto>(createdProjectUser);

            createdProjectUserDto.Username = userEntity.Username;
            var projectDto = _mapper.Map <ProjectDto>(project);

            var notificationDto = new NotificationDto(createdProjectUserDto.UserId)
            {
                NotificationObject = projectDto
            };
            await _notifier.SendYouJoinedProjectNotificationAsync(notificationDto);

            return(createdProjectUserDto);
        }
        public async void Post([FromBody] PostDto post)
        {
            post.Id = PublishPost(post);
            string fullPicture = null;

            if (post.Full_Picture != null)
            {
                var image = _imgLoader.GetBytes(post.Full_Picture);
                fullPicture = await _imgLoader.SaveFile();
            }

            _dbContext.Posts.Add(new Post()
            {
                Id          = post.Id,
                Message     = post.Message,
                Picture     = fullPicture,
                CreatedDate = DateTime.Now,
                URL         = post.Url
            });
            _dbContext.SaveChanges();


            var notification = new NotificationDto {
                Message = post.Message, Pns = "gcm"
            };
            var notificationResult = await SendNotificationAsync(notification);
        }
Exemple #4
0
 public async void AddNotificationIdsAsync(List <int> userIds, NotificationDto newEntry)
 {
     foreach (int userId in userIds)
     {
         await Task.Run(() => AddNotificationByIdAsync(userId, newEntry));
     }
 }
Exemple #5
0
        public void Initialize()
        {
            _notificationSubscrubedUserMock = new Mock <INotificationSubscribedUserRepository>();
            _notificationRepoMock           = new Mock <INotificationRepository>();
            _validator = new NotificationDtoValidator();

            _hubMock = new Mock <IHubContext <INotificationProxy> >();
            _hubMock.Setup(o => o.Clients.User(It.IsAny <string>()).UpdateNotices(It.IsAny <NotificationDto>()));

            _service      = new NotificationService(_notificationSubscrubedUserMock.Object, _notificationRepoMock.Object, _validator, _hubMock.Object);
            _notification = new Notification()
            {
                CreatorId   = 1,
                CreatedDate = DateTime.Now,
                Id          = 1,
                Message     = "test",
                ReceiverId  = 1,
                Title       = "test"
            };
            _notificationDto = new NotificationDto()
            {
                Message    = "test",
                Title      = "test",
                ReceiverId = 1,
                SenderId   = 1
            };
            _testTokens = new List <string>();
            _testTokens.AddRange(Enumerable.Repeat("test", 5));
        }
        public async Task <EmailMessage> PrepareInvalidWorkspaceInviteMail(NotificationDto notification)
        {
            string        notificantEmail = (await _userStorage.FindAsync(u => u.Id == notification.NotificantId)).Email;
            EmailMessage  emailMessage    = new EmailMessage();
            string        mailName        = "InvalidWorkspaceInviteMessage";
            MailConfigDto mailConfigDto   = await _mailConfig.GetConfig(mailName);

            SendGridTemplateDto template = await _sendGridService.GetMailTemplate(mailConfigDto.TemplateId);

            DTOs.Version activeTemplate = template.Versions.FirstOrDefault(v => v.Active == 1);

            EmailAddress fromAddress = _fromAddress;
            EmailAddress toAddress   = new EmailAddress("", notificantEmail);

            emailMessage.FromAddresses.Add(fromAddress);
            emailMessage.ToAddresses.Add(toAddress);
            emailMessage.Subject = $"{activeTemplate.Subject} {_testEmailIndicator}";

            ProjectDto project     = notification.NotificationObject as ProjectDto;
            string     htmlContent = activeTemplate.HtmlContent
                                     .Replace("{{projectName}}", project.Name)
                                     .Replace("{{workspaceName}}", project.CommunicationPlatform);
            string plainTextContent = activeTemplate.PlainContent
                                      .Replace("{{projectName}}", project.Name)
                                      .Replace("{{workspaceName}}", project.CommunicationPlatform);

            emailMessage.MailContent.Add("text/html", htmlContent);
            emailMessage.MailContent.Add("text/plain", plainTextContent);


            return(emailMessage);
        }
Exemple #7
0
        public List <NotificationDto> GetUserNotifications(string userId)
        {
            var potentialUser = _repository.GetByFilter <PotentialUser>(x => x.UserCode == userId);


            var role = _repository.GetByFilter <UserRole>(x => x.Id == potentialUser.UserRoleId);

            if (role.Name != "Admin")
            {
                var   account          = _repository.GetByFilter <Account>(x => x.PotentialUserId == potentialUser.Id);
                ; var notifications    = _repository.GetAllByFilter <Notification>(x => x.ReciverId == account.Id || x.ReciverId == Guid.Empty);
                var   notificationDtos = new List <NotificationDto>();
                foreach (var notification in notifications)
                {
                    if (notification.SenderId != account.Id)
                    {
                        var notificationDto = new NotificationDto
                        {
                            Title  = notification.Title,
                            Body   = notification.Body,
                            IsRead = notification.IsRead,
                            ItemId = notification.ItemId,
                            Id     = notification.Id,
                            Time   = notification.Time
                        };

                        notificationDtos.Add(notificationDto);
                    }
                }

                return(notificationDtos);
            }

            return(null);
        }
Exemple #8
0
        public async Task <IActionResult> Edit(
            [Bind("Id", "Username", "Email", "RoleType",
                  "PasswordHash", "ConfirmPassword", "RecaptchaValue")]
            EditUserInputModel input)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.View(input ?? new EditUserInputModel()));
            }

            var result = await this.userService.Edit(input);

            if (result.Succeeded)
            {
                var dto = new NotificationDto
                {
                    Arg     = input.Username,
                    Message = InfoMessages.EditUserNotification,
                    User    = this.User,
                    Link    = ViewUsersUrl,
                };

                await this.notificationHelper.SendToAdmin(dto);

                string infoMessage = string.Format(this.sharedLocalizer.GetHtmlString(InfoMessages.UpdateUser), input.Username);
                return(this.ShowInfoLocal(infoMessage, ViewUsersUrl));
            }

            this.AddErrors(result);
            return(this.ShowErrorLocal(this.sharedLocalizer.GetHtmlString(ErrorMessages.UnsuccessfulUpdate), ViewUsersUrl));
        }
Exemple #9
0
        public async Task <IActionResult> Delete(
            [Bind("Id", "Username", "RecaptchaValue")]
            DeleteUserInputModel input)
        {
            var result = await this.userService.Delete(input);

            if (result.Succeeded)
            {
                var dto = new NotificationDto
                {
                    Arg     = input.Username,
                    Message = InfoMessages.DeleteUserNotification,
                    User    = this.User,
                    Link    = ViewUsersUrl,
                };

                await this.notificationHelper.SendToAdmin(dto);

                string infoMessage = string.Format(this.sharedLocalizer.GetHtmlString(InfoMessages.RemoveUser), input.Username);
                return(this.ShowInfoLocal(infoMessage, ViewUsersUrl));
            }

            this.AddErrors(result);
            return(this.ShowErrorLocal(this.sharedLocalizer.GetHtmlString(ErrorMessages.UnsuccessfulDelete), ViewUsersUrl));
        }
        /// <summary>
        /// Sends notification to user device about starting video call.
        /// </summary>
        /// <param name="customerId"></param>
        /// <param name="meetingId"></param>
        /// <param name="patient"></param>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task SendVideoCallNotification(int customerId, long meetingId, PatientDto patient,
                                                    User sender, object data = null)
        {
            var tags = new List <string>
            {
                CustomerTagTemplate.FormatWith(customerId),
                PatientIdTagTemplate.FormatWith(patient.Id)
            };
            var senderFullName = string.Join(" ", sender.FirstName, sender.LastName);
            var title          = VideoCallNotificationTitleTemplate.FormatWith(senderFullName);
            var requestDto     = new NotificationDto
            {
                AllTags = true,
                Tags    = NormalizeTags(tags),
                Types   = MobileRegistrationTypes,
                Data    = new
                {
                    call = new
                    {
                        customerID = customerId,
                        patientID  = patient.Id,
                        meetingID  = meetingId,
                        title      = title,
                        data       = data
                    }
                },
                Sender  = SenderNameTemplate.FormatWith(customerId),
                Message = null
            };

            await this.messagingHubDataProvider.SendNotification(requestDto);
        }
Exemple #11
0
        private string GetMessage(NotificationDto notificationDto)
        {
            JObject message      = new JObject();
            JObject notification = new JObject();

            message["notification"] = notification;
            notification["title"]   = notificationDto.Title;
            notification["body"]    = notificationDto.Text;


            if (!string.IsNullOrEmpty(notificationDto.ActionUrl))
            {
                JArray actions = new JArray();
                notification["actions"] = actions;
                JObject actionObj = new JObject();
                actionObj["action"] = notificationDto.Action;
                actionObj["title"]  = notificationDto.Title;
                actions.Add(actionObj);

                JObject data = new JObject();
                notification["data"] = data;
                data["url"]          = notificationDto.ActionUrl;
            }

            return(message.ToString());
        }
Exemple #12
0
        public async Task <ProjectDto> CreateProjectAsync(ProjectDto project)
        {
            await ValidateProject(project);

            var           mappedEntity   = _mapper.Map <ProjectEntity>(project);
            ProjectEntity createdProject = await _projectStorage.CreateAsync(mappedEntity);

            // By default when project is created, there is only 1 ProjectUser
            // the user that created the project aka project owner.
            var projectOwner    = project.ProjectUsers.First();
            var notificationDto = new NotificationDto(projectOwner.UserId)
            {
                NotificationObject = project
            };

            if (project.CommunicationPlatform != "other")
            {
                // send workspace app download link if CommunicationPlatform not
                // set to other
                await _notifier.SendProjectPostedNotificationAsync(notificationDto);
            }

            ProjectDto mappedProject = _mapper.Map <ProjectDto>(createdProject);
            await _messageQueue.SendMessageAsync(mappedProject, "projectpost", queueName : _pubSlackAppQueueName);

            await RecomputeProjectCollaboratorSuggestions(mappedProject, true);

            return(mappedProject);
        }
 public async Task <ActionResult <NotificationDto> > GetNotification(string userId, string notificationId)
 {
     if (Guid.TryParse(userId, out Guid gUserId) && Guid.TryParse(notificationId, out Guid gNotificationId))
     {
         try
         {
             if (await _userService.CheckIfUserExists(gUserId))
             {
                 NotificationDto notificationToReturn = _notificationService.GetNotification(gNotificationId);
                 return(Ok(notificationToReturn));
             }
             else
             {
                 return(NotFound($"User: {userId} not found."));
             }
         }
         catch (Exception ex)
         {
             _logger.LogError(ex, "Error occured during getting the notification. Notification id: {id}", notificationId);
             return(StatusCode(StatusCodes.Status500InternalServerError));
         }
     }
     else
     {
         return(BadRequest($"User id: {userId} or notification id: {notificationId} is not valid guid."));
     }
 }
Exemple #14
0
        public async Task <bool> ProcessExternalMtaNotification(FormDetailModel form)
        {
            NotificationConfiguration notificationConfiguration = await _service.GetExternalMtaNotificationConfiguration();

            NotificationDto notificationDto = new NotificationDto(notificationConfiguration.Title);
            RecipientDto    recipientDto    = new RecipientDto()
            {
                EmailAddress = form.InitiationModel !.CustomerAdminSignature.Email,
                Name         = form.InitiationModel !.CustomerAdminSignature.PrintedName
            };

            notificationDto.AddRecipient(recipientDto);
            try {
                ExternalMtaNotification notificationModel = new ExternalMtaNotification(_settings.CurrentValue.BaseUrl, form);
                notificationDto.Body = _templateManager.GetContent(notificationConfiguration.Target, notificationConfiguration.TemplatePath, notificationModel).Result;
                int processedCount = await _service.CreateNotifications(notificationDto.ToNotifications());

                if (processedCount > 0)
                {
                    await _service.UpdateLastProcessedDate(notificationConfiguration.Id);

                    return(true);
                }
            }
            catch (Exception ex) {
                _logger.LogError(ex, "Failed to process notification configuration {notificationConfiguration}", notificationConfiguration);
            }
            return(false);
        }
        public async Task <EmailMessage> PrepareInitialFeedbackRequestMail(NotificationDto notification)
        {
            UserEntity user = await _userStorage.FindAsync(u => u.Id == notification.NotificantId);

            string notificantEmail = user.Email;

            EmailMessage  emailMessage  = new EmailMessage();
            string        mailName      = "InitialFeedbackRequestMessage";
            MailConfigDto mailConfigDto = await _mailConfig.GetConfig(mailName);

            SendGridTemplateDto template = await _sendGridService.GetMailTemplate(mailConfigDto.TemplateId);

            DTOs.Version activeTemplate = template.Versions.FirstOrDefault(v => v.Active == 1);

            EmailAddress fromAddress = _fromAddress;
            EmailAddress toAddress   = new EmailAddress("", notificantEmail);

            emailMessage.FromAddresses.Add(fromAddress);
            emailMessage.ToAddresses.Add(toAddress);
            emailMessage.Subject = $"{activeTemplate.Subject} {_testEmailIndicator}";

            string htmlContent      = activeTemplate.HtmlContent;
            string plainTextContent = activeTemplate.PlainContent;

            emailMessage.MailContent.Add("text/html", htmlContent);
            emailMessage.MailContent.Add("text/plain", plainTextContent);

            return(emailMessage);
        }
        public async Task <PagedResultDto <NotificationDto> > GetListAsync(NotificationSearchDto pageDto)
        {
            List <NotificationDto> notification = (await _notificationRepository.Select
                                                   .Include(r => r.ArticleEntry)
                                                   .Include(r => r.CommentEntry)
                                                   .Include(r => r.UserInfo)
                                                   .WhereIf(pageDto.NotificationSearchType == NotificationSearchType.UserComment,
                                                            r => r.NotificationType == NotificationType.UserCommentOnArticle ||
                                                            r.NotificationType == NotificationType.UserCommentOnComment)
                                                   .WhereIf(pageDto.NotificationSearchType == NotificationSearchType.UserLike,
                                                            r => r.NotificationType == NotificationType.UserLikeArticle ||
                                                            r.NotificationType == NotificationType.UserLikeArticleComment)
                                                   .WhereIf(pageDto.NotificationSearchType == NotificationSearchType.UserLikeUser,
                                                            r => r.NotificationType == NotificationType.UserLikeUser)
                                                   .Where(r => r.NotificationRespUserId == _currentUser.Id)
                                                   .OrderByDescending(r => r.CreateTime)
                                                   .ToPagerListAsync(pageDto, out long totalCount))
                                                  .Select(r =>
            {
                NotificationDto notificationDto = _mapper.Map <NotificationDto>(r);
                if (notificationDto.UserInfo != null)
                {
                    notificationDto.UserInfo.Avatar = _fileRepository.GetFileUrl(notificationDto.UserInfo.Avatar);
                }

                return(notificationDto);
            }).ToList();

            return(new PagedResultDto <NotificationDto>(notification, totalCount));
        }
        public async Task <EmailMessage> PrepareWelcomeMail(NotificationDto notification)
        {
            string        notificantEmail = (await _userStorage.FindAsync(u => u.Id == notification.NotificantId)).Email;
            EmailMessage  emailMessage    = new EmailMessage();
            string        mailName        = "WelcomeMessage";
            MailConfigDto mailConfigDto   = await _mailConfig.GetConfig(mailName);

            SendGridTemplateDto template = await _sendGridService.GetMailTemplate(mailConfigDto.TemplateId);

            DTOs.Version activeTemplate = template.Versions.FirstOrDefault(v => v.Active == 1);

            EmailAddress fromAddress = _fromAddress;
            EmailAddress toAddress   = new EmailAddress("", notificantEmail);

            emailMessage.FromAddresses.Add(fromAddress);
            emailMessage.ToAddresses.Add(toAddress);
            emailMessage.Subject = $"{activeTemplate.Subject} {_testEmailIndicator}";
            string htmlContent      = activeTemplate.HtmlContent.Replace("{{currentYear}}", DateTime.Now.Year.ToString());
            string plainTextContent = activeTemplate.PlainContent.Replace("{{currentYear}}", DateTime.Now.Year.ToString());

            emailMessage.MailContent.Add("text/html", htmlContent);
            emailMessage.MailContent.Add("text/plain", plainTextContent);

            return(emailMessage);
        }
Exemple #18
0
        public BaseResponse AddNotification(NotificationDto notificationDto)
        {
            var response = new BaseResponse();

            try {
                var notificationRepository = new NotificationRepository();
                var newNotification        = new Notification()
                {
                    CreateBy    = notificationDto.CreateBy,
                    CreatedDate = DateTime.Now,
                    Text        = notificationDto.Text,
                    UpdatedDate = DateTime.Now,
                    WasViewed   = false
                };
                notificationRepository.Add(newNotification);
                notificationRepository.SaveChanges();
                notificationRepository.Dispose();
                response.Acknowledgment = true;
                response.Message        = "Success";
            }catch (Exception ex) {
                response.Acknowledgment = true;
                response.Message        = "Error addin a notification: " + ex.Message;
            }
            return(response);
        }
Exemple #19
0
        public override void OnBuildNotification(NotificationCompat.Builder notificationBuilder, IDictionary <string, object> parameters)
        {
            var notification = new NotificationDto()
                               .FromDictionary(new Dictionary <string, object>(parameters));

            notifoMobilePush.OnBuildNotification(notificationBuilder, notification);
        }
Exemple #20
0
        public async Task <bool> ConfirmBreweryMemberAsync(string username, NotificationDto notificationDto)
        {
            using (var context = new MicrobrewitContext())
            {
                var breweryMember = await
                                    context.BreweryMembers.SingleOrDefaultAsync(
                    b => b.BreweryId == notificationDto.Id && b.MemberUsername == username);

                if (breweryMember == null)
                {
                    return(false);
                }
                if (notificationDto.Value)
                {
                    breweryMember.Confirmed = true;
                }
                else
                {
                    context.BreweryMembers.Remove(breweryMember);
                }
                await context.SaveChangesAsync();

                return(true);
            }
        }
Exemple #21
0
        private async Task RejectNotification(NotificationDto notification, NotificationAcceptRejectDto acceptRejectDetails = null)
        {
            logger.LogWarning($"Rejecting notification {notification.NotificationId}");
            var response = await fomaSdk.SendData <NotificationAcceptRejectDto>(notification.Links[LinkRels.Accept].Href);

            logger.LogInformation($"Accepting notification {notification.NotificationId} resulted in {response.StatusCode}.");
        }
Exemple #22
0
        private async Task ImportOrder(NotificationDto notification)
        {
            logger.LogInformation($"Processing notification for order {notification.Order.OrderId}");
            foreach (var nItem in notification.Items)
            {
                logger.LogInformation($"Downloading details for item {nItem.ItemId}: item details");
                var item = await fomaSdk.GetData <ItemDto>(nItem.Links[LinkRels.Self].Href);

                logger.LogInformation($"Downloading details for item {nItem.ItemId}: manufacturing details");
                var manufacturingDetails = await fomaSdk.GetData <ManufacturingDetailDto>(item.Links[LinkRels.ManufacturingDetails].Href);

                logger.LogInformation($"Downloading details for item {nItem.ItemId}: order details");
                var order = await fomaSdk.GetData <OrderDto>(item.Order.Links[LinkRels.Self].Href);

                logger.LogInformation($"Downloading details for item {nItem.ItemId}: artwork / document");
                using (var response = await fomaSdk.Download(item.Links[LinkRels.Document].Href))
                {
                    var suggestedFilename = response.Content.Headers.ContentDisposition.FileNameStar;
                    var ext = (string.IsNullOrEmpty(suggestedFilename) ? ".pdf" : Path.GetExtension(suggestedFilename)) ?? ".pdf";
                    using (var fileStream = File.OpenWrite($"imported-item-{item.ItemId}{ext}"))
                    {
                        await response.Content.CopyToAsync(fileStream);
                    }
                }

                logger.LogInformation($"Importing item {nItem.ItemId}");
                var dataToImport = (item, manufacturingDetails, order);
                File.WriteAllText($"imported-item-{item.ItemId}.json", JsonConvert.SerializeObject(dataToImport));
            }
        }
Exemple #23
0
        private NotificationDto CreateNotif(Account account, string userCode)
        {
            var sender        = new BaseUser();
            var potentialUser = _repository.GetByFilter <PotentialUser>(x => x.UserCode == userCode);
            var role          = _repository.GetByFilter <UserRole>(x => x.Id == potentialUser.UserRoleId).Name;

            if (potentialUser == null || role == null)
            {
                return(null);
            }

            if (role == "Student")
            {
                sender = _repository.GetByFilter <Student>(x => x.PotentialUserId == potentialUser.Id);
            }
            if (role == "Professor")
            {
                sender = _repository.GetByFilter <Professor>(x => x.PotentialUserId == potentialUser.Id);
            }
            var notification = new NotificationDto
            {
                ReciverId = Guid.Empty,
                Title     = "New post on wall.",
                Body      = sender.LastName + ' ' + sender.FirstName + " has posted on the wall.",
                IsRead    = false,
                SenderId  = account.PotentialUserId,
            };

            _notificationLogic.Create(notification);

            return(notification);
        }
        public async Task <JsonWebTokenDto> RegisterUserAsync(RegistrationDto registration)
        {
            if (registration.Password != registration.PasswordConfirmation)
            {
                throw new AuthenticationException(ExceptionMessage.NonMatchingPasswords);
            }

            JsonWebTokenDto jsonWebToken;

            _user = new Common.Models.User(registration.Username, registration.Email, registration.Timezone, registration.Locale, true);

            var userEntity = _mapper.Map <UserEntity>(_user);

            userEntity.HashedPassword = HashPassword(_user, registration.Password);
            await _storage.CreateAsync(userEntity);

            jsonWebToken = GenerateJsonWebToken(new JwtUserClaimsDto(userEntity.Id.ToString()));
            NotificationDto notification = new NotificationDto(userEntity.Id);
            // re-create registration object to avoid queueing password info
            var registrationToQueue = new RegistrationDto()
            {
                Email = registration.Email, Username = registration.Username
            };
            await _messageQueue.SendMessageAsync(registrationToQueue, "registration", queueName : _pubSlackAppQueueName);

            await _notifier.SendWelcomeNotificationAsync(notification);

            await _notifier.SendInitialFeedbackRequestNotificationAsync(notification);

            return(jsonWebToken);
        }
 public void Requeue()
 {
     lock (_syncRoot)
     {
         if (!FetchedAt.HasValue)
         {
             return;
         }
         var realm = _storage.GetRealm();
         realm.Write(() =>
         {
             var queuedJob = realm.Find <JobQueueDto>(_id);
             if (queuedJob == null)
             {
                 return;
             }
             var notification = new NotificationDto
             {
                 Type  = NotificationType.JobEnqueued.ToString(),
                 Value = Queue
             };
             queuedJob.FetchedAt = null;
             realm.Add <NotificationDto>(notification);
             if (Logger.IsTraceEnabled())
             {
                 Logger.Trace($"Requeue job '{JobId}' from queue '{Queue}'");
             }
         });
         FetchedAt = null;
         _queued   = true;
     }
 }
        public HttpResponseMessage RequestFriend(NotificationDto postData)
        {
            var success = false;

            try
            {
                var notify = NotificationsController.Instance.GetNotification(postData.NotificationId);
                ParseInviteNotificationKey(notify.Context);

                _inviteRepo = new InviteRepository();
                var oInvitation = _inviteRepo.GetInvite(_inviteid);

                if (oInvitation != null)
                {
                    // Add friend of new user to invite user
                    UserInfo inviteUser = UserController.GetUserById(oInvitation.PortalId, oInvitation.InvitedByUserId);
                    if (inviteUser != null)
                    {
                        UserInfo recipientUser = UserController.GetUserById(oInvitation.PortalId, oInvitation.RecipientUserId);
                        FriendsController.Instance.AddFriend(inviteUser, recipientUser);
                    }
                    success = true;
                    NotificationsController.Instance.DeleteNotification(postData.NotificationId);
                }
            }
            catch (Exception exc)
            {
                DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);
            }

            return(success ? Request.CreateResponse(HttpStatusCode.OK, new { Result = "success" }) : Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "unable to process notification"));
        }
 private async Task CreateMessagePayloadAndSend(string conversationId, Message message)
 {
     var notification    = new MessageAddedNotification(conversationId, message.UtcTime);
     var participants    = Conversation.ParseId(conversationId);
     var notificationDto = new NotificationDto(participants, JsonConvert.SerializeObject(notification));
     await notificationService.SendNotification(notificationDto);
 }
Exemple #28
0
        private void CreateNotification(Feedback feedback)
        {
            var student = _repository.GetByFilter <Student>(x => x.Id == feedback.StudentId);
            var prof    = _repository.GetByFilter <Professor>(x => x.Id == feedback.ProfessorId);
            var body    = "";
            var sender  = Guid.Empty;

            if (student == null)
            {
                body   = "Anonymous Feedback";
                sender = Guid.Empty;
            }
            else
            {
                body   = student.LastName + ' ' + student.FirstName + " left feedback for you";
                sender = student.PotentialUserId;
            }

            var notification = new NotificationDto
            {
                Title     = "New feedback",
                Body      = body,
                IsRead    = false,
                ReciverId = prof.PotentialUserId,
                SenderId  = sender,
                ItemId    = feedback.Id
            };

            _notificationLogic.Create(notification);
        }
        public JsonResult Notice(int Id)
        {
            OperationResult       oper        = new OperationResult(OperationResultType.Error, "操作异常");
            OnlinePurchaseProduct online      = _onlinePurchaseProductContract.View(Id);
            List <Store>          listStore   = _storeContract.Stores.Where(x => x.IsDeleted == false && x.IsEnabled == true && x.Administrators.Any()).ToList();
            List <int>            listAdminId = new List <int>();

            foreach (Store item in listStore)
            {
                listAdminId.AddRange(item.Administrators.Where(x => x.IsDeleted == false && x.IsEnabled == true).Select(x => x.Id));
            }
            string          strContent = string.IsNullOrEmpty(online.NoticeContent) ? online.NoticeTitle : online.NoticeContent;
            NotificationDto dto        = new NotificationDto()
            {
                AdministratorIds = listAdminId,
                Title            = online.NoticeTitle,
                Description      = strContent,
                IsEnableApp      = true,
                NoticeTargetType = (int)NoticeTargetFlag.Admin,
                NoticeType       = (int)NoticeFlag.Immediate
            };

            oper = _notificationContract.Insert(sendNotificationAction, dto);
            return(Json(oper));
        }
        public async Task CreateNotification_WhenCalled_ProperNotificationExpected()
        {
            // ARRANGE
            var templateData = Substitute.For <INotificationTemplateData>();

            templateData.GetKeys().Returns(new List <string> {
                "{body}"
            });
            templateData.GetValue("{body}").Returns("The body content");
            var repository           = Substitute.For <IRepository <NotificationTemplate> >();
            var notificationTemplate = new NotificationTemplate {
                Abbreviation = "ABC", Body = "{body}", Subject = "The subject"
            };

            repository.SingleOrDefaultAsync(Arg.Any <Expression <Func <NotificationTemplate, bool> > >()).Returns(notificationTemplate);
            var expected = new NotificationDto {
                Body = "The body content", Subject = notificationTemplate.Subject
            };
            var service = new NotificationTemplateService(repository);

            // ACT
            var actual = await service.CreateNotification(templateData);

            // ASSERT
            actual.Should().BeEquivalentTo(expected);
        }
Exemple #31
0
        public bool SendNotificationEmail(UserDto user, MojangProfileModel model, NotificationDto notification)
        {
            var username = model.Name;

            try
            {
                string availableBody;
                string subject;

                switch (notification.Type)
                {
                    case NotificationType.AvailableSoon:
                        availableBody = $"Username '{username}' will be available in {model.AvailableIn}.\n" +
                                        $"We will notify you again if username will be released on {model.AvailableSince.Value.Subtract(TimeSpan.FromDays(7))} (UTC).";
                        subject = $"{username} will be available soon!";
                        break;
                    case NotificationType.ReleasedSoon:
                        availableBody = $"Username '{username}' will be released in {model.AvailableIn}.\n" +
                                        $"We will notify you again on {model.AvailableSince} (UTC).";
                        subject = $"{username} will be released soon!";
                        break;
                    case NotificationType.Available:
                        availableBody =
                            $"Username '{username}' is now available! Change now on https://account.mojang.com/";
                        subject = $"{username} is now available!";
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                var body = "Hi!\n" +
                           "\n" +
                           "MCNotifier is happy to notify you about some changes in your watchlist.\n" +
                           $"{availableBody}\n" +
                           "\n" +
                           "Regards,\n" +
                           "The MCNotifier Team.";

                var message = BuildMessage(user.Email, subject, body);
                SendEmail(message);
                notification.LastStatus = true;
            }
            catch (Exception e)
            {
                //log me
                notification.Retries--;
                return false;
            }
            finally
            {
                notification.Modified = DateTime.UtcNow;
            }

            return true;
        }