public async Task <WorkEntry> CreateAsync(WorkEntry workEntry)
        {
            if (workEntry.HoursSpent <= 0 || workEntry.HoursSpent > 24)
            {
                throw new ArgumentOutOfRangeException(nameof(workEntry.HoursSpent));
            }

            if (workEntry.Id == Guid.Empty)
            {
                workEntry.Id = Guid.NewGuid();
            }

            if (string.IsNullOrWhiteSpace(workEntry.UserId) || !_userContextAccessor.IsAdminUser())
            {
                workEntry.UserId = _userContextAccessor.GetUserId();
            }

            try
            {
                _dbContext.Add(workEntry);
                await _dbContext.SaveChangesAsync().ConfigureAwait(false);

                return(workEntry);
            }
            catch (DbUpdateException e)
            {
                if (_dbErrorHandler.IsDuplicateKeyError(e, "UserId", "Date"))
                {
                    throw new ArgumentException($"Duplicate entry for date {workEntry.Date:yyyy-MM-dd}");
                }

                throw;
            }
        }
        public async Task UpdateAsync_AnotherUser_ReturnsNull(bool isAdmin, bool isNullResult)
        {
            // Arrange
            using var dbContext = CreateDbContext();
            var user = await CreateTestUserAsync(dbContext);

            var anotherUser = await CreateTestUserAsync(dbContext);

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(user.Id);
            userContextAccessorMock.Setup(m => m.IsAdminUser()).Returns(isAdmin);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);
            var entry = await CreateWorkEntry(dbContext, anotherUser.Id);

            // Act
            var entryToUpdate = new WorkEntry
            {
                Id         = entry.Id,
                Date       = new DateTime(2021, 1, 1),
                HoursSpent = 6,
                Notes      = "Some notes..."
            };

            entry = await workEntriesService.UpdateAsync(entryToUpdate);

            Assert.Equal(isNullResult, entry == null);
        }
        public async Task UpdateAsync_EntryDoesNotExists_ReturnsNull()
        {
            // Arrange
            using var dbContext = CreateDbContext();
            var user = await CreateTestUserAsync(dbContext);

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(user.Id);
            userContextAccessorMock.Setup(m => m.IsAdminUser()).Returns(false);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);

            // Act
            var entryToUpdate = new WorkEntry
            {
                Id         = Guid.NewGuid(),
                Date       = new DateTime(2021, 1, 1),
                HoursSpent = 6,
                UserId     = user.Id + "1",
                Notes      = "Some notes..."
            };

            var entry = await workEntriesService.UpdateAsync(entryToUpdate);

            Assert.Null(entry);
        }
        public async Task CreateAsync_ExplicitUserId(bool isAdmin, string currentUserId, string createdByUserId, string expectedEntryUserId)
        {
            // Arrange
            using var dbContext = CreateDbContext();

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(currentUserId);
            userContextAccessorMock.Setup(m => m.IsAdminUser()).Returns(isAdmin);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);

            // Act
            var entry = new WorkEntry
            {
                HoursSpent = 5,
                Date       = DateTime.Now.Date,
                Notes      = "Notes",
                UserId     = createdByUserId
            };

            entry = await workEntriesService.CreateAsync(entry);

            // Assert
            Assert.Equal(expectedEntryUserId, entry.UserId);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Syncs the Jira entry with the work entry
        /// </summary>
        /// <param name="jEntry">Jira entry to update</param>
        /// <param name="wEntry">Work entry to update Jira with</param>
        /// <returns>True if updated successfully</returns>
        public bool SyncWorkEntry(JiraWorkEntry jEntry, WorkEntry wEntry)
        {
            jEntry.TimeSpent        = wEntry.TimeSpent;
            jEntry.TimeSpentSeconds = 0;

            Logger.DebugFormat("Syncronizing {0} in {1}", wEntry.TogglId, wEntry.IssueId);

            try
            {
                using (IHttpResponse response = GetResponse(() => GetWorkEntryRequest(jEntry, jEntry.Self, "PUT")))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        EncounteredError = false;
                        WorkEntryUpdated?.Invoke(wEntry);
                        return(true);
                    }
                    else
                    {
                        EncounteredError = true;
                        WorkEntryUpdateFailed?.Invoke(wEntry);
                        Logger.WarnFormat("Didn't get the expected status code back when syncing a work entry for {0}. Got {1}", wEntry.IssueId, response.StatusCode);
                    }
                }
            }
            catch (WebException we)
            {
                EncounteredError = true;
                WorkEntryUpdateFailed?.Invoke(wEntry);
                Logger.Error("Unable to sync web entry", we);
            }

            return(false);
        }
        public async Task <WorkEntry> UpdateAsync(WorkEntry entry)
        {
            if (entry.HoursSpent <= 0 || entry.HoursSpent > 24)
            {
                throw new ArgumentOutOfRangeException(nameof(entry.HoursSpent));
            }

            if (entry is null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            var dbEntry = await GetByIdAsync(entry.Id).ConfigureAwait(false);

            if (dbEntry == null)
            {
                return(null);
            }

            dbEntry.Date       = entry.Date;
            dbEntry.Notes      = entry.Notes;
            dbEntry.HoursSpent = entry.HoursSpent;

            await _dbContext.SaveChangesAsync().ConfigureAwait(false);

            return(dbEntry);
        }
        public async Task CreateAsync_InitsEmptyFields()
        {
            // Arrange
            string testUserId = Guid.NewGuid().ToString();

            using var dbContext = CreateDbContext();

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(testUserId);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);

            // Act
            var entry = new WorkEntry
            {
                HoursSpent = 5,
                Date       = DateTime.Now.Date,
                Notes      = "Notes"
            };

            var createdEntry = await workEntriesService.CreateAsync(entry);

            // Assert
            Assert.NotEqual(Guid.Empty, createdEntry.Id);
            Assert.Equal(testUserId, createdEntry.UserId);
            Assert.Equal(entry.Date, createdEntry.Date);
            Assert.Equal(entry.Notes, createdEntry.Notes);
            Assert.Equal(entry.HoursSpent, createdEntry.HoursSpent);
        }
Exemplo n.º 8
0
        private void TestValid(string issueId, string comment, string seperator = ": ")
        {
            var entry = WorkEntry.Create(GetEntry($"{issueId}{seperator}{comment}"));

            Assert.IsNotNull(entry);
            Assert.AreEqual(issueId, entry.IssueId);
            Assert.AreEqual(comment, entry.Comment);
        }
 private static void AssertEqual(WorkEntry expected, WorkEntry actual)
 {
     Assert.Equal(expected.Id, actual.Id);
     Assert.Equal(expected.Date, actual.Date);
     Assert.Equal(expected.HoursSpent, actual.HoursSpent);
     Assert.Equal(expected.Notes, actual.Notes);
     Assert.Equal(expected.UserId, actual.UserId);
 }
Exemplo n.º 10
0
        public override WorkEntry ToWorkEntry()
        {
            WorkEntry entry = base.ToWorkEntry();

            entry.Id     = Id;
            entry.UserId = UserId;

            return(entry);
        }
Exemplo n.º 11
0
 private async void HandleSelectedItem()
 {
     if (SelectedEntry != null)
     {
         string name = SelectedEntry.Name;
         _selectedEntry = null;
         await Navigation.PushAsync(new EditBookEntries(NewBook, name));
     }
 }
Exemplo n.º 12
0
        public void SetWorkEntry(WorkEntry entry)
        {
            CurrentEntry = entry;
            lbl_ClientTrackerUser.Content = entry.User.FirstName + " " + entry.User.LastName;
            lbl_DateTime.Content = entry.StartTime.ToString("g");
            lbl_WorkType.Content = entry.TypeOfWorkDone.ToString();
            lbl_Duration.Content = Math.Round(entry.TimeWorked.TotalMinutes, 2).ToString() + " minutes";

            txtBox_Notes.Text = entry.Notes;
        }
Exemplo n.º 13
0
        public async Task Update(int id, WorkEntry newValue)
        {
            if (!this.Exists(id))
            {
                throw new KeyNotFoundException();
            }
            var entity = await _context.WorkEntries.FirstOrDefaultAsync(w => w.Id == id);

            entity = newValue;
            _context.WorkEntries.Update(entity);
        }
		public object Deserialize(JsonValue json, JsonMapper mapper)
		{
			WorkEntry entry = null;
			if ( json != null && !json.IsNull )
			{
				entry = new WorkEntry();
				entry.StartDate = json.ContainsName("start_date") ? json.GetValue<string>("start_date") : String.Empty;
				entry.EndDate   = json.ContainsName("end_date"  ) ? json.GetValue<string>("end_date"  ) : String.Empty;
				
				entry.Employer  = mapper.Deserialize<Reference>(json.GetValue("employer"));
			}
			return entry;
		}
Exemplo n.º 15
0
        public WorkEntryDto(WorkEntry workEntry)
        {
            if (workEntry is null)
            {
                throw new ArgumentNullException(nameof(workEntry));
            }

            Id         = workEntry.Id;
            Date       = workEntry.Date;
            HoursSpent = workEntry.HoursSpent;
            Notes      = workEntry.Notes;
            UserId     = workEntry.UserId;
        }
Exemplo n.º 16
0
        public WorkEntry ToWork()
        {
            WorkEntry e = new WorkEntry();

            e.Name        = Name;
            e.Description = Description;
            e.ImagePath   = ImagePath;
            foreach (Tag t in Tags)
            {
                e.Tags.Add(new WorkTag(t.Name, t.Value));
            }

            return(e);
        }
        public object Deserialize(JsonValue json, JsonMapper mapper)
        {
            WorkEntry entry = null;

            if (json != null && !json.IsNull)
            {
                entry           = new WorkEntry();
                entry.StartDate = json.ContainsName("start_date") ? json.GetValue <string>("start_date") : String.Empty;
                entry.EndDate   = json.ContainsName("end_date") ? json.GetValue <string>("end_date") : String.Empty;

                entry.Employer = mapper.Deserialize <Reference>(json.GetValue("employer"));
            }
            return(entry);
        }
Exemplo n.º 18
0
        public NewEntryViewModel(INavigation navigation, WorkBook book)
        {
            Navigation    = navigation;
            NewBook       = book;
            NewEntry      = new WorkEntry();
            CurrentTags   = new ObservableCollection <WorkTag>();
            AddImage      = new Command(OnAddImage);
            AddTag        = new Command(OnAddTag);
            RemoveLastTag = new Command(OnRemoveLastTag);
            SaveEntry     = new Command(OnSaveEntry);
            DiscardEntry  = new Command(OnDiscardEntry);
            ToggleView    = new Command(OnToggleView);
            Return        = new Command(OnReturn);

            TagsVisible        = true;
            DescriptionVisible = false;
        }
        public ActionResult LogHours(WorkEntry entry)
        {
            if (entry.Hours > 0)
            {
                entry.UserName = UserModel.Current.UserName;
                entry.Logged   = DateTime.Now;

                _repositories.WorkEntries.Add(entry);
                _repositories.WorkEntries.SaveChanges();

                TempData["message"] = "Your hours have been logged and you have been successfully logged out.";
            }

            TempData["message"] = "You have been successfully logged out.";

            return(RedirectToAction("SignOut", "Account"));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Adds the gived entry to the worklog of its issue
        /// </summary>
        /// <param name="wEntry">Worklog entry to add</param>
        /// <returns>True if added successfully</returns>
        public bool AddWorkEntry(WorkEntry wEntry)
        {
            JiraWorkEntry jEntry = new JiraWorkEntry
            {
                Started   = GetStartTime(wEntry),
                Comment   = wEntry.CommentWithMarker,
                TimeSpent = wEntry.TimeSpent
            };

            Logger.DebugFormat("Creating a entry for {0} corresponding to {1}.", wEntry.IssueId, wEntry.TogglId);
            HttpWebRequest request = GetRequest(string.Format(GetWorklogUrl, wEntry.IssueId), true);

            request.ContentType = "application/json;charset=UTF-8";
            request.Method      = "POST";

            try
            {
                WriteWorkEntry(jEntry, request);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        Logger.DebugFormat("Work entry created for issue {0}", wEntry.IssueId);
                        EncounteredError = false;
                        WorkEntryCreated?.Invoke(wEntry);
                        return(true);
                    }
                    else
                    {
                        WorkEntryCreationFailed?.Invoke(wEntry);
                        Logger.WarnFormat("Didn't get the expected status code back when creating a work entry for {0}. Got {1}", wEntry.IssueId, response.StatusCode);
                    }
                }
            }
            catch (WebException we)
            {
                WorkEntryCreationFailed?.Invoke(wEntry);
                Logger.Error("Unable add work entry", we);
            }

            EncounteredError = true;
            return(false);
        }
        private static async Task <WorkEntry> CreateWorkEntry(ApplicationDbContext dbContext, string createdBy, Action <WorkEntry> modifier = null)
        {
            var entry = new WorkEntry
            {
                Id         = Guid.NewGuid(),
                HoursSpent = 5,
                Date       = DateTime.Now.Date,
                Notes      = "Notes",
                UserId     = createdBy
            };

            if (modifier != null)
            {
                modifier(entry);
            }

            dbContext.Add(entry);
            await dbContext.SaveChangesAsync();

            return(entry);
        }
        public async Task UpdateAsync_EntryExists_UpdatesEntry()
        {
            // Arrange
            using var dbContext = CreateDbContext();
            var user = await CreateTestUserAsync(dbContext);

            var entry = await CreateWorkEntry(dbContext, user.Id);

            var userContextAccessorMock = new Mock <IUserContextAccessor>();

            userContextAccessorMock.Setup(m => m.GetUserId()).Returns(user.Id);
            userContextAccessorMock.Setup(m => m.IsAdminUser()).Returns(false);

            var workEntriesService = new WorkEntriesService(dbContext, Mock.Of <IDbErrorHandler>(), userContextAccessorMock.Object);

            // Act
            var entryToUpdate = new WorkEntry
            {
                Id         = entry.Id,
                Date       = new DateTime(2021, 1, 1),
                HoursSpent = 6,
                UserId     = user.Id + "1",
                Notes      = "Some notes..."
            };

            entry = await workEntriesService.UpdateAsync(entryToUpdate);

            Assert.NotEqual(entryToUpdate.UserId, entry.UserId);

            // Line above tests that a user can't update the UserId field.
            // Now assign the same user id to compare all properties of both objects,
            // otherwise assert will fail
            entryToUpdate.UserId = entry.UserId;
            AssertEqual(entryToUpdate, entry);

            // assert entry state directly in the database
            entry = await dbContext.WorkEntries.FindAsync(entry.Id);

            AssertEqual(entryToUpdate, entry);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Syncs the Jira entry with the work entry
        /// </summary>
        /// <param name="jEntry">Jira entry to update</param>
        /// <param name="wEntry">Work entry to update Jira with</param>
        /// <returns>True if updated successfully</returns>
        public bool SyncWorkEntry(JiraWorkEntry jEntry, WorkEntry wEntry)
        {
            jEntry.TimeSpent        = wEntry.TimeSpent;
            jEntry.TimeSpentSeconds = 0;

            Logger.DebugFormat("Syncronizing {0} in {1}", wEntry.TogglId, wEntry.IssueId);
            HttpWebRequest request = GetRequest(jEntry.Self, false);

            request.ContentType = "application/json;charset=UTF-8";
            request.Method      = "PUT";

            try
            {
                WriteWorkEntry(jEntry, request);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        EncounteredError = false;
                        WorkEntryUpdated?.Invoke(wEntry);
                        return(true);
                    }
                    else
                    {
                        EncounteredError = true;
                        WorkEntryUpdateFailed?.Invoke(wEntry);
                        Logger.WarnFormat("Didn't get the expected status code back when syncing a work entry for {0}. Got {1}", wEntry.IssueId, response.StatusCode);
                    }
                }
            }
            catch (WebException we)
            {
                EncounteredError = true;
                WorkEntryUpdateFailed?.Invoke(wEntry);
                Logger.Error("Unable to sync web entry", we);
            }

            return(false);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Adds the gived entry to the worklog of its issue
        /// </summary>
        /// <param name="wEntry">Worklog entry to add</param>
        /// <returns>True if added successfully</returns>
        public bool AddWorkEntry(WorkEntry wEntry)
        {
            JiraWorkEntry jEntry = new JiraWorkEntry
            {
                Started   = GetStartTime(wEntry),
                Comment   = wEntry.CommentWithMarker,
                TimeSpent = wEntry.TimeSpent
            };

            Logger.DebugFormat("Creating a entry for {0} corresponding to {1}.", wEntry.IssueId, wEntry.TogglId);


            try
            {
                using (IHttpResponse response = GetResponse(() => GetWorkEntryRequest(jEntry, ServerUrl + string.Format(GetWorklogUrl, wEntry.IssueId), "POST")))
                {
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        Logger.DebugFormat("Work entry created for issue {0}", wEntry.IssueId);
                        EncounteredError = false;
                        WorkEntryCreated?.Invoke(wEntry);
                        return(true);
                    }
                    else
                    {
                        WorkEntryCreationFailed?.Invoke(wEntry);
                        Logger.WarnFormat("Didn't get the expected status code back when creating a work entry for {0}. Got {1}", wEntry.IssueId, response.StatusCode);
                    }
                }
            }
            catch (WebException we)
            {
                WorkEntryCreationFailed?.Invoke(wEntry);
                Logger.Error("Unable add work entry", we);
            }

            EncounteredError = true;
            return(false);
        }
Exemplo n.º 25
0
        public async Task <ActionResult> PostWorkingGroupSchedule([FromBody] WorkEntry workEntry)
        {
            try
            {
                await _workEntry.Add(workEntry);
            }
            catch (DbUpdateConcurrencyException e)
            {
                _logger.LogError(e.Message);
                return(Problem(e.Message));
            }
            catch (DbUpdateException e)
            {
                _logger.LogError(e.Message);
                return(Problem(e.Message));
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message);
                return(Problem(e.Message));
            }

            return(CreatedAtAction("PostWorkingDay", new { workEntry.Id, workEntry }));
        }
Exemplo n.º 26
0
 public void Create_NoDesc()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry(null)));
 }
Exemplo n.º 27
0
 public void Create_NoDash()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry("P12: Foo")));
 }
Exemplo n.º 28
0
 public void Create_LowerCaseLetterProj()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry("p-1")));
 }
Exemplo n.º 29
0
 /// <summary>
 /// Returns a string containing the start time of the entry in a correct format for Jira
 /// </summary>
 /// <param name="wEntry">Entry to get start time from</param>
 /// <returns>Start time of the entry in a correctly formatted string</returns>
 private static string GetStartTime(WorkEntry wEntry)
 {
     return(wEntry.Start.ToString(TimeFormat) + wEntry.Start.ToString("zzz").Replace(":", ""));
 }
Exemplo n.º 30
0
 public async Task Add(WorkEntry toAdd)
 {
     _context.WorkEntries.Add(toAdd);
     await _context.SaveChangesAsync();
 }
Exemplo n.º 31
0
 public void Create_NoNumberWithDesc()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry("P- Hello")));
 }
Exemplo n.º 32
0
 public void Create_NoNumber()
 {
     Assert.IsNull(WorkEntry.Create(GetEntry("P-")));
 }