public void Send(Message msg) { var accountRepo = new RavenUserAccountRepository(MasterStore); var userAccountService = new UserAccountService(accountRepo) { Configuration = MembershipRebootConfig.Create() }; string user = msg.To;// think this is probably e-mail address... UserAccount account; account = userAccountService.GetByEmail(user); // who the message is to will give us org and user- query masterdb by username using (var session = MasterStore.OpenSession()) { } var notify = new Notification { //need url to put in here. Body = String.Format("Your temporary Illuminate passowrd is : {0} \n Please follow the instructions at {1} to change your password and login to Illuminate", password), SendDate = DateTime.Now, Title = string.Format("Your temporary Illuminate password"), From = EmailRecipient.GetIlluminateRecipient(), NotificationRecipients = new NotificationRecipient[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes .Email, Users = new List<SimpleUser>{OrgUser.ToSimpleUser()} } }, }; using (var orgSession = OrgStore.OpenSession()) { orgSession.Store(notify); orgSession.SaveChanges(); } }
public bool Dispatch(Notification notification,IDocumentStore store) { var phoneNumbers = new List<string>(); foreach (var users in notification.NotificationRecipients.Select(r=>r.Users)) { phoneNumbers.AddRange(users.Where(u=>!string.IsNullOrEmpty(u.MobilePhoneNumber)).Select(u => u.MobilePhoneNumber)); } var message = notification.Body.Length >= 140 ? notification.Body.Substring(0, 140) : notification.Body; var sms = new Sms { From = "Illuminate", Message = message, Numbers = phoneNumbers }; bool sent=false; try { sent=_smsSender.Send(sms); } catch (Exception ex) { _log.Error(string.Format("Problem sending SMS"),ex); } if (sent) { using (var session = store.OpenSession()) { sms.Sent = true; sms.SentOn = DateTime.Now; session.Store(sms); session.SaveChanges(); } _log.Info(string.Format("succesfully sent sms to provider")); return true; } _log.Error(string.Format("problem submitting sms to provider")); return false; }
/// <summary> /// dispatch the notification as an email /// </summary> /// <param name="notification">The notification to dispatch</param> /// <param name="users">users to send the email to</param> /// <param name="store"></param> /// <returns></returns> public bool Dispatch(Notification notification,IEnumerable<Organisation.SimpleUser> users,IDocumentStore store ) { //create an email from the notification and user details var email = new Email { Body = notification.Body, Subject = notification.Title, To = users.Where(simpleUser => !string.IsNullOrEmpty(simpleUser.EmailAddress)).Select(u => new EmailRecipient { Email = u.EmailAddress, Name = u.FullName }).ToList() }; if (email.To.Count == 0) { _log.Warn(string.Format("Cannot send email with subject {0} because there is not a valid To address",email.Subject)); return false; } try { if (_emailSender.Send(email)) { using (var session = store.OpenSession()) { session.Store(email); session.SaveChanges(); } _log.Info(string.Format("successfully sent email to {0}", email.To[0].Email)); return true; } _log.Error(string.Format("problem sending email for {0}", email.To[0].Email)); return false; } catch (Exception ex) { _log.Error(string.Format("problem sending email for {0}", email.To[0].Email), ex); return false; } }
public void Invoke(IUser user,IInferenceType inferenceType,IDocumentSession session) { //create a new notification and save it var notification = new Notification { About = user.ToSimpleUser(), Id = IlluminateDatabase.GenerateId<Notification>(), SendDate = DateTime.Now, From = EmailRecipient.GetIlluminateRecipient(), Title = "Illuminate Inference", Body = inferenceType.GetDescription(user), NotificationRecipients = new NotificationRecipient[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes .Toast | NotificationDeliveryTypes .Email, Users = user.Relationships .Where( r => r.RelationshipName == Role.BuiltInRole .LineManager .ToString()) } } }; session.Store(notification); session.SaveChanges(); }
public bool Dispatch(Notification notification,IDocumentStore orgStore) { if (string.IsNullOrEmpty(notification.Title)) { _log.Warn(string.Format("cannot send notification {0} by TOAST - title is not set. Org {1}",notification.Id,orgStore.Url)); return false; } if (string.IsNullOrEmpty(notification.Body)) { _log.Warn(string.Format("cannot send notification {0} by TOAST - body is not set. Org {1}", notification.Id, orgStore.Url)); return false; } using (var session = _store.OpenSession()) { foreach (var toast in (from recipient in notification.NotificationRecipients from user in recipient.Users select user).Select(user => new Toast{CreatedDate = DateTime.Now,Message = notification.Body,Name = notification.Title,UserId=user.UserId,Id = IlluminateDatabase.GenerateId<Toast>()})) { session.Store(toast); } session.SaveChanges(); } return true; //TODO - dont just return true here }
public JsonResult EmailHIGHitLink() { using (var orgSession = OrgStore.OpenSession()) { var notify = new Notification { Body = String.Format("Your HIG Hit Url is : {0}/HIGHit/Auth/{1}", ConfigurationManager.AppSettings["HostName"], Claims.FirstOrDefault(c => c.Type==IlluminateClaimTypes.AuthHash).Value), SendDate = DateTime.Now, Title = string.Format("HIG Hit Link"), From = EmailRecipient.GetIlluminateRecipient(), NotificationRecipients = new NotificationRecipient[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes .Email | NotificationDeliveryTypes.Sms , Users = new List<SimpleUser>{OrgUser.ToSimpleUser()} } }, }; orgSession.Store(notify); orgSession.SaveChanges(); } return JsonSuccess("Email Sent"); }
public static HIGEntry Capture(IDocumentStore store, User user, HIGCaptureViewModel model) { using (var orgSession = store.OpenSession()) { var simpleUser = user.ToSimpleUser(); var hv = new HIGEntry { CaptureDate = DateTime.Now, ConsolidatedCompletionDate = DateTime.Now, Subject = simpleUser, Value = model.HIGValue, Message = model.HIGMessage, Id = IlluminateDatabase.GenerateId<HIGEntry>(), LastInDay = true }; if (user.LatestHig != null && user.LatestHig.CaptureDate.Date == DateTime.UtcNow.Date) //same day { //previous hig should be not latest in day. var lasthig = orgSession.Load<HIGEntry>(user.LatestHig.Id); lasthig.LastInDay = false; } //set users latest hig. user.LatestHig = hv; if (hv.Value < 0) { //alert! Alert! var notify = new Notification { About = simpleUser, Body = String.Format( "{0} added a new negative HIG on {1}. Perhaps you should investigate", user.Name, hv.CaptureDate), SendDate = DateTime.Now, Title = string.Format("HIG Alert for {0}", user.Name), From = EmailRecipient.GetIlluminateRecipient(), NotificationRecipients = new[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes .Toast | NotificationDeliveryTypes .Email | NotificationDeliveryTypes.Sms , Users = user.Relationships .Where(r => r.RelationshipName == Role.BuiltInRole.LineManager.ToString() ) } }, }; orgSession.Store(notify); } orgSession.Store(user); orgSession.Store(hv); orgSession.SaveChanges(); return hv; } }
/// <summary> /// dispatch a notification /// </summary> /// <param name="notification"></param> /// <param name="store"></param> private void Dispatch(Notification notification,IDocumentStore store) { _log.Information(string.Format("About to dispatch a notification {0} from store {1}", notification.ToString(), store.Url)); var dispatched = false; //a notification can have multiple recipients e.g. send notification to employee and manager foreach (var recipient in notification.NotificationRecipients) { bool emailDispatched; if (recipient.RemainingNotificationDeliveryTypes.Has(NotificationDeliveryTypes.Email)) { emailDispatched = _emailDispatcher.Dispatch(notification, recipient.Users, store); if (emailDispatched) { recipient.RemainingNotificationDeliveryTypes = recipient.RemainingNotificationDeliveryTypes.Remove(NotificationDeliveryTypes.Email); _log.Information(string.Format("dispatched an email notification to {0}", string.Join(",", recipient.Users.Select(u => u.EmailAddress)))); } else { _log.Warning(string.Format("could not dispatch an email notification to {0}", string.Join(",", recipient.Users.Select(u => u.EmailAddress)))); } } else { emailDispatched = true; } bool toastDispatched; if (recipient.RemainingNotificationDeliveryTypes.Has(NotificationDeliveryTypes.Toast)) { toastDispatched = _toastDispatcher.Dispatch(notification,store); if (toastDispatched) { recipient.RemainingNotificationDeliveryTypes = recipient.RemainingNotificationDeliveryTypes.Remove(NotificationDeliveryTypes.Toast); _log.Information(string.Format("dispatched an toast notification to {0}", string.Join(",", recipient.Users.Select(u => u.FullName)))); } else { _log.Warning(string.Format("could not dispatch a toast notification to {0}", string.Join(",", recipient.Users.Select(u => u.FullName)))); } } else { toastDispatched = true; } bool smsDispatched; if (recipient.RemainingNotificationDeliveryTypes.Has(NotificationDeliveryTypes.Sms)) { smsDispatched = _smsDispatcher.Dispatch(notification,store); if (smsDispatched) { recipient.RemainingNotificationDeliveryTypes = recipient.RemainingNotificationDeliveryTypes.Remove(NotificationDeliveryTypes.Sms); _log.Information(string.Format("dispatched an SMS notification to {0}", string.Join(",", recipient.Users.Select(u => u.MobilePhoneNumber)))); } else { _log.Warning(string.Format("could not dispatch an SMS notification to {0}", string.Join(",", recipient.Users.Select(u => u.MobilePhoneNumber)))); } } else { smsDispatched = true; } dispatched = emailDispatched && smsDispatched && toastDispatched; } //update the notification to say its been dealt with if (dispatched) { notification.Sent = true; notification.ActualSentDate = DateTime.Now; _log.Information(string.Format("sucessfully dispatched a notification {0}", notification)); } else { notification.NumDeliveryAttempts--; notification.SendDate = DateTime.Now.AddSeconds(_numSecondsBackoff); _log.Warning(string.Format("problem dispatching a notification {0} - backing off {1} more attempts left", notification,notification.NumDeliveryAttempts)); } using (var session= store.OpenSession()) { session.Store(notification); session.SaveChanges(); } }
public static void EmailActivation(IUser ou, IAuthUser au, IDocumentStore store,string password) { var activationurl = String.Format("{0}://{1}/{2}", "https", ConfigurationManager.AppSettings["ActivationUrl"], au.ActivationCode); var body = GetActivationEmailBody(ou, activationurl, au.ActivationCode,password); var notification = new Notification { About = ou.ToSimpleUser(), Body = body, Id = IlluminateDatabase.GenerateId<Notification>(), SendDate = DateTime.Now, Title = "Illuminate Account Activation Code", NotificationRecipients = new[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes.Email, Users = new[] { ou.ToSimpleUser() } } } }; using (var session = store.OpenSession()) { session.Store(notification); session.SaveChanges(); } }
public static void PasswordReset(IUser ou, IDocumentStore store, string password) { var body = GetPasswordResetEmailBody(ou, password)+EmailFooter; var notification = new Notification { About = ou.ToSimpleUser(), Body = body, Id = IlluminateDatabase.GenerateId<Notification>(), SendDate = DateTime.Now, Title = "Illuminate Password Reset", NotificationRecipients = new[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes.Email, Users = new[] { ou.ToSimpleUser() } } } }; using (var session = store.OpenSession()) { session.Store(notification); session.SaveChanges(); } }
public static void TestNotification() { var store = new DocumentStore {ConnectionStringName = "RavenServer"}; store.Initialize(); using (var orgSession = store.OpenSession()) { //alert! Alert! var simpleUser = new SimpleUser {FullName = "andy"}; var recipients = new NotificationRecipient[] {new NotificationRecipient(),}; var notify = new Notification { Body = "body", SendDate = DateTime.Now, Title = "HIG Alert", NotificationRecipients = new NotificationRecipient[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes .Toast | NotificationDeliveryTypes .Email, Users = new SimpleUser[] { new SimpleUser { FullName = "andy" } } } }, }; orgSession.Store(notify); orgSession.SaveChanges(); } }
void AddNotificationsToDB() { var notifications = new List<Notification>(); for (var i = 0; i < 30; i++) { var notification = new Notification {Title = "notification"}; var about = new SimpleUser { FullName = "Andy Evans", EmailAddress = "*****@*****.**", UserId = "user_293ebdcf-d47c-4e63-9c12-3fbb6603b644" }; notification.About = about; notification.Body = "you have a notification"; notification.Id = i + "notification"; var notificationrecipients = new List<NotificationRecipient>(); var notificationrecipient = new NotificationRecipient(); notification.NotificationRecipients = new[] {new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes.Email, Users = new [] { new SimpleUser {EmailAddress = "*****@*****.**",FullName = "Andy Evans",UserId = "user_293ebdcf-d47c-4e63-9c12-3fbb6603b644"} }}}; notification.Read = true; notification.Sent = true; notification.SendDate = DateTime.Now; notification.ActualSentDate = DateTime.Now; notification.From = null; //notificationrecipient.Users = new IEnumerable<SimpleUser>(); //var recipient = new SimpleUser(); //recipient.EmailAddress= "*****@*****.**"; //recipient.UserId = "user_293ebdcf-d47c-4e63-9c12-3fbb6603b644" //var recipients = new IEnumerable<SimpleUser>(); //notificationrecipient.Users = new IEnumerable<recipient>(); ////notification.NotificationRecipients notifications.Add(notification); } var store = new DocumentStore { ConnectionStringName = "RavenServer" }; store.Initialize(); using (var session = store.OpenSession()) { foreach (var notification in notifications) { session.Store(notification); } session.SaveChanges(); } }
/// <summary> /// Create a priase for a person /// </summary> /// <param name="model"></param> /// <returns></returns> public JsonResult CreatePraise(PraiseViewModel model) { //remove Id from modelstate if tehre. ModelState.Remove("Id"); ModelState.Remove("EventDate"); ModelState.Remove("CreatedBy"); if (ModelState.IsValid) { using (var orgSession = OrgStore.OpenSession()) { //who is the priase for var target = orgSession.Load<User>(model.SubjectUserId); var praise = new Praise { CreatedBy = OrgUser.ToSimpleUser(), EventDate = DateTime.Now, ConsolidatedCompletionDate = DateTime.Now, Comment = model.Comment, SubjectUser = target.ToSimpleUser(), Level = model.Level, Id = IlluminateDatabase.GenerateId<Praise>() }; orgSession.Store(praise); //also send the target an email letting them know var notify = new Notification { Body =Email.GetPraiseEmailBody(target,OrgUser,model.Comment), SendDate = DateTime.Now, Title = string.Format("Congratulations you have been praised"), From = EmailRecipient.GetIlluminateRecipient(), NotificationRecipients = new[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes .Email , Users = new List<SimpleUser>{target.ToSimpleUser()} } }, }; orgSession.Store(notify); orgSession.SaveChanges(); return JsonSuccess(praise.ToTimelineItems(), "Praise created"); } } return JsonError("Invalid data"); }
private static void CreateRewardNotification(Reward reward, IDocumentSession session) { //also send the target an email letting them know var notify = new Notification { Body = Email.GetRewardEmailBody(reward.SubjectUser, reward.RewardGiver, reward.Message, reward.Points), SendDate = DateTime.UtcNow, Title = string.Format("Congratulations you have got a reward"), From = EmailRecipient.GetIlluminateRecipient(), NotificationRecipients = new[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes .Email , Users = new List<SimpleUser>{reward.SubjectUser} } }, }; session.Store(notify); session.SaveChanges(); }
public virtual void EmailActivation(AuthUser au, User ou, IDocumentStore orgStore) { //check not already activated. Work this out from if (String.IsNullOrEmpty(au.ActivationCode)) { throw new Exception("User is already activated"); } var activationurl = String.Format("{0}://{1}/{2}", Request.Url.Scheme, ConfigurationManager.AppSettings["ActivationUrl"], au.ActivationCode); var notification = new Notification { Title = "New Administrator account for Illuminate", Body = Email.GetActivationEmailBody(ou, activationurl,au.ActivationCode,""), Id = IlluminateDatabase.GenerateId<Notification>(), NotificationRecipients = new[] { new NotificationRecipient { Users = new[] {ou.ToSimpleUser()}, NotificationDeliveryTypes = NotificationDeliveryTypes.Email } }, SendDate = DateTime.Now }; using (var session = orgStore.OpenSession()) { session.Store(notification); session.SaveChanges(); } }
/// <summary> /// Perform an action on the default sickness workflow /// </summary> /// <param name="documentStore">The document store to use</param> /// <param name="triggerprocess">The workflow initiator that triggered this</param> /// <param name="action">The action to be performed</param> public override void PerformAction(IDocumentStore documentStore, WorkflowInitiator triggerprocess, WorkflowHandlerAction action) { var sickness = (Sickness) triggerprocess; //we know its a sickness so cast to it switch (action.Action) //depending on the action type act accordingly { case WorkflowHandlerAction.Actions.AddTask: //what am I creating? - deserialise the contents of the action var actionModel = action.DeserialiseObject<CreateProcessTaskActionModel>(); //need to convert the actionmodel into an event - in this case a task var newtask = new Task { Id = IlluminateDatabase.GenerateId<Task>(), Type = new TaskType {Name = actionModel.TaskName}, AssignedRoles = (from role in actionModel.AssignedRoles select Role.GetRole(role)).ToList(), DueDate = actionModel.DueDate, ConsolidatedCompletionDate = actionModel.DueDate>=DateTime.Now ? actionModel.DueDate : DateTime.Now, CreatedBy = sickness.UserCreatedProcess, Title =string.Format( actionModel.Title,sickness.Subject.FullName), Description = string.Format( actionModel.Description,sickness.Subject.FullName), ParentItemId = sickness.Id }; //store the task in the db using (var session = documentStore.OpenSession()) { session.Store(newtask); newtask.UpdateAssignees(session, sickness.Subject.UserId); session.SaveChanges(); } break; case WorkflowHandlerAction.Actions.AddMeeting: var meetingactionmodel = action.DeserialiseObject<CreateProcessMeetingActionModel>(); //need to convert the actionmodel into an event. but problem is looking up user? var newmeeting = new Meeting { Id = IlluminateDatabase.GenerateId<Meeting>(), Type = new TaskType { Name = meetingactionmodel.TaskName }, AssignedRoles = (from role in meetingactionmodel.AssignedRoles select Role.GetRole(role)).ToList(), Invitees = new List<Invitee> { Invitee.FromSimpleUser(sickness.Subject)}, DueDate = meetingactionmodel.DueDate, ConsolidatedCompletionDate = meetingactionmodel.DueDate >= DateTime.Now ? meetingactionmodel.DueDate : DateTime.Now, CreatedBy = sickness.UserCreatedProcess, Title = meetingactionmodel.Title, Description = meetingactionmodel.Description, ParentItemId = sickness.Id }; //save the meeting in the DB using (var session = documentStore.OpenSession()) { session.Store(newmeeting); newmeeting.UpdateAssignees(session, sickness.Subject.UserId); session.SaveChanges(); } break; case WorkflowHandlerAction.Actions.DeleteTask: //delete the task from the DB using (var session = documentStore.OpenSession()) { var task = session.Load<Task>(action.Value); session.Delete(task); session.SaveChanges(); } break; case WorkflowHandlerAction.Actions.DeleteMeeting: //delete the meeting from the DB using (var session = documentStore.OpenSession()) { var meeting = session.Load<Meeting>(action.Value); session.Delete(meeting); session.SaveChanges(); } break; case WorkflowHandlerAction.Actions.NotifyActorsOfCreation: using (var session = documentStore.OpenSession()) { var managerCreatedSickness=sickness.UserCreatedProcess.UserId==sickness.CurrentProcessOwner.UserId; //if the manager created the sickness notify the employee Notification notification; if (managerCreatedSickness) { notification = new Notification { NotificationRecipients = new[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes .Email | NotificationDeliveryTypes .Toast, Users = new[] { sickness .Subject } } }, Body = string.Format( "You have been registered as off sick for {0} by {1}", sickness.SicknessReason.Name, sickness.CurrentProcessOwner.FullName) }; } else { notification = new Notification { NotificationRecipients = new[] { new NotificationRecipient { NotificationDeliveryTypes = NotificationDeliveryTypes .Email | NotificationDeliveryTypes .Toast| NotificationDeliveryTypes.Sms, Users = new[] { sickness.CurrentProcessOwner } } }, Body = string.Format( "{0} has registered themselves as off sick for {1}.", sickness.Subject.FullName, sickness.SicknessReason.Name) }; } notification.Title = string.Format("Sickness for {0}", sickness.Subject.FullName); notification.About = sickness.Subject; notification.Id = IlluminateDatabase.GenerateId<Notification>(); notification.SendDate = DateTime.Now; session.Store(notification); session.SaveChanges(); } break; } }