Esempio n. 1
0
        public void GetWorkItem_OnValidRequest_ReturnsWorkItem()
        {
            // ARRANGE
            DbContextOptions <TestDatabaseContext> options = new DbContextOptionsBuilder <TestDatabaseContext>()
                                                             .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                                                             .Options;
            IDatabaseContext   dbContext  = new TestDatabaseContext(options);
            WorkItemRepository repository = new WorkItemRepository(dbContext);
            WorkItemConverter  converter  = new WorkItemConverter(dbContext);

            WorkItem workItem = new WorkItem()
            {
                Description          = Guid.NewGuid().ToString(),
                Name                 = Guid.NewGuid().ToString(),
                WorkItemEnd          = DateTime.Now,
                WorkItemStart        = DateTime.Now,
                WorkItemCollectionId = 1
            };

            dbContext.WorkItems.Add(workItem);

            dbContext.SaveChanges();

            // ACT
            WorkItemPublic result = repository.GetWorkItem(1);

            // ASSERT
            result.Should().BeEquivalentTo <WorkItemPublic>(converter.Convert(workItem));
        }
Esempio n. 2
0
        private static void GetWorkItem(APIHelper aPIHelper, AzureServiceConfiguration azureServiceConfiguration)
        {
            Console.WriteLine($"Obtendo os dados do Work Item de ID {azureServiceConfiguration.LastWorkItemID}");
            WorkItemDTO workItemDTO = aPIHelper.Get <WorkItemDTO>($"{azureServiceConfiguration.Organization}/{azureServiceConfiguration.Project}/_apis/wit/workitems/{azureServiceConfiguration.LastWorkItemID}?fields=System.Id,System.Title,System.WorkItemType,System.CreatedDate&api-version=5.1").GetAwaiter().GetResult();

            if (workItemDTO != null)
            {
                Console.WriteLine($"Dados do Work Item de ID {azureServiceConfiguration.LastWorkItemID} foram encontrados e serão adicionados ao banco de dados");

                WorkItemRepository workItemRepository = new WorkItemRepository(new AzureDevOpsDbContextFactory().CreateDbContext());
                workItemRepository.Add(new WorkItem {
                    ID        = workItemDTO.fields.SystemId,
                    Title     = workItemDTO.fields.SystemTitle,
                    Type      = workItemDTO.fields.SystemWorkItemType,
                    CreatedOn = workItemDTO.fields.SystemCreatedDate
                });

                azureServiceConfiguration.LastWorkItemID++;
                GetWorkItem(aPIHelper, azureServiceConfiguration);
            }
            else
            {
                Console.WriteLine($"Dados do Work Item de ID {azureServiceConfiguration.LastWorkItemID} não foram encontrados a rotina será encerrada");
                azureServiceConfiguration.LastWorkItemID--;
                azureServiceConfigurationRepository.Update(azureServiceConfiguration);
            }
        }
        public int AddWorkItem(WorkItemDto dto, string userId)
        {
            UserWorkItem workItem = null;

            using (WorkItemRepository workItemRepository = new WorkItemRepository())
            {
                workItem = workItemRepository
                           .Find(x => x.TaskId == dto.TaskId &&
                                 x.WeekId == dto.WeekId &&
                                 x.UserId == userId &&
                                 x.ServerId == dto.ServerId);

                if (workItem != null)
                {
                    throw new Exception("Work Item already exists");
                }

                // Add a new work item.
                UserWorkItem userWorkItem = new UserWorkItem
                {
                    WeekId      = dto.WeekId,
                    UserId      = dto.UserId,
                    TaskId      = dto.TaskId,
                    ServerId    = dto.ServerId,
                    Title       = dto.Title,
                    Description = dto.Description
                };

                return(workItemRepository.Insert(userWorkItem));
            }
        }
        public int MoveWorkItemToPrevious(WorkItemDto workItemDto)
        {
            if (workItemDto == null)
            {
                throw new ArgumentNullException(nameof(workItemDto), "WorkItem cannot be null");
            }

            int workItemWeekId = workItemDto.WeekId;
            int previousWeekId = -1;

            using (WeekInfoRepository weekInfoRepository = new WeekInfoRepository())
            {
                WeekInfo weekInfo = weekInfoRepository.Find(x => x.Id == workItemWeekId);
                if (weekInfo == null)
                {
                    throw new Exception("Week not found.");
                }

                DateTime startDate = weekInfo.StartDate;
                DateTime nextDate  = startDate.AddDays(-7);
                weekInfo = weekInfoRepository
                           .Find(x => DbFunctions.TruncateTime(x.StartDate) == nextDate);
                if (weekInfo == null)
                {
                    throw new Exception("Next Week not found.");
                }
                previousWeekId = weekInfo.Id;
            }

            using (WorkItemRepository workItemRepository = new WorkItemRepository())
            {
                UserWorkItem workItem = workItemRepository.Find(x => x.Id == workItemDto.Id);
                if (workItem == null)
                {
                    throw new Exception("Work Item not found");
                }

                // Validate if work item already exists in previous week.
                UserWorkItem previousWeekWorkItem = workItemRepository
                                                    .Find(x => x.TaskId == workItemDto.TaskId &&
                                                          x.WeekId == previousWeekId &&
                                                          x.ServerId == workItemDto.ServerId);
                if (previousWeekWorkItem != null)
                {
                    workItemRepository.Delete(previousWeekWorkItem);
                }

                workItem.WeekId = previousWeekId;
                workItem.State  = WorkItemState.New;
                int nextWorkItemId = workItemRepository.Insert(workItem);

                UserWorkItem currentWorkItem = workItemRepository.Find(x => x.Id == workItemDto.Id);
                // update the current work item.
                currentWorkItem.State = WorkItemState.Moved;
                workItemRepository.Update(currentWorkItem);

                return(nextWorkItemId);
            }
        }
Esempio n. 5
0
 public UnitOfWork(ApplicationDbContext dbContext)
 {
     _dbContext          = dbContext;
     _projectRepository  = new ProjectRepository(_dbContext);
     _userRepository     = new UserRepository(_dbContext);
     _workItemRepository = new WorkItemRepository(_dbContext);
     _commentRepository  = new CommentRepository(_dbContext);
 }
Esempio n. 6
0
        public IEnumerable <WorkItem> GetItems(int limit)
        {
            string             connectionString = ConfigurationManager.ConnectionStrings["WorkTrekEntities"].ConnectionString;
            WorkItemRepository repository       = new WorkItemRepository(connectionString);
            var list = repository.Entities.Take(limit).ToList();

            return(list);
        }
 public List <WorkItemDto> GetWorkItemByTaskId(int taskId, int weekId)
 {
     using (WorkItemRepository repository = new WorkItemRepository())
     {
         return(repository
                .Filter(x => x.TaskId == taskId && x.WeekId == weekId)
                .Select(x => x.ToDto(x.Id)).ToList());
     }
 }
        public List <WorkItemDto> GetUserSyncedTasksByDateRange(DateTime fromDate, DateTime endDate, string userId, bool includeIncompleteItems = false)
        {
            List <WorkItemDto> workItemDtos = new List <WorkItemDto>();

            if (fromDate.Date > DateTime.Today.Date.AddDays(7))
            {
                return(workItemDtos);
            }

            if (endDate.Date < fromDate.Date)
            {
                return(workItemDtos);
            }
            WeekInfo   currentWeekInfo = null;
            List <int> weekIdRange     = new List <int>();

            using (WeekInfoRepository repository = new WeekInfoRepository())
            {
                currentWeekInfo = repository.GetCurrentWeekInfo();
                if (currentWeekInfo == null)
                {
                    throw new Exception("Current Week is not registered.");
                }

                IQueryable <WeekInfo> weekItems = repository.FilterLocal(
                    x => DbFunctions.TruncateTime(x.StartDate) >= fromDate &&
                    DbFunctions.TruncateTime(x.EndDate) <= endDate);

                weekIdRange = weekItems.Select(x => x.Id).ToList();
            }
            if (weekIdRange.Count == 0 && !includeIncompleteItems)
            {
                return(workItemDtos);
            }

            // Get Current Week Tasks.
            if (weekIdRange.Contains(currentWeekInfo.Id))
            {
                List <WorkItemDto> userWorkItems = GetUserCurrentWeekSyncedTasks(userId, includeIncompleteItems);
                workItemDtos.AddRange(userWorkItems);
                weekIdRange = weekIdRange.Except(new List <int>()
                {
                    currentWeekInfo.Id
                }).ToList();
            }

            // Get other week Tasks.
            using (WorkItemRepository repository = new WorkItemRepository())
            {
                List <WorkItemDto> otherWeekWorkItems =
                    repository.Filter(x => weekIdRange.Contains(x.WeekId)).ToList()
                    .Select(x => x.ToDto(x.Id)).ToList();
                workItemDtos.AddRange(otherWeekWorkItems);
            }

            return(workItemDtos);
        }
Esempio n. 9
0
 public WorkItemFileManager(
     WorkItemPermissionManager workItemPermissionManager,
     UserContext userContext,
     WorkItemRepository repository)
 {
     this.workItemPermissionManager = workItemPermissionManager;
     this.userContext = userContext;
     this.repository  = repository;
 }
        public int CopyWorkItemToNext(WorkItemDto workItemDto)
        {
            if (workItemDto == null)
            {
                throw new ArgumentNullException(nameof(workItemDto), "WorkItem cannot be null");
            }

            int workItemWeekId = workItemDto.WeekId;
            int nextWeekId     = -1;

            using (WeekInfoRepository weekInfoRepository = new WeekInfoRepository())
            {
                WeekInfo weekInfo = weekInfoRepository.Find(x => x.Id == workItemWeekId);
                if (weekInfo == null)
                {
                    throw new Exception("Week not found.");
                }

                DateTime startDate = weekInfo.StartDate;
                DateTime nextDate  = startDate.AddDays(7);
                weekInfo = weekInfoRepository
                           .Find(x => DbFunctions.TruncateTime(x.StartDate) == nextDate);
                if (weekInfo == null)
                {
                    throw new Exception("Next Week not found.");
                }
                nextWeekId = weekInfo.Id;
            }

            using (WorkItemRepository workItemRepository = new WorkItemRepository())
            {
                UserWorkItem workItem = workItemRepository.Find(x => x.Id == workItemDto.Id);
                if (workItem == null)
                {
                    throw new Exception("Work Item not found");
                }

                // Validate if work item already exists in next week.
                UserWorkItem nextWeekWorkItem = workItemRepository
                                                .Find(x => x.TaskId == workItemDto.TaskId &&
                                                      x.WeekId == nextWeekId &&
                                                      x.ServerId == workItemDto.ServerId);
                if (nextWeekWorkItem != null)
                {
                    workItemRepository.Delete(nextWeekWorkItem);
                }

                // Clone the work item.
                workItem.WeekId = nextWeekId;
                workItem.State  = WorkItemState.New;
                int nextWorkItemId = workItemRepository.Insert(workItem);

                return(nextWorkItemId);
            }
        }
        public override void Initialize(object sender, SectionInitializeEventArgs e)
        {
            base.Initialize(sender, e);
            _settingsRepository = new SettingsRepository(e.ServiceProvider);
            _workItemRepository = new WorkItemRepository(CurrentContext);
            var view = new MyWorkItemsSectionView();

            SectionContent   = view;
            view.DataContext = this;
            view.Loaded     += ViewOnLoaded;
        }
        public void ShouldGetUpdatesForWorkItem()
        {
            using (var client = new HttpClient() { BaseAddress = new Uri(ConfigurationManager.AppSettings["VSOnlineBaseUrl"]) })
            {
                var connection = new TfsConnection(userName, password, client);
                var repo = new WorkItemRepository(connection);

                var results = repo.GetWorkItemUpdates(86);
                Assert.IsTrue(results.Result.Where(s => s.ChangedDate != string.Empty).All(s => s.Id != 0));
            }
        }
 public bool DeleteWorkItem(WorkItemDto dto, string userId)
 {
     using (WorkItemRepository workItemRepository = new WorkItemRepository())
     {
         UserWorkItem workItem = workItemRepository.Find(x => x.Id == dto.Id);
         if (workItem != null)
         {
             workItemRepository.Delete(workItem);
             return(true);
         }
     }
     return(false);
 }
Esempio n. 14
0
        public void ShouldGetWorkItemsFromQuery()
        {
            using (var client = new HttpClient()
            {
                BaseAddress = new Uri(ConfigurationManager.AppSettings["VSOnlineBaseUrl"])
            })
            {
                var connection = new TfsConnection(userName, password, client);
                var repo       = new WorkItemRepository(connection);
                var results    = repo.GetInProcAndClosedWorkItems(@"BPS.Scrum\Dev -SEP Project");

                Assert.IsTrue(results.Result.WorkItems.All(r => r.Id != 0));
            }
        }
Esempio n. 15
0
        public void ShouldGetUpdatesForWorkItem()
        {
            using (var client = new HttpClient()
            {
                BaseAddress = new Uri(ConfigurationManager.AppSettings["VSOnlineBaseUrl"])
            })
            {
                var connection = new TfsConnection(userName, password, client);
                var repo       = new WorkItemRepository(connection);

                var results = repo.GetWorkItemUpdates(86);
                Assert.IsTrue(results.Result.Where(s => s.ChangedDate != string.Empty).All(s => s.Id != 0));
            }
        }
        public WorkItemDto GetWorkItemByTaskId(int taskId, int weekId, int serverId)
        {
            WorkItemDto workItem = null;

            using (WorkItemRepository workItemRepository = new WorkItemRepository())
            {
                UserWorkItem entity = workItemRepository.
                                      Find(x => x.TaskId == taskId && x.WeekId == weekId && x.ServerId == x.ServerId);
                if (entity != null)
                {
                    return(entity.ToDto(entity.Id));
                }
            }
            return(workItem);
        }
Esempio n. 17
0
 private void GetWorkItemStore()
 {
     try
     {
         string        tfsUrl            = (string)Session["TfsUrl"];
         string        collectionName    = (string)Session["SelectedCollection"];
         Uri           teamCollectionUri = new Uri(tfsUrl + "/" + collectionName);
         WorkItemStore workItemStore     = WorkItemRepository.Get(teamCollectionUri);
         Session["WorkItemStore"] = workItemStore;
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
Esempio n. 18
0
        public void UpdateWorkItem_OnValidRequest_UpdatesWorkItem()
        {
            // ARRANGE
            DbContextOptions <TestDatabaseContext> options = new DbContextOptionsBuilder <TestDatabaseContext>()
                                                             .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                                                             .Options;
            IDatabaseContext   dbContext  = new TestDatabaseContext(options);
            WorkItemRepository repository = new WorkItemRepository(dbContext);
            WorkItemPublic     workItem   = new WorkItemPublic()
            {
                ID                   = 1,
                Description          = Guid.NewGuid().ToString(),
                Name                 = Guid.NewGuid().ToString(),
                WorkItemEnd          = DateTime.Now,
                WorkItemStart        = DateTime.Now,
                WorkItemCollectionID = 1
            };

            dbContext.WorkItems.Add(new WorkItem()
            {
                ID = 1
            });

            dbContext.WorkItemCollections.Add(new WorkItemCollection()
            {
                ID          = 1,
                TaskBoardId = 1
            });

            dbContext.TaskBoards.Add(new TaskBoard()
            {
                ID     = 1,
                UserID = 1
            });

            dbContext.Users.Add(new User()
            {
                ID = 1
            });

            dbContext.SaveChanges();

            // ACT
            WorkItemPublic result = repository.UpdateWorkItem(workItem);

            // ASSERT
            result.Should().BeEquivalentTo <WorkItemPublic>(workItem);
        }
Esempio n. 19
0
        public WorkItemDto GetWorkItemById(int taskId, int serverId, int weekId, string userId)
        {
            UserWorkItem userWorkItem = null;

            using (WorkItemRepository repository = new WorkItemRepository())
            {
                userWorkItem = repository.Find(
                    x => x.TaskId == taskId &&
                    x.ServerId == serverId &&
                    x.WeekId == weekId &&
                    x.UserId == userId);
            }
            if (userWorkItem == null)
            {
                return(null);
            }
            return(userWorkItem.ToDto(userWorkItem.Id));
        }
        public void ShouldGetworkItems()
        {
            using (var client = new HttpClient() { BaseAddress = new Uri(ConfigurationManager.AppSettings["VSOnlineBaseUrl"]) })
            {
                var connection = new TfsConnection(userName, password, client);
                var repo = new WorkItemRepository(connection);
                var results = repo.GetInProcAndClosedWorkItems(@"BPS.Scrum\Dev -SEP Project");
                var workItemIds = results.Result.WorkItems.Select(r => r.Id).ToArray();

                var wi = repo.GetWorkItems(workItemIds);
                Assert.IsNotNull(wi.Result.First().Id);
                Assert.IsNotNull(wi.Result.First().Rev);
                Assert.IsNotNull(wi.Result.First().Title);
                Assert.IsNotNull(wi.Result.First().Effort);
                Assert.IsNotNull(wi.Result.First().State);
                Assert.IsNotNull(wi.Result.First().ChangedDate);
                Assert.IsNotNull(wi.Result.First().ClosedDate);
            }
        }
Esempio n. 21
0
        public void DeleteWorkItem_OnValidRequest_DeletesWorkItem()
        {
            // ARRANGE
            DbContextOptions <TestDatabaseContext> options = new DbContextOptionsBuilder <TestDatabaseContext>()
                                                             .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                                                             .Options;
            IDatabaseContext   dbContext  = new TestDatabaseContext(options);
            WorkItemRepository repository = new WorkItemRepository(dbContext);

            dbContext.WorkItems.Add(new WorkItem()
            {
                ID = 1
            });

            dbContext.SaveChanges();

            // ACT
            repository.DeleteWorkItem(1);

            // ASSERT
            dbContext.WorkItems.Any(wi => wi.ID == 1).Should().BeFalse();
        }
Esempio n. 22
0
        public void ShouldGetworkItems()
        {
            using (var client = new HttpClient()
            {
                BaseAddress = new Uri(ConfigurationManager.AppSettings["VSOnlineBaseUrl"])
            })
            {
                var connection  = new TfsConnection(userName, password, client);
                var repo        = new WorkItemRepository(connection);
                var results     = repo.GetInProcAndClosedWorkItems(@"BPS.Scrum\Dev -SEP Project");
                var workItemIds = results.Result.WorkItems.Select(r => r.Id).ToArray();

                var wi = repo.GetWorkItems(workItemIds);
                Assert.IsNotNull(wi.Result.First().Id);
                Assert.IsNotNull(wi.Result.First().Rev);
                Assert.IsNotNull(wi.Result.First().Title);
                Assert.IsNotNull(wi.Result.First().Effort);
                Assert.IsNotNull(wi.Result.First().State);
                Assert.IsNotNull(wi.Result.First().ChangedDate);
                Assert.IsNotNull(wi.Result.First().ClosedDate);
            }
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            using (var workItemRepo = new WorkItemRepository())
            {
                const string c_collectionUri = "https://fabrikam.visualstudio.com/DefaultCollection";
                const string c_projectName   = "MyGreatProject";
                const string c_repoName      = "MyRepo";

                // Interactively ask the user for credentials, caching them so the user isn't constantly prompted
                VssCredentials creds = new VssClientCredentials();
                creds.Storage = new VssClientCredentialStorage();

                // Connect to VSTS
                VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);

                // Get a GitHttpClient to talk to the Git endpoints
                GitHttpClient gitClient = connection.GetClient <GitHttpClient>();

                // Get data about a specific repository
                var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;

                var a = workItemRepo.GetAll().ToList();
            }
        }
 public void SetUp()
 {
     _workItemRepository = new WorkItemRepository(_connection);
 }
Esempio n. 25
0
        public List <WorkItemDto> GetUserCurrentWeekSyncedTasks(string userId, bool includeIncompleteItems = true)
        {
            List <WorkItemDto> currentWeekTasks = new List <WorkItemDto>();
            WeekInfo           currentWeek      = null;

            UserInfo currentUser = null;

            using (UserInfoRepository userInfoRepository = new UserInfoRepository())
            {
                currentUser = userInfoRepository.Find(x => x.UserId == userId);
                if (currentUser == null)
                {
                    throw new Exception(string.Format("User Id {0} not found", userId));
                }
            }

            // Get current week.
            using (WeekInfoRepository repository = new WeekInfoRepository())
            {
                currentWeek = repository.GetCurrentWeekInfo();
                if (currentWeek == null)
                {
                    throw new Exception("Current Week is not registered.");
                }
            }

            // Get servers configured for the user.
            List <UserServerInfo> userServers = new List <UserServerInfo>();

            using (UserServerInfoRepository repository = new UserServerInfoRepository())
            {
                userServers = repository.Filter(x => x.UserId == userId).ToList();
            }

            // Get user incomplete tasks from task repository.
            List <int> currentWeekTaskIdList    = new List <int>();
            List <int> currentWeekMovedTaskList = new List <int>();

            foreach (UserServerInfo server in userServers)
            {
                using (WorkItemRepository workItemRepository = new WorkItemRepository())
                {
                    IQueryable <UserWorkItem> currentWeekSavedTasks = workItemRepository
                                                                      .Filter(x => x.ServerId == server.Id &&
                                                                              x.UserId == userId &&
                                                                              x.State != WorkItemState.Moved &&
                                                                              x.WeekId == currentWeek.Id);

                    IQueryable <UserWorkItem> currentWeekMovedTasks = workItemRepository
                                                                      .Filter(x => x.ServerId == server.Id &&
                                                                              x.UserId == userId &&
                                                                              x.State == WorkItemState.Moved &&
                                                                              x.WeekId == currentWeek.Id);

                    currentWeekTaskIdList    = currentWeekSavedTasks.Select(x => x.TaskId).ToList();
                    currentWeekMovedTaskList = currentWeekSavedTasks.Select(x => x.TaskId).ToList();
                }

                TeamServer teamServer = null;
                using (TeamServerRepository repository = new TeamServerRepository())
                {
                    teamServer = repository.Find(x => x.Id == server.TfsId);
                    if (teamServer == null)
                    {
                        continue;
                    }
                }

                // Get all tasks by id including to do items.
                List <WorkItem> userIncompleteItems = _teamServerManagementService
                                                      .GetWorkItemsByIds(currentWeekTaskIdList, teamServer.Url, server.CredentialHash, includeIncompleteItems);
                using (WorkItemRepository workItemRepository = new WorkItemRepository())
                {
                    foreach (WorkItem item in userIncompleteItems)
                    {
                        // Add new items.
                        UserWorkItem existingWorkItem = workItemRepository.Find(x => x.UserId == userId &&
                                                                                x.WeekId == currentWeek.Id &&
                                                                                x.TaskId == item.Id);
                        if (existingWorkItem == null)
                        {
                            UserWorkItem newWorkItem = item.ToEntity(server.TfsId);
                            newWorkItem.UserId     = userId;
                            newWorkItem.AssignedTo = currentUser.FirstName + " " + currentUser.LastName;
                            newWorkItem.WeekId     = currentWeek.Id;
                            int newWorkItemId = workItemRepository.Insert(newWorkItem);

                            currentWeekTasks.Add(newWorkItem.ToDto(newWorkItemId));
                        }
                        else
                        {
                            existingWorkItem.Title       = item.Title;
                            existingWorkItem.Status      = item.State;
                            existingWorkItem.Sprint      = item.IterationPath;
                            existingWorkItem.Project     = item.AreaPath;
                            existingWorkItem.Description = item.Description;

                            workItemRepository.Update(existingWorkItem);
                            currentWeekTasks.Add(existingWorkItem.ToDto(existingWorkItem.Id));
                        }
                    }
                }
            }
            return(currentWeekTasks);
        }
Esempio n. 26
0
 public WorkItemService()
 {
     workItemRepository = new WorkItemRepository(new AzureDevOpsDbContextFactory().CreateDbContext());
 }
        public void ShouldGetWorkItemsFromQuery()
        {
            using (var client = new HttpClient() { BaseAddress = new Uri(ConfigurationManager.AppSettings["VSOnlineBaseUrl"]) })
            {
                var connection = new TfsConnection(userName, password, client);
                var repo = new WorkItemRepository(connection);
                var results = repo.GetInProcAndClosedWorkItems(@"BPS.Scrum\Dev -SEP Project");

                Assert.IsTrue(results.Result.WorkItems.All(r => r.Id != 0));
            }
        }
Esempio n. 28
0
        public List <WorkItemDto> GetUserIncompleteSyncedTasks(int serverId, string userId)
        {
            TeamServer         server           = null;
            List <WorkItemDto> workItemsDtoList = new List <WorkItemDto>();
            UserServerInfo     userServerInfo   = null;

            try
            {
                using (TeamServerRepository teamServerRepository = new TeamServerRepository())
                {
                    server = teamServerRepository.GetById(serverId);
                    if (server == null)
                    {
                        throw new Exception(string.Format("Invalid Server Id : {0}", serverId));
                    }
                }

                UserInfo userInfo = null;
                using (UserInfoRepository userInfoRepository = new UserInfoRepository())
                {
                    userInfo = userInfoRepository.Find(x => x.UserId == userId);
                    if (userInfo == null)
                    {
                        throw new Exception(string.Format("User with ID {0} Not Found", userId));
                    }
                }

                using (UserServerInfoRepository userServerInfoRepository = new UserServerInfoRepository())
                {
                    userServerInfo = userServerInfoRepository.FindLocal(
                        x => x.UserId == userId &&
                        x.TfsId == serverId
                        );
                    if (userServerInfo == null)
                    {
                        throw new Exception(string.Format("User with id : {0} is not registered with server id : {1}", userId, serverId));
                    }
                }

                string credentialHash = userServerInfo.CredentialHash;
                string url            = server.Url;

                WeekInfo currentWeek = null;
                using (WeekInfoRepository weekInfoRepository = new WeekInfoRepository())
                {
                    currentWeek = weekInfoRepository.GetCurrentWeekInfo();
                    if (currentWeek == null)
                    {
                        throw new Exception("Current Week is not registered.");
                    }
                }
                List <WorkItem> tfsWorkItems = _teamServerManagementService.GetUserIncompleteItems(url, credentialHash);
                using (WorkItemRepository workItemRepository = new WorkItemRepository())
                {
                    foreach (WorkItem item in tfsWorkItems)
                    {
                        // Add new items.
                        UserWorkItem existingWorkItem = workItemRepository.Find(x => x.UserId == userId &&
                                                                                x.WeekId == currentWeek.Id &&
                                                                                x.TaskId == item.Id);
                        if (existingWorkItem == null)
                        {
                            UserWorkItem newWorkItem = item.ToEntity(userServerInfo.TfsId);
                            newWorkItem.UserId     = userId;
                            newWorkItem.AssignedTo = userInfo.FirstName + " " + userInfo.LastName;
                            newWorkItem.WeekId     = currentWeek.Id;
                            int newWorkItemId = workItemRepository.Insert(newWorkItem);

                            workItemsDtoList.Add(newWorkItem.ToDto(newWorkItemId));
                        }
                        else
                        {
                            existingWorkItem.Title       = item.Title;
                            existingWorkItem.Status      = item.State;
                            existingWorkItem.Sprint      = item.IterationPath;
                            existingWorkItem.Project     = item.AreaPath;
                            existingWorkItem.Description = item.Description;

                            workItemRepository.Update(existingWorkItem);
                            workItemsDtoList.Add(existingWorkItem.ToDto(existingWorkItem.Id));
                        }
                    }
                }

                return(workItemsDtoList);
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw;
            }
        }