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)); } }
private void Work() { try { ConnectEntity(); //we do this here to ensure single threaded on handle! // Program.Entity.Users.Count(); //force connection to be open & test //Log.WriteLine(LogLevel.Info, "Database Initialized at {0}", Settings.Instance.Entity.DataCatalog); } catch (Exception ex) { Log.WriteLine(LogLevel.Exception, "Error initializing database: {0}", ex.ToString()); return; } Action action; while (this.IsRunning) { while (callbacks.TryDequeue(out action)) { try { UserWorkItem Work = new UserWorkItem(action); Work.Queue(); //action(); } catch (Exception ex) { Log.WriteLine(LogLevel.Exception, ex.ToString()); } } Thread.Sleep(sleep); } Log.WriteLine(LogLevel.Info, "Server stopped handling callbacks."); }
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); } }
/// <summary>A thread worker function that processes items from the work queue</summary> private static void ProcessQueuedItems() { // Get the system/hardware thread index this thread is going to use. We hope that // the threads more or less start after each other, but there is no guarantee that // tasks will be handled by the CPU cores in the order the queue was filled with. // This could be added, though, by using a WaitHandle so the thread creator could // wait for each thread to take one entry out of the queue. int hardwareThreadIndex; lock (hardwareThreads) { hardwareThreadIndex = hardwareThreads.Dequeue(); } if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // Prevent this managed thread from impersonating another system thread. // In .NET, managed threads can supposedly be moved to different system threads // and, more worryingly, even fibers. This should make sure we're sitting on // a normal system thread and stay with that thread during our lifetime. Thread.BeginThreadAffinity(); // Assign the ideal processor, but don't force it. It's not a good idea to // circumvent the thread scheduler of a desktop machine, so we try to play nice. uint threadId = Kernel32.GetCurrentThreadId(); ProcessThread thread = GetProcessThread((int)threadId); if (thread != null) { thread.IdealProcessor = hardwareThreadIndex; } } // Keep processing tasks indefinitely for (; ;) { UserWorkItem workItem = getNextWorkItem(); // Execute the work item we just picked up. Make sure to accurately // record how many callbacks are currently executing. try { Interlocked.Increment(ref inUseThreads); workItem.Callback(workItem.State); } catch (Exception exception) { // Make sure we don't throw here. ExceptionDelegate exceptionHandler = ExceptionHandler; if (exceptionHandler != null) { exceptionHandler(exception); } } finally { Interlocked.Decrement(ref inUseThreads); } } }
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); } }
/// <summary>Queues a user work item to the thread pool.</summary> /// <param name="callback"> /// A WaitCallback representing the delegate to invoke when a thread in the /// thread pool picks up the work item /// </param> /// <param name="state"> /// The object that is passed to the delegate when serviced from the thread pool /// </param> public static void QueueUserWorkItem(WaitCallback callback, object state) { // Create a waiting callback that contains the delegate and its state. // Add it to the processing queue, and signal that data is waiting. UserWorkItem waiting = new UserWorkItem(callback, state); lock (userWorkItems) { userWorkItems.Enqueue(waiting); } // Wake up one of the worker threads so this task will be processed workAvailable.Release(); }
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); }
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); }
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 static WorkItemDto ToDto(this UserWorkItem userWorkItem, int id) { WorkItemDto dto = new WorkItemDto { Id = id, TaskId = userWorkItem.TaskId, UserId = userWorkItem.UserId, WeekId = userWorkItem.WeekId, Title = userWorkItem.Title, Description = userWorkItem.Description, Sprint = userWorkItem.Sprint, Project = userWorkItem.Project, TotalHours = userWorkItem.TotalHours, WeekHours = userWorkItem.WeekHours, Status = userWorkItem.Status, ServerId = userWorkItem.ServerId, Comments = userWorkItem.Comments, EstimatedHours = userWorkItem.EstimatedHours, AssignedTo = userWorkItem.AssignedTo }; if (userWorkItem.StartDate != null) { dto.StartDate = userWorkItem.StartDate.Value.ToString(Constants.DATE_FORMAT); } if (userWorkItem.EndDate != null) { dto.EndDate = userWorkItem.EndDate.Value.ToString(Constants.DATE_FORMAT); } if (userWorkItem.ETA != null) { dto.ETA = userWorkItem.ETA.Value.ToString(Constants.DATE_FORMAT); } return(dto); }
private void Work() { try { //ConnectEntity(); // Program.Entity.Characters.Count(); //test if database is online // Log.WriteLine(LogLevel.Info, "Database Initialized at {0}", Settings.Instance.Entity.DataCatalog); } catch (Exception ex) { Log.WriteLine(LogLevel.Exception, "Error initializing database: {0}", ex.ToString()); return; } Action action; var pingCheckRan = DateTime.Now; var lastClientTime = DateTime.Now; ulong last = 0; var lastCheck = DateTime.Now; for (ulong i = 0;; i++) { if (!IsRunning) { break; } var now = DateTime.Now; while (_callbacks.TryDequeue(out action)) { try { var Work = new UserWorkItem(action); Work.Queue(); //action(); } catch (Exception ex) { Log.WriteLine(LogLevel.Exception, ex.ToString()); } } if (now.Subtract(pingCheckRan).TotalSeconds >= 15) { // Just check every minute ClientManager.Instance.PingCheck(now); pingCheckRan = now; } if (now.Subtract(lastCheck).TotalSeconds >= 1) { TicksPerSecond = i - last; last = i; lastCheck = now; //Log.WriteLine(LogLevel.Debug, "TicksPerSecond: {0}", TicksPerSecond); if (TicksPerSecond <= 100) { Log.WriteLine(LogLevel.Warn, "Server overload! Only {0} ticks per second!", TicksPerSecond); } } if (now.Subtract(lastClientTime).TotalSeconds >= 60) { ClientManager.Instance.UpdateClientTime(now); lastClientTime = now; } if (i % TicksToSleep == 0) { Program.CurrentTime = DateTime.Now; Thread.Sleep(_sleep); } } Log.WriteLine(LogLevel.Info, "Server stopped handling callbacks."); }
private void Work() { while (Program.ServiceInfo == null) { System.Threading.Thread.Sleep(200); // Wait.. } try { // Estrella.Database.DatabaseHelper.Initialize(Settings.Instance.WorldConnString, "WorkerConn"); // Program.Entity.Characters.Count(); //test if database is online Log.WriteLine(LogLevel.Info, "Database Initialized."); } catch (Exception ex) { Log.WriteLine(LogLevel.Exception, "Error initializing database: {0}", ex.ToString()); return; } Action action; ulong last = 0; DateTime lastCheck = DateTime.Now; DateTime lastPing = DateTime.Now; DateTime lastGC = DateTime.Now; DateTime lastClientTime = DateTime.Now; DateTime LastMountCheck = DateTime.Now; for (ulong i = 0; ; i++) { if (!this.IsRunning) { break; } try { DateTime now = Program.CurrentTime; while (callbacks.TryDequeue(out action)) { try { UserWorkItem Work = new UserWorkItem(action); Work.Queue(); // action(); } catch (Exception ex) { Log.WriteLine(LogLevel.Exception, ex.ToString()); } } if (now.Subtract(lastCheck).TotalSeconds >= 1) { TicksPerSecond = i - last; last = i; lastCheck = now; //Log.WriteLine(LogLevel.Debug, "TicksPerSecond: {0}", TicksPerSecond); if (TicksPerSecond <= 100) { Log.WriteLine(LogLevel.Warn, "Server overload! Only {0} ticks per second!", TicksPerSecond); } } if (now.Subtract(lastPing).TotalSeconds >= 300) { ClientManager.Instance.PingCheck(); lastPing = now; } if (now.Subtract(lastGC).TotalSeconds >= 300) { GC.Collect(); lastGC = now; } if (now.Subtract(lastClientTime).TotalSeconds >= 60) { } if (now.Subtract(LastMountCheck).TotalSeconds >= 30) { ClientManager.Instance.UpdateMountTicks(now); LastMountCheck = now; } if (i % 2000 == 0 && MapManager.Instance != null) { foreach (var val in MapManager.Instance.Maps) { foreach (var map in val.Value) { map.Update(now); //test } } } if (i % ticksToSleep == 0) // No max load but most ticks to be parsed. Epic win! { Program.CurrentTime = DateTime.Now; // Laaast update Thread.Sleep(sleep); } } catch (Exception ex) { Log.WriteLine(LogLevel.Exception, "Ohgod. {0}", ex.ToString()); } } Log.WriteLine(LogLevel.Info, "Server stopped handling callbacks."); }
/// <summary>Queues a user work item to the thread pool.</summary> /// <param name="callback"> /// A WaitCallback representing the delegate to invoke when a thread in the /// thread pool picks up the work item /// </param> /// <param name="state"> /// The object that is passed to the delegate when serviced from the thread pool /// </param> public static void QueueUserWorkItem(WaitCallback callback, object state) { // Create a waiting callback that contains the delegate and its state. // Add it to the processing queue, and signal that data is waiting. UserWorkItem waiting = new UserWorkItem(callback, state); lock(userWorkItems) { userWorkItems.Enqueue(waiting); } // Wake up one of the worker threads so this task will be processed workAvailable.Release(); }
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); }
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; } }