public async Task <IActionResult> PutNotificationUser([FromRoute] int id, [FromBody] NotificationUser notificationUser) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != notificationUser.Id) { return(BadRequest()); } _context.Entry(notificationUser).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NotificationUserExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public void CreateNotification(NotificationModel notification, int[] users, bool all = false) { Notification finalNotification = new Notification() { content = notification.content, title = notification.title, stamp = DateTime.Now }; entities.Notification.Add(finalNotification); entities.SaveChanges(); finalNotification = entities.Notification .Single(notif => notif.content.Equals(finalNotification.content) && notif.title.Equals(finalNotification.title)); foreach (var user in (all ? entities.Users.ToList() : entities.Users.Where(user => users.Any(uids => uids == user.id)).ToList())) { NotificationUser notifUser = new NotificationUser() { id_notification = finalNotification.id, read = false, id_user = user.id }; entities.NotificationUser.Add(notifUser); } entities.SaveChanges(); }
public override Task OnConnected() { var applicationName = Convert.ToString(HttpContext.Current.Request.QueryString["application_name"]); var identity = (ClaimsIdentity)Context.User.Identity; var username = identity.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress").FirstOrDefault().Value;; NotificationRepository repository = new NotificationRepository(); NotificationUser user = repository.GetUser(username, applicationName); if (user != null) { NotificationUserConnection connection = new NotificationUserConnection { UserName = user.UserName, ConnectionId = Context.ConnectionId, UserAgent = Context.Request.Headers["User-Agent"], IsConnected = true }; repository.AddUserConnection(connection); Clients.Client(Context.ConnectionId).refreshNotification(repository.GetNotificationMessages(applicationName, username)); } return(base.OnConnected()); }
/*Section="CustomCodeRegion"*/ #region Customized // Keep your custom code in this region. public void AddNotificationUsers(NotificationUser notificationUser) { using (IDAL dal = this.DAL) { try { dal.BeginTransaction(); IUniParameter prmNotificationId = dal.CreateParameter("Notification", notificationUser.Notification); IUniParameter prmUserId = dal.CreateParameter("User", null); IEnumerable <NotificationUser> notificationUserList = dal.List <NotificationUser>("ANN_LST_NOTIFICATIONUSER_SP", prmNotificationId, prmUserId).ToList(); var notificationUserIds = notificationUserList.Select(x => x.User).ToArray(); foreach (int userId in notificationUser.UserList) { if (notificationUserIds.Contains(userId) == false) { notificationUser.User = userId; dal.Create <NotificationUser>(notificationUser); } } dal.CommitTransaction(); } catch (Exception ex) { dal.RollbackTransaction(); throw ex; } } }
public async Task SaveNotificationAsync(Notification nu, string UserName) { using (NotificationApplicationDbContext context = new NotificationApplicationDbContext()) { nu.ObjectState = Model.ObjectState.Added; context.Notification.Add(nu); NotificationUser User = new NotificationUser(); User.NotificationId = nu.NotificationId; User.UserName = UserName; User.ObjectState = Model.ObjectState.Added; context.NotificationUser.Add(User); try { await context.SaveChangesAsync(); } catch (Exception ex) { try { using (StreamWriter writer = new StreamWriter(@"c:\temp\NotificationException.txt", true)) { writer.WriteLine(" {0} : " + ex.ToString(), DateTime.Now); writer.Close(); } } catch (Exception x) { } } } }
public void PurchaseOrder_OnSubmit(int Id) { PurchaseOrderHeader Header = new PurchaseOrderHeaderService(_unitOfWork).Find(Id); Notification Note = new Notification(); Note.NotificationSubjectId = (int)NotificationSubjectConstants.PurchaseOrderSubmitted; Note.NotificationText = "Purchase Order " + Header.DocNo + " is submitted."; Note.NotificationUrl = "/PurchaseOrderHeader/Detail/" + Id.ToString() + "?transactionType=apptove"; Note.UrlKey = (string)System.Configuration.ConfigurationManager.AppSettings["PurchaseDomain"]; Note.ExpiryDate = DateTime.Now.AddHours(24); Note.IsActive = true; Note.CreatedBy = Header.CreatedBy; Note.ModifiedBy = Header.CreatedBy; Note.CreatedDate = DateTime.Now; Note.ModifiedDate = DateTime.Now; new NotificationService(_unitOfWork).Create(Note); var RoleList = new string[] { "Purchase Manager (Finished Tufted)", "Purchase Manager (Finished Knotted)", "Purchase Manager (Finished Kelim),Purchase Manager (Raw)" }; IEnumerable <IdentityUser> UserList = new UserService().GetUserList(RoleList); foreach (IdentityUser item in UserList) { NotificationUser NoteUser = new NotificationUser(); NoteUser.NotificationId = Note.NotificationId; NoteUser.UserName = item.UserName; new NotificationUserService(_unitOfWork).Create(NoteUser); } }
public static Boolean SendNotificationToUser(NotificationUser notification, int userID) { try { using (var db = new DBContextModel()) { TblNotifications notif = new TblNotifications { Description = notification.Description, Hour = DateTime.Now, Subject = notification.Subject, Urgency = notification.Urgency, Approval = notification.Approval, UserFK = notification.SenderFK }; db.TblNotifications.Add(notif); db.SaveChanges(); TblValidations valid = new TblValidations { NotificationFK = notif.ID, ReceiverFK = notification.ReceiverFK, Accepted = false, Read = false, StudentFK = notification.StudentFK }; db.TblValidations.Add(valid); db.SaveChanges(); BAction.SetActionToUser(String.Format("enviou uma notificação ao utilizador '{0}'", db.TblUsers.Find(notification.ReceiverFK).Name), userID); return(true); } } catch (Exception) { return(false); } }
public bool SetNotifications(NotificationMessage notificationMessage, NotificationUser makeNotification, string username) { var user = _dbContext.Users .SingleOrDefault(u => u.Email.Equals(username)); if (user == null) { return(false); } makeNotification.UserId = user.Id; try { _dbContext.Add(notificationMessage); _dbContext.Add(makeNotification); _dbContext.SaveChanges(); return(true); } catch (Exception e) { _logger.LogError(e.Message); } return(false); }
/// <summary> /// Add a notification user /// </summary> /// <param name="notificationUser"></param> /// <returns></returns> public int Add(NotificationUserDomain notificationUser) { var notificationDb = new NotificationUser().FromDomainModel(notificationUser); _context.NotificationUser.Add(notificationDb); _context.SaveChanges(); return(notificationDb.NotificationUserId); }
/// <summary> /// Sends the user registered notification. /// </summary> /// <param name="userName">The user.</param> public static void SendUserRegisteredNotification(string userName) { if (userName == "") { throw new ArgumentNullException("userName"); } var user = GetUser(userName); if (user.ProviderUserKey == null) { throw new ArgumentNullException("userName"); } // TODO - create this via dependency injection at some point. IMailDeliveryService mailService = new SmtpMailDeliveryService(); var emailFormatType = HostSettingManager.Get(HostSettingNames.SMTPEMailFormat, EmailFormatType.Text); var emailFormatKey = (emailFormatType == EmailFormatType.Text) ? "" : "HTML"; const string subjectKey = "UserRegisteredSubject"; var bodyKey = string.Concat("UserRegistered", emailFormatKey); var profile = new WebProfile().GetProfile(user.UserName); var nc = new CultureNotificationContent().LoadContent(profile.PreferredLocale, subjectKey, bodyKey); var notificationUser = new NotificationUser { Id = (Guid)user.ProviderUserKey, CreationDate = user.CreationDate, Email = user.Email, UserName = user.UserName, DisplayName = profile.DisplayName, FirstName = profile.FirstName, LastName = profile.LastName, IsApproved = user.IsApproved }; var data = new Dictionary <string, object> { { "User", notificationUser } }; var emailSubject = nc.CultureContents .First(p => p.ContentKey == subjectKey) .FormatContent(); var bodyContent = nc.CultureContents .First(p => p.ContentKey == bodyKey) .TransformContent(data); var message = new MailMessage { Subject = emailSubject, Body = bodyContent, IsBodyHtml = true }; mailService.Send(user.Email, message, null); }
public NotificationUser Create(NotificationUser pt) { //pt.ObjectState = ObjectState.Added; //_unitOfWork.Repository<NotificationUser>().Insert(pt); pt.ObjectState = ObjectState.Added; db.NotificationUser.Add(pt); db.SaveChanges(); return(pt); }
public async Task <IActionResult> AddComment(int projectId, int requirementId, int?parentId, string commentBody, string posterId) { var user = await GetCurrentUserAsync(); var project = _context.Projects.Include(p => p.Updates).FirstOrDefault(x => x.Id == projectId); var requirement = _context.Requirements.FirstOrDefault(x => x.Id == requirementId); Comment comment = new Comment { UserId = user.Id, DateTime = DateTime.Now, CommentBody = commentBody, ParentId = parentId, Requirement = requirement }; List <NotificationUser> notificationUserList = new List <NotificationUser>(); NotificationUser notificationUser = new NotificationUser() { UserId = posterId }; notificationUserList.Add(notificationUser); if (posterId != "undefined") { Notification notification = new Notification { Title = user.FirstName + " replied to your comment", Body = user.FirstName + " " + user.LastName + " replied to a comment you posted in the " + project.Name + " project.", Type = UpdateType.Reply, Users = notificationUserList, UserLink = posterId, ProjectLink = projectId, DateTime = DateTime.Now }; _context.Notifications.Add(notification); } _context.Comments.Add(comment); await _context.SaveChangesAsync(); var commentVm = _mapper.Map <CommentViewModel>(comment); commentVm.LastName = user.LastName; commentVm.FirstName = user.FirstName; commentVm.CurrentUser = user.Id; return(Ok(new CreateCommentResponse { Comment = commentVm })); }
/// <summary> /// method to insert the notification in database /// one record foe notification table and one record in notificationuser table /// </summary> /// <param name="NotificationTypeID"></param> /// <param name="FromAppUserID">if its value is null then its the case of approving post from control panel</param> /// <param name="Message"></param> /// <param name="Link">in our case its just postID</param> /// <param name="?"></param> /// <returns></returns> public bool InsertNotification(int NotificationTypeID, int?FromAppUserID, string Message, string Link, int ToAppUserID) { if (FromAppUserID != ToAppUserID) { Notification newNotif = new Notification() { NotificationTypeID = NotificationTypeID, FromAppUserID = FromAppUserID, Message = Message, Link = Link, CreateDate = DateTime.Now }; _NotificationRepository.Save(newNotif); NotificationUser newNotifUser = new NotificationUser() { Notification = newNotif, AppUserID = ToAppUserID, IsSeen = false }; _NotificationUserRepository.Save(newNotifUser); int row = _unitOfWork.Submit(); if (row > 0) { // var user = new AppUserService().GetAppUserContextByID(ToAppUserID); // //if the user logged in from 2 devices with different platforms send notif to both // string GCMID = ""; // string APNID = ""; //// string registrationType=""; // if(!string.IsNullOrEmpty(user.GCMID)) // { // GCMID = user.GCMID; // // registrationType="gcm"; // } // if(!string.IsNullOrEmpty(user.APNID)) // { // APNID = user.APNID; // // registrationType = "apns"; // } // int userID = user.ID; // int notificationsCount = UnSeenNotificationsCount(userID); // if (!string.IsNullOrEmpty(user.GCMID) || !string.IsNullOrEmpty(user.APNID)) // { // SendNotification(GCMID, APNID, Message, notificationsCount,int.Parse(Link)); // } } return(row > 0); } else { return(true); } }
public static NotificationUserDomain ToDomainModel(this NotificationUser obj) { return(obj == null ? null : new NotificationUserDomain() { Id = obj.NotificationUserId, NotificationId = obj.NotificationId, UserInfoId = obj.UserInfoId, UserTenantId = obj.UserTenantId, }); }
/// <summary> /// Sends the forgot password email. /// </summary> /// <param name="user">The user.</param> /// <param name="token">The token.</param> /// <exception cref="System.ArgumentNullException"> /// user /// or /// user /// </exception> public static void SendForgotPasswordEmail(MembershipUser user, string token) { if (user == null) { throw new ArgumentNullException("user"); } if (user.ProviderUserKey == null) { throw new ArgumentNullException("user"); } IMailDeliveryService mailService = new SmtpMailDeliveryService(); var emailFormatType = HostSettingManager.Get(HostSettingNames.SMTPEMailFormat, EmailFormatType.Text); var emailFormatKey = (emailFormatType == EmailFormatType.Text) ? "" : "HTML"; const string subjectKey = "ForgotPasswordSubject"; var bodyKey = string.Concat("ForgotPassword", emailFormatKey); var profile = new WebProfile().GetProfile(user.UserName); var nc = new CultureNotificationContent().LoadContent(profile.PreferredLocale, subjectKey, bodyKey); var notificationUser = new NotificationUser { Id = (Guid)user.ProviderUserKey, CreationDate = user.CreationDate, Email = user.Email, UserName = user.UserName, DisplayName = profile.DisplayName, FirstName = profile.FirstName, LastName = profile.LastName, IsApproved = user.IsApproved }; var data = new Dictionary <string, object> { { "Token", token } }; var emailSubject = nc.CultureContents .First(p => p.ContentKey == subjectKey) .FormatContent(); var bodyContent = nc.CultureContents .First(p => p.ContentKey == bodyKey) .TransformContent(data); var message = new MailMessage { Subject = emailSubject, Body = bodyContent, IsBodyHtml = true }; mailService.Send(user.Email, message, null); }
public async Task <IActionResult> PostNotificationUser([FromBody] NotificationUser notificationUser) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.NotificationUser.Add(notificationUser); await _context.SaveChangesAsync(); return(CreatedAtAction("GetNotificationUser", new { id = notificationUser.Id }, notificationUser)); }
public IActionResult SetInvisibleNotification(int notID) { int id = (int)HttpContext.Session.GetInt32("Userid"); NotificationUser nu = _context.NotificationUsers.Where(n => n.UserID == id && n.NotificationID == notID).FirstOrDefault(); nu.Visible = 0; _context.Update(nu); _context.SaveChanges(); return(RedirectToAction("Notifications")); }
public async Task <Notification> CreateNotification(string userId, string targetId, string notificationReason, string message, bool isForAll) { var walletId = await _context.Users.Where(u => u.Id == targetId).Select(u => u.WalletID).FirstOrDefaultAsync(); var notificationReasonId = await _context.NotificationCategories.Where(n => n.Title == notificationReason).Select(n => n.Id).FirstOrDefaultAsync(); var exists = await _context.Notifications.Where(n => n.ReasonId == notificationReasonId && n.WalletId == walletId && n.InitiatorUser == userId && n.TargetUser == targetId).AnyAsync(); if (!exists) { Notification note = new Notification { InitiatorUser = userId, TargetUser = targetId, CreationDate = DateTime.Now, Message = message, ReasonId = notificationReasonId, WalletId = walletId, isForAll = isForAll, }; _context.Notifications.Add(note); await _context.SaveChangesAsync(); if (walletId != 0 && isForAll) { List <ApplicationUser> users = await _context.Users.Where(u => u.WalletID == walletId).ToListAsync(); foreach (var user in users) { NotificationUser notificationUser = new NotificationUser { NotificationId = note.Id, UserId = user.Id, }; _context.NotificationsUsers.Add(notificationUser); } await _context.SaveChangesAsync(); } else { NotificationUser notificationUser = new NotificationUser { NotificationId = note.Id, UserId = targetId, }; _context.NotificationsUsers.Add(notificationUser); await _context.SaveChangesAsync(); } return(note); } return(null); }
public void AssignNotificationToStoreUsers(long notificationId, IEnumerable <long> userIds) { foreach (int userId in userIds) { NotificationUser notUser = new NotificationUser(); notUser.Notification = notificationId; notUser.User = userId; notUser.IsRead = false; notUser.UserList = new int[1]; notUser.UserList[0] = userId; _notificationUserService.AddNotificationUsers(notUser); } }
/// <summary> /// 特定ユーザに通知 /// </summary> /// <param name="message">メッセージ</param> /// <param name="user">通知対象ユーザー情報</param> /// <returns>結果</returns> public async Task <string> SendAsync(string message, NotificationUser user) { var notificationContent = new NotificationContent(); notificationContent.Message = message; notificationContent.Tags = new List <string>(); notificationContent.Tags.Add(user.Name); var json = JsonConvert.SerializeObject(notificationContent); var stringContent = new StringContent(json, Encoding.UTF8, Constant.Http.ContentType); HttpResponseMessage response = await this.httpHandler.PostAsync(Constant.Api.NotificationUrl, stringContent); response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsStringAsync()); }
/// <summary> /// Set is seen true /// </summary> /// <param name="iNotificationUserId"></param> /// <returns></returns> public int SetIsSeen(int?iUserId, int?iNotificationId) { int Return = 0; NotificationUser objnotification = NotificationUserList.FirstOrDefault(i => i.NotificationID == iNotificationId && i.AppUserID == iUserId); objnotification.IsSeen = true; _NotificationUserRepository.Save(objnotification); _unitOfWork.Submit(); //_NotificationUserRepository.CommitChanges(); Return = objnotification.ID; return(Return); }
public static NotificationUser FromDomainModel(this NotificationUser obj, NotificationUserDomain domain) { if (obj == null) { obj = new NotificationUser(); } obj.NotificationUserId = domain.Id; obj.NotificationId = domain.NotificationId; obj.UserInfoId = domain.UserInfoId; obj.UserTenantId = domain.UserTenantId; return(obj); }
public void InsertNotification(object o, NotificationEventArgs noti) { using (ApplicationDbContext db = new ApplicationDbContext()) { Notification notification = new Notification(); notification.NotificationText = noti.Message; db.Notifications.Add(notification); db.SaveChanges(); var users = db.Users.ToList(); foreach (var user in users) { var number = db.NotificationUsers .Where(a => a.UserAccountId == user.Id) .Count(); /*Checks if notifications for one user isn't more or equal to 5 */ /*if yes - deletes them until notification number is 4 */ /*using >= 'cause in the scenario where request happens almost in the same time it is possible * to have more 5 notifications per user*/ if (number >= 5) { while (db.NotificationUsers.Where(u => u.UserAccountId == user.Id).Count() != 4) { var notifi = db.NotificationUsers .Where(u => u.UserAccountId == user.Id).ToList() .Last(); db.NotificationUsers.Remove(notifi); db.SaveChanges(); } NotificationUser ns = new NotificationUser() { UserAccountId = user.Id, NotificationId = notification.Id }; db.NotificationUsers.Add(ns); } } db.SaveChanges(); } }
public async Task <NotificationUserResponse> SaveAsync(NotificationUser notificationUser) { try { await _notificationUserRepository.AddAsync(notificationUser); await _unitOfWork.CompleteAsync(); return(new NotificationUserResponse(notificationUser)); } catch (Exception ex) { return(new NotificationUserResponse($"An error ocurred while saving the notification user: {ex.Message}")); } }
//Send Notifications public JObject SendNotification(Notification newNotification) { var notificationMessage = new NotificationMessage(); notificationMessage.Id = Guid.NewGuid().ToString(); notificationMessage.Message = newNotification.Message; var makeNotification = new NotificationUser(); makeNotification.Id = Guid.NewGuid().ToString(); makeNotification.New = true; makeNotification.NotificationId = notificationMessage.Id; var succeed = _dbManage.SetNotifications(notificationMessage, makeNotification, newNotification.UserName); return(succeed ? _jsonEditor.GetSucced() : _jsonEditor.GetError("User doesn't exists")); }
/// <summary> /// Eventhandler for PublishedContent that adds the page's ChangedBy /// user to a subscription based on the page's ContentLink ID. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnPublishedContent(object sender, EPiServer.ContentEventArgs e) { var page = e.Content as IChangeTrackable; if (page == null) { return; } // Create a subscription var key = new Uri(BaseUri, e.Content.ContentLink.ID.ToString()); var user = new NotificationUser(page.ChangedBy); _subscriptionService.SubscribeAsync(key, user).Wait(); }
public override async Task <CommandResponse> HandleCommand(CreateNotificationCommandModel request, CancellationToken cancellationToken) { var notification = new Notification(request.Title, request.Summary); var notificationUser = new NotificationUser(request.UserId, notification); notificationUser.Send(); await _notificationRepository.CreateNotificationUserAsync(notificationUser); await _notificationRepository.Commit(); //await _hubContext.Clients.All.Notify($"Conta {@event.AccountNumber} criada com sucesso!"); return(ReplySuccessful()); }
public Object SendToUser([FromBody] NotificationUser notification) { Payload payload = BAccount.ConfirmToken(this.Request); if (payload == null || payload.rol.Contains(1)) { return(new { result = false, info = "Não autorizado." }); } var result = BNotification.SendNotificationToUser(notification, payload.aud); if (!result) { return(new { result = false, info = "Não foi possivel enviar a notificação." }); } return(new { result = true }); }
public int Insert(int iNotificationId, int iUserId, bool bIsSeen) { int Return = 0; NotificationUser objnotificationuser = new NotificationUser(); objnotificationuser.NotificationID = iNotificationId; objnotificationuser.AppUserID = iUserId; objnotificationuser.IsSeen = bIsSeen; _NotificationUserRepository.Save(objnotificationuser); _unitOfWork.Submit(); // _NotificationUserRepository.CommitChanges(); Return = objnotificationuser.ID; return(Return); }
public async Task <bool> Handle(BalanceIncreasedIntegrationEvent @event) { var notification = new Domain.Notification( "Depósito efetuado com sucesso!", $"Um depósito de R$ {@event.Value} foi efetuado em sua conta!"); var notificationUser = new NotificationUser(@event.UserId, notification); notificationUser.Send(); await _notificationRepository.CreateNotificationUserAsync(notificationUser); await _notificationRepository.Commit(); await _hubContext.Clients.All.Notify($"Depósito no valor de R$ {@event.Value} efetuado com sucesso!"); return(true); }
private NotificationMessage CreateNotification(Project project, ProjectItem item) { // load the content that is associated with the project item var content = _contentRepository.Get<IContent>(item.ContentLink); // get the edit link to the content var editUrl = _urlResolver.GetEditViewUrl(content.ContentLink, new EditUrlArguments { ForceEditHost = true, ForceHost = true, Language = item.Language }); // cast it to change trackable to be able to get the user that changed the item var change = content as IChangeTrackable; var changedBy = new NotificationUser(change.ChangedBy); // create the notification message var notificationMessage = new NotificationMessage { TypeName = "translate", Sender = changedBy, Recipients = new[] { changedBy }, ChannelName = ZapireNotificationFormatter.ChannelName, Subject = string.Format("{0} was added to {1}", content.Name, project.Name), Content = string.Format("[{0}]({1})", content.Name, editUrl) }; return notificationMessage; }