public static void Start() { var work = new WorkEvent(); var stopwatch = new Stopwatch(); stopwatch.Start(); new Thread(() => { while (stopwatch.IsRunning) { Console.Title = stopwatch.Elapsed.ToString(@"hh\:mm\:ss"); Thread.Sleep(1000); } }).Start(); for (; ;) { Console.Clear(); Console.Write("To stop please type 'stop': "); if (Console.ReadLine() == "stop") { break; } } stopwatch.Stop(); work.Elapsed = stopwatch.Elapsed; Console.WriteLine("What have you done?"); work.Comment = Console.ReadLine(); Save(work); }
protected override ICollection <ApplicationUser> GetOnlyResponsableUsers(WorkEvent workEvent, ICollection <ApplicationUser> users) { var currentUser = _currentUserProvider.GetCurrentUser(); var responsibleUsers = users.Where(x => x.Id != currentUser.Id); if (_previousEvents.Count == 5) { _previousEvents.Clear(); } if (IsSpecialEvent(workEvent)) { _previousEvents.Add(workEvent); } if (workEvent.Type == EventType.WorkItemChanged) { var events = _previousEvents.Where(IsSpecialEvent).ToArray(); if (events.Any()) { responsibleUsers = responsibleUsers.Where(x => events.All(ev => ev.Data != x.Id)); _previousEvents.Clear(); } } return(responsibleUsers.ToArray()); }
public List <ApplicationUser> GetUsersForEventNotification(WorkEvent @event) { var userIds = new List <ApplicationUser>(); switch (@event.Type) { case EventType.WorkItemChanged: case EventType.WorkItemStateChanged: case EventType.WorkItemAdded: case EventType.WorkItemDeleted: case EventType.WorkItemCommentAdded: // ReSharper disable once PossibleInvalidOperationException // Проверяется перед вызовом метода var workItem = _workItemRepository.GetByIdNoTracking(@event.ObjectId.Value); return(GetResponsibleUsers(workItem).Distinct(new ApplicationUserEqualityComparer()).ToList()); case EventType.WorkItemAppointed: case EventType.WorkItemDisappointed: return(new List <ApplicationUser> { _usersService.Get(@event.Data) }); case EventType.User: break; default: throw new ArgumentOutOfRangeException(); } return(userIds); }
public void RequireDateTimeInstant() { var instant = DateTime.UtcNow; WorkEvent workEvent = new WorkEvent(instant); Assert.Equal(instant, workEvent.DateTimeInstant); }
public void DateTimeInstantIsUTC() { var instant = DateTime.Now; WorkEvent workEvent = new WorkEvent(instant); Assert.Equal(instant.ToUniversalTime(), workEvent.DateTimeInstant); }
public void Notify(WorkEvent @event, ICollection <ApplicationUser> users) { @event.Validate(); var responsableUsers = GetOnlyResponsableUsers(@event, users); NotifyInner(@event, responsableUsers); }
private void Validate(WorkEvent workEvent) { if (string.IsNullOrEmpty(workEvent.UserId)) { throw new PmsException("UserId can not be empty"); } }
public void Notify_WhenEventIsInvalid_ExceptionExpected() { var notificator = new TestEventNotificator(); var @event = new WorkEvent { Type = EventType.WorkItemAppointed }; Assert.Catch <PmsException>(() => notificator.Notify(@event, new List <ApplicationUser>())); }
/// <summary> /// Сообщить о событии (послать все возможные уведомления) /// </summary> /// <param name="event">Произошедшее событие</param> public void SendEventNotifications(WorkEvent @event) { var users = _eventNotificatorsUsersForEventProvider.GetUsersForEventNotification(@event); foreach (var eventNotificator in _notificators) { eventNotificator.Notify(@event, users); } }
public void InitEvents(WorkEvent workEvent, WorkMessageEvent messageEvent) { this.FormEvent += workEvent; this.MessageEvent += messageEvent; AsyncWorker.FormEvent -= workEvent; AsyncWorker.FormEvent += workEvent; AsyncWorker.MessageEvent -= messageEvent; AsyncWorker.MessageEvent += messageEvent; }
public void InitEvents(WorkEvent workEvent, WorkMessageEvent messageEvent) { this.FormEvent -= workEvent; this.FormEvent = workEvent; this.MessageEvent -= messageEvent; this.MessageEvent = messageEvent; userEntity.Clear(); userRow.Clear(); userRun.Clear(); }
protected override ICollection <ApplicationUser> GetOnlyResponsableUsers(WorkEvent workEvent, ICollection <ApplicationUser> users) { if (users.Any(x => x.Id == workEvent.UserId)) { return(users); } return(users.Union(new[] { new ApplicationUser { Id = workEvent.UserId } }).ToList()); }
/// <summary> /// Получить описание события /// </summary> /// <param name="workEvent">Событие</param> /// <param name="forUser">Пользователь, для которого необходимо описание события</param> /// <returns></returns> public string DescribeEvent(WorkEvent workEvent, ApplicationUser forUser) { if (!CanDescribeEventType(workEvent.Type)) { throw new PmsException($"Can not describe event with type {workEvent.Type}"); } //IsCurrentUser = currentUser.Id == forUser.Id; IsUserAuthor = forUser.Id == workEvent.UserId; CurrentUser = forUser; return(GetDescription(workEvent, forUser)); }
public static void Save(WorkEvent work) { Console.WriteLine(); Console.Write(work.ToString()); try { File.AppendAllText("work.txt", work.ToString()); Console.WriteLine("Saved!"); } catch { Console.WriteLine("Failed to save"); } }
public EventUserModel(WorkEvent @event, WorkEventUserRelation eventUser) { EventId = @event.Id; EventCreaterId = @event.UserId; ObjectId = @event.ObjectId; ObjectStringId = @event.ObjectStringId; Type = @event.Type; Data = @event.Data; Date = @event.CreatedDate; UserId = eventUser.UserId; State = eventUser.State; IsFavorite = eventUser.IsFavorite; }
protected override string GetDescription(WorkEvent workEvent, ApplicationUser forUser) { var user = this._userService.Get(workEvent.Data); if (!workEvent.ObjectId.HasValue) { throw new PmsException("Error in event model"); } var item = this._workItemService.GetWithNoTracking(workEvent.ObjectId.Value); var text = GetStartText(forUser); text += IsUserAuthor ? $" {NotificationResources.HaveDisappointed} " : $" {NotificationResources.Disappointed} "; text += $"{LexicalHelper.GetWorkItemTypeInCase(item.Type, "a")} {item.GetWorkItemIdentityText()} c пользователя {user.GetUserIdentityText()}."; return(text); }
//public void SendNotification(string eventName, object sendedObject, BroadcastType broadcastType, params string[] userNames) //{ // if (broadcastType != BroadcastType.All && (userNames == null || userNames.All(string.IsNullOrEmpty))) // return; // //string[] usersNames;// = userNames.Where(x => !string.IsNullOrEmpty(x)).ToArray(); // dynamic clients; // switch (broadcastType) // { // case BroadcastType.All: // clients = Clients.All; // break; // case BroadcastType.Others: // clients = Clients.AllExcept(userNames); // break; // case BroadcastType.Users: // var users = userNames.Where(x => !string.IsNullOrEmpty(x)).ToArray(); // if (!users.Any()) // return; // clients = Clients.Users(users); // break; // default: // throw new ArgumentOutOfRangeException(nameof(broadcastType), broadcastType, null); // } // clients.recieveNotification(eventName, sendedObject); //} //public void SendNotification(WorkEvent workEvent, BroadcastType broadcastType, params string[] userNames) //{ // if (broadcastType != BroadcastType.All && (userNames == null || userNames.All(string.IsNullOrEmpty))) // return; // //string[] usersNames;// = userNames.Where(x => !string.IsNullOrEmpty(x)).ToArray(); // dynamic clients; // switch (broadcastType) // { // case BroadcastType.All: // clients = Clients.All; // break; // case BroadcastType.Others: // clients = Clients.AllExcept(userNames); // break; // case BroadcastType.Users: // var users = userNames.Where(x => !string.IsNullOrEmpty(x)).ToArray(); // if (!users.Any()) // return; // clients = Clients.Users(users); // break; // default: // throw new ArgumentOutOfRangeException(nameof(broadcastType), broadcastType, null); // } // clients.recieveNotification(workEvent.Type.ToString().ToLower(), workEvent); //} public void SendNotifications(WorkEvent workEvent, ICollection <ApplicationUser> users) { foreach (var user in users) { var clients = Clients.Users(new[] { user.UserName }); var description = _eventService.GetEventDescription(workEvent, user); var model = new NotificationViewModel { Text = description, Type = (int)workEvent.Type, WorkItemId = workEvent.ObjectId.Value }; clients.recieveNotification(workEvent.Type.ToString().ToLower(), model); } }
public WorkEvent AddEvent(WorkEvent workEvent, IEnumerable <string> usersIds) { workEvent = _repository.AddEvent(workEvent); foreach (var userId in usersIds) { var relation = new WorkEventUserRelation(workEvent.Id, userId); if (userId == workEvent.UserId) { relation.State = EventState.Seen; } _repository.AddWorkEventRelation(relation); } _repository.SaveChanges(); return(workEvent); }
public WorkEvent AddEvent(WorkEvent workEvent) { if (workEvent.Id == default(int)) { if (Events.Any()) { workEvent.Id = this.Events.OrderByDescending(x => x.Id).First().Id + 1; } else { workEvent.Id = 1; } } Events.Add(workEvent); return(workEvent); }
public WorkEvent AddEvent(WorkEvent workEvent, IEnumerable <string> usersIds) { if (workEvent.Id == default(int)) { if (Events.Any()) { workEvent.Id = this.Events.OrderByDescending(x => x.Id).First().Id + 1; } else { workEvent.Id = 1; } } Events.Add(workEvent); foreach (var userId in usersIds) { EventsUsers.Add(new WorkEventUserRelation(workEvent.Id, userId)); } return(workEvent); }
public static void Validate(this WorkEvent workEvent) { if (string.IsNullOrEmpty(workEvent.UserId)) { throw new PmsException("UserId can not be empty"); } switch (workEvent.Type) { case EventType.WorkItemChanged: case EventType.WorkItemStateChanged: case EventType.WorkItemAdded: case EventType.WorkItemDeleted: case EventType.WorkItemCommentAdded: if (!workEvent.ObjectId.HasValue) { throw new PmsException("Не указан идентификатор рабочего элемента"); } break; case EventType.WorkItemAppointed: case EventType.WorkItemDisappointed: if (string.IsNullOrWhiteSpace(workEvent.Data)) { throw new PmsException("В поле Data не содержится идентификатор пользователя"); } break; case EventType.User: break; default: throw new ArgumentOutOfRangeException(); } if (workEvent.Type == EventType.WorkItemStateChanged && string.IsNullOrWhiteSpace(workEvent.Data)) { throw new PmsException("В поле Data не содержится предыдущее состояние РЭ"); } }
public async Task <Result> SaveAsync(Guid employeeId, WorkEvent workEvent) { if (await EmployeeNotExists(employeeId)) { return(Result.Fail(new EmployeeNotExistsError())); } if (await EmployeeAddedWorkEventAtTime(employeeId, workEvent.DateTimeInstant)) { return(Result.Fail(new WorkEventAlreadyExistsError($"Employee: {employeeId} already have event with the same date time instant: {workEvent.DateTimeInstant}"))); } await dbContext.WorkEvents.AddAsync(new WorkEventEntity { EmployeeId = employeeId, DateTimeInstant = workEvent.DateTimeInstant.ToUniversalTime() }); await dbContext.SaveChangesAsync(); return(Result.Ok()); }
public void DoSomeWork(int hours) { //before calling events make sure the delegate list isn't empty for (int i = 0; i < hours; i++) { //raise workevent WorkEvent?.Invoke(this, new CoolEventArgs() { IsCool = true, Number = i + 1 }); } var args = new CoolEventArgs() { IsCool = true, Number = hours }; //raise workdone WorkDone?.Invoke(this, args); }
protected override string GetDescription(WorkEvent workEvent, ApplicationUser forUser) { var stateChangedModel = JsonConvert.DeserializeObject <StateChangedModel>(workEvent.Data); if (!workEvent.ObjectId.HasValue) { throw new PmsException("Error in event model"); } var item = _workItemService.GetWithNoTracking(workEvent.ObjectId.Value); _isUserExecutor = workEvent.UserId == item.ExecutorId; var user = _userService.Get(workEvent.UserId); var text = GetStartText(user); bool needAddition = true; text += GetTextForStateChanging(stateChangedModel, item, ref needAddition); if (needAddition) { text += LexicalHelper.GetWorkItemTypeInCase(item.Type, "a") + " "; } text += item.GetWorkItemIdentityText() + "."; return(text); }
protected override string GetDescription(WorkEvent workEvent, ApplicationUser forUser) { var appointedUser = _userService.Get(workEvent.Data); if (appointedUser == null) { throw new PmsException("Invalid event data. Must be Id."); } var appointedUserText = appointedUser.Id == forUser.Id ? (IsUserAuthor ? " себе " : " вам ") : " пользователю " + appointedUser.GetUserIdentityText(); if (!workEvent.ObjectId.HasValue) { throw new PmsException("Error in event model"); } var user = _userService.Get(workEvent.UserId); var item = _workItemService.GetWithNoTracking(workEvent.ObjectId.Value); var text = GetStartText(user); text += IsUserAuthor ? $" {NotificationResources.HaveAppointed} " : $" {NotificationResources.Appointed} "; text += appointedUserText + $"{LexicalHelper.GetWorkItemTypeInCase(item.Type, "a")} {item.GetWorkItemIdentityText()}."; return(text); }
public void PopulateAndUseClasses() { // school events SchoolEvent s = new SchoolEvent(); s.EventDate = DateTime.Today; s.EventName = "TestEvent"; s.RoomEventIsIn = "TestRoom"; Assert.AreEqual(DateTime.Today, s.EventDate); Assert.AreEqual("TestEvent", s.EventName); Assert.AreEqual("TestRoom", s.RoomEventIsIn); // work events WorkEvent w = new WorkEvent(); w.EventDate = DateTime.Today; w.EventName = "TestEvent"; w.MeetingTime = 0900; Assert.AreEqual(DateTime.Today, w.EventDate); Assert.AreEqual("TestEvent", w.EventName); Assert.AreEqual(0900, w.MeetingTime); // life events LifeEvent l = new LifeEvent(); l.EventDate = DateTime.Today; l.EventName = "TestEvent"; l.Location = "TestLocation"; Assert.AreEqual(DateTime.Today, l.EventDate); Assert.AreEqual("TestEvent", l.EventName); Assert.AreEqual("TestLocation", l.Location); }
protected abstract void NotifyInner(WorkEvent @event, ICollection <ApplicationUser> users);
protected abstract ICollection <ApplicationUser> GetOnlyResponsableUsers(WorkEvent workEvent, ICollection <ApplicationUser> users);
public List <ApplicationUser> GetUsersForEventNotification(WorkEvent @event) { return(Users); }
public string GetEventDescription(WorkEvent workEvent, ApplicationUser forUser) { return(null); }