Ejemplo n.º 1
0
 public TaskViewModel(task task)
 {
     this.task = task;
     this.Title = task.title;
     this._deadline = task.Deadline.HasValue ? (DateTime?)task.Deadline.Value.ToLocalTime() : null;
     this.allDay = task.AllDay;
     this.completed = task.isComplete;
 }
Ejemplo n.º 2
0
        public void UpdateTask(UIDT uid, LineT pos, DateTime begin, DateTime end)
        {
            if (tasks.Count() < pos)
                throw new Exception("Please add tasks to gantt continiously");
            if (tasks.Count() == pos)
                tasks.Add(new TaskT());

            tasks[pos] = new TaskT(begin, end);

            positions[uid] = pos;
        }
Ejemplo n.º 3
0
	private bool taskManager(List<GameObject> team, task func){
		List<GameObject> finalEntities;
		GameObject entity;
		int numEntities;
		int index;
		bool success = false;
		
		finalEntities = potentialAttackees (team);
		numEntities = finalEntities.Count;
		for(int i = 0; numEntities > 0 && i < this.numAttack; ++i){
			index = (int)(Mathf.Floor(Random.value * numEntities));
			entity = finalEntities[index];
			finalEntities.RemoveAt(index);
			--numEntities;
			func (entity);
			xpManager ();
			success = true;
		}
		return success;
	}
Ejemplo n.º 4
0
        }//получаем список всех задач

        public bool AddTask(int Id, string name, int date_end, string FIO, int admin)
        {
            task           t  = new task();
            TaskRepository _t = new TaskRepository();

            t.taskID     = Id;
            t.name       = name;
            t.date_end   = date_end;
            t.date_start = DateTime.Today.Day;
            t.state      = "Ready to begin";
            _t.Create(t);
            _t.Save();
            if (CreatChat(Id, name) && CreateCommand(Id, Id, admin) && UpdateManager(FIO, Id))
            {
                return(true);
            }
            else
            {
                _t.Delete(Id);
                _t.Save();
                return(false);
            }
        }//добавляем задачу
Ejemplo n.º 5
0
        public int GetExDataByTNCount(string loginName, string taskName)
        {
            waterdataEntities entity  = new waterdataEntities();
            users             objuser = entity.users.SingleOrDefault(s => s.login_name == loginName);
            task task = entity.task.FirstOrDefault(s => s.task_name == taskName && s.user_id == objuser.user_id);
            IQueryable <water_data> dataquery = entity.water_data.Where(s => s.task_id == task.task_id && (s.parameter_value > s.parameter.uplimit || s.parameter_value < s.parameter.lowlimit));
            List <WaterData>        datas     = new List <WaterData>();

            foreach (var data in dataquery)
            {
                datas.Add(new WaterData()
                {
                    TaskId         = task.task_id.ToString(),
                    TaskName       = task.task_name,
                    ParameterId    = data.parameter_id.ToString(),
                    ParameterName  = data.parameter.parameter_name.ToString(),
                    ParameterValue = data.parameter_value.ToString(),
                    Longitude      = data.longitude.ToString(),
                    Latitude       = data.latitude.ToString()
                });
            }
            return(datas.Count);
        }
Ejemplo n.º 6
0
    private void run_task_non_pre(task running)
    {
        if (running.arrival_time > Timer)
        {
            Timer = running.arrival_time;
        }
        running.start_time = Timer;

        bool fi_task_gya_w_enta_48al = false;

        do    //lw fi task gya w enta 43'al
        {
            if (tasks_map.Count != 0)
            {
                if (Timer + running.duration >= tasks_map.First().Key)
                {
                    fi_task_gya_w_enta_48al = true;
                    update_current_tasks();
                }
                else
                {
                    fi_task_gya_w_enta_48al = false;
                }
            }
            else
            {
                break;
            }
        } while (fi_task_gya_w_enta_48al);

        Timer += running.duration;
        running.finish_time = Timer;
        running.finished    = true;
        task temp = new task(running);

        finished_tasks.Add(temp);
    }
Ejemplo n.º 7
0
        /// <summary>
        /// Adds a new task to a list.
        /// </summary>
        public void AddTask()
        {
            view.PrintContentTitle(listsContentTitle);
            view.ClearContent();
            view.PrintLists(context.lists.ToList(), context.tasks.ToList());
            view.PrintContent(new List <string>(), "Add task to list with ID ");

            int listID;

            if (int.TryParse(view.ReadLine(), out listID))
            {
                view.PrintContentTitle("Adding task...");
                view.ClearContent();

                list selectedList = context.lists.SingleOrDefault(x => x.list_id == listID);

                if (selectedList != null)
                {
                    view.ClearContent();
                    view.PrintLists(new List <list>()
                    {
                        selectedList
                    }, context.tasks.Where(task => task.list_id == selectedList.list_id).ToList());
                    view.PrintContent(new List <string>());
                    string newTaskContent = view.ReadLine();

                    if (newTaskContent != "")
                    {
                        task newTask = new task();
                        newTask.content = newTaskContent;
                        newTask.list_id = selectedList.list_id;
                        context.tasks.Add(newTask);
                        context.SaveChanges();
                    }
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="parameterName"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List <WaterData> GetExDataByPTN(string loginName, string parameterName, string taskName, int page, int limit)
        {
            waterdataEntities entity          = new waterdataEntities();
            users             objuser         = entity.users.SingleOrDefault(s => s.login_name == loginName);
            string            englishparamter = ToEnglish(parameterName);
            parameter         objparameter    = entity.parameter.SingleOrDefault(s => s.parameter_name == englishparamter && s.company_id == objuser.company_id);
            task task = entity.task.FirstOrDefault(s => s.task_name == taskName && s.user_id == objuser.user_id);
            IQueryable <water_data> dataquery = entity.water_data.Where(s => s.task_id == task.task_id && s.parameter_id == objparameter.parameter_id && (s.parameter_value > s.parameter.uplimit || s.parameter_value < s.parameter.lowlimit)).OrderByDescending(s => s.create_time);
            List <WaterData>        datas     = new List <WaterData>();
            string parametername = null;

            foreach (var data in dataquery)
            {
                parametername = ToChinese(data.parameter.parameter_name);
                datas.Add(new WaterData()
                {
                    TaskId         = task.task_id.ToString(),
                    TaskName       = task.task_name,
                    ParameterId    = data.parameter_id.ToString(),
                    ParameterName  = parametername,
                    ParameterValue = data.parameter_value.ToString(),
                    Longitude      = data.longitude.ToString(),
                    Latitude       = data.latitude.ToString(),
                    CreateTime     = data.create_time.ToString(),
                    WaterDataId    = data.watedata_id.ToString()
                });
            }
            int strat = (page - 1) * limit;
            int end   = strat + limit;
            List <WaterData> newdatas = new List <WaterData>();

            for (int i = strat; i < end && i < datas.Count; i++)
            {
                newdatas.Add(datas[i]);
            }
            return(newdatas);
        }
Ejemplo n.º 9
0
        public ActionResult updateTask(task task)
        {
            try
            {
                task.startdate       = DateTime.Now;
                db.Entry(task).State = EntityState.Modified;
                db.SaveChanges();

                tasklog log = checkChanged(task);
                log.taskId   = task.taskId;
                log.date     = DateTime.Now;
                log.assignto = task.assignto;
                db.tasklogs.Add(log);
                db.SaveChanges();

                updateLastActDate(task.projId);

                return(Json("Success", JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                return(Json(e.Message, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 10
0
        static async Task Main(string[] args)
        {
            var catMeowTask = catMeowAsync(1);
            var dogBarkTask = dogBarkAsync(1);
            var alltask     = new List <Task> {
                catMeowTask, dogBarkTask
            };

            Console.WriteLine("tasks");
            while (alltask.any())
            {
                task finished = await task.whenany(alltask);

                if (finished == catmeowtask)
                {
                    console.writeline("cat has meowed");
                }
                if (finished == dogbarktask)
                {
                    console.writeline("dog has barked");
                }
                alltask.remove(finished);
            }
        }
Ejemplo n.º 11
0
        // PUT: odata/Tasks(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <task> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            task task = db.tasks.Find(key);

            if (task == null)
            {
                return(NotFound());
            }

            patch.Put(task);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!taskExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(task));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 获得单个任务信息
        /// </summary>
        /// <param name="id">任务ID</param>
        /// <returns></returns>
        public task GetTask(string id)
        {
            task     tsk      = null;
            XElement root     = LoadTaskRoot();
            XElement taskinfo = root.XPathSelectElement("task[id='" + id + "']");

            if (taskinfo == null)
            {
                throw new Exception("要编辑的任务不存在");
            }
            else
            {
                tsk = new task()
                {
                    id           = taskinfo.Element("id").Value,
                    taskcontent  = taskinfo.Element("taskcontent").Value,
                    completedate = taskinfo.Element("completedate").Value,
                    createdate   = taskinfo.Element("createdate").Value,
                    taskstatus   = taskinfo.Element("taskstatus").Value,
                    keeper       = taskinfo.Element("keeper").Value
                };
            }
            return(tsk);
        }
Ejemplo n.º 13
0
    private void run_preemptive()
    {
        if (running_task.arrival_time > Timer)
        {
            Timer = running_task.arrival_time;
        }

        running_task.start_time = Timer;
        if (tasks_map.Count != 0)
        {
            running_task.start_time = Timer;

            if (tasks_map.First().Key <= (Timer + running_task.remaining_time))    //lw fi task gya w hya 43'ala
            {
                preempt();
            }
            else
            {
                running_task.start_time = Timer;
                Timer = Timer + running_task.remaining_time;
                running_task.finish_time = Timer;
                running_task.finished    = true;
                task temp = new task(running_task);
                finished_tasks.Add(temp);
            }
        }

        else    //ya3ni mafi4 7ad hyege gded 4a3'al eli 3ndk beltartib bta3k
        {
            Timer = Timer + running_task.remaining_time;
            running_task.finish_time = Timer;
            running_task.finished    = true;
            task temp = new task(running_task);
            finished_tasks.Add(temp);
        }
    }
Ejemplo n.º 14
0
 public ActionResult AddTask(task task)
 {
     try
     {
         DateValidate = new DateValidate();
         if (ModelState.IsValid)
         {
             if (DateValidate.IsDateLessThanToday(task.task_started_date) && DateValidate.IsDateLessThanToday(task.task_end_date))
             {
                 int flag = ProjectsControllerManager.saveTask(task);
                 if (flag == 1)
                 {
                     return(RedirectToAction("Index", "Projects"));
                 }
                 else
                 {
                     ModelState.AddModelError("", "Task name is already taken, Please use unique Task Names");
                     return(View());
                 }
             }
             else
             {
                 ModelState.AddModelError("", "Dates are Invalid");
                 return(View());
             }
         }
         else
         {
             return(View());
         }
     }
     catch (Exception)
     {
         return(RedirectToAction("Error", "Home"));
     }
 }
        public ActionResult ToggleDone(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            task task = db.tasks.Find(id);

            if (task == null)
            {
                return(HttpNotFound());
            }
            if (task.IsDone)
            {
                task.IsDone = false;
            }
            else
            {
                task.IsDone = true;
            }
            db.SaveChanges();

            return(RedirectToAction("Index"));
        }
        public IHttpActionResult Puttask(int id, task task)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != task.task_id)
            {
                return(BadRequest());
            }
            //

            MapTaskUser(task);

            db.Entry(task).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                //if (!taskExists(id))
                //{
                return(NotFound());

                //}
                //else
                //{
                throw;
                //}
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 17
0
      public void AddTask()
      {
          var TDate = System.Web.HttpContext.Current.Request.Form["TaskDate"];
          var Ttime = System.Web.HttpContext.Current.Request.Form["TaskTime"];
          var task  = new task();

          task.describtion = System.Web.HttpContext.Current.Request.Form["describtion"];
          task.TaskDate    = Convert.ToDateTime(TDate);
          task.TaskTime    = TimeSpan.Parse(Ttime);

          task.ApplicationUserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
          _context.task.Add(task);
          _context.SaveChanges();
          HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

          if (files.Count != 0)
          {
              for (var i = 0; i < files.Count; i++)
              {
                  HttpPostedFile file = files[i];
                  AddFile(file, task.Id);
              }
          }
      }
Ejemplo n.º 18
0
        private LineT Move(out TaskT moved)
        {
            var drift = (mouse_current_state.coords.x - mouse_enter_state.coords.x) / hour_to_pixel_ratio;
            var active_task = MouseActiveTask();
            moved = new TaskT();

            moved.start = active_task.Item2.start;
            moved.end = active_task.Item2.end;

            try
            {
                moved.start = active_task.Item2.start.AddHours(drift);
            }
            catch (System.ArgumentOutOfRangeException)
            {
                if (drift < 0)
                    moved.start = DateTime.MinValue;
                else
                    moved.start = DateTime.MaxValue;
            }

            try
            {
                moved.end = active_task.Item2.end.AddHours(drift);
            }
            catch (System.ArgumentOutOfRangeException)
            {
                if (drift < 0)
                    moved.end = DateTime.MinValue;
                else
                    moved.end = DateTime.MaxValue;
            }

            return active_task.Item1;
        }
Ejemplo n.º 19
0
        private LineT Resize(out TaskT resized)
        {
            var active = MouseActiveTask();
            var origin_start = active.Item2.start;
            var new_end = XCoordinateToDateTime((int)mouse_current_state.coords.x);

            if (new_end < origin_start)
                new_end = origin_start;

            resized = new TaskT(origin_start, new_end);

            return active.Item1;
        }
Ejemplo n.º 20
0
        public ActionResult AddTask(int id, task addTask)
        {
            if (Request.Cookies["UserID"].Value == null)
            {
                //Redirect to login if it can't find user id
                TempData["message"] = "Please log in.";
                System.Diagnostics.Debug.WriteLine("User not logged in. Redirecting to login page.\n");
                return(RedirectToAction("LandingPage", "Home"));
            }

            ViewBag.UserID = Request.Cookies["UserID"].Value;
            string message;

            using (Entities dc = new Entities())
            {
                project proj = dc.projects.Find(id);

                if (proj == null)
                {
                    message             = "Project not found.";
                    TempData["message"] = message;
                    //TODO: Redirect to somewhere more general.
                    return(RedirectToAction("MyProjects", "Home"));
                }

                ViewBag.ProjectName = proj.ProjName;
                ViewBag.ProjectID   = proj.ProjID;

                task newTask = new task()
                {
                    ProjID       = proj.ProjID,
                    TaskName     = addTask.TaskName,
                    BillableRate = addTask.BillableRate,
                    IsBillable   = true,
                };

                dc.tasks.Add(newTask);

                try
                {
                    dc.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
                {
                    Exception exception = dbEx;
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            string message1 = string.Format("{0}:{1}",
                                                            validationErrors.Entry.Entity.ToString(),
                                                            validationError.ErrorMessage);

                            //create a new exception inserting the current one
                            //as the InnerException
                            exception = new InvalidOperationException(message1, exception);
                        }
                    }
                    throw exception;
                }
            }
            message             = "Task added successfully.";
            TempData["message"] = message;
            return(RedirectToAction("AddTask", "Project", new { id = id }));
        }
Ejemplo n.º 21
0
 if (task != await Task.WhenAny(task, tcs.Task).ConfigureAwait(false))
 HandleSafeFireAndForget(task, continueOnCapturedContext, onException);
Ejemplo n.º 23
0
 /// <summary>
 /// Safely execute the Task without waiting for it to complete before moving to the next line of code; commonly known as "Fire And Forget". Inspired by John Thiriet's blog post, "Removing Async Void": https://johnthiriet.com/removing-async-void/.
 /// </summary>
 /// <param name="task">Task.</param>
 /// <param name="continueOnCapturedContext">If set to <c>true</c>, continue on captured context; this will ensure that the Synchronization Context returns to the calling thread. If set to <c>false</c>, continue on a different context; this will allow the Synchronization Context to continue on a different thread</param>
 /// <param name="onException">If an exception is thrown in the Task, <c>onException</c> will execute. If onException is null, the exception will be re-thrown</param>
 /// <typeparam name="TException">Exception type. If an exception is thrown of a different type, it will not be handled</typeparam>
 public static void SafeFireAndForget <TException>(this Task task, in bool continueOnCapturedContext = false, in Action <TException>?onException = null) where TException : Exception => HandleSafeFireAndForget(task, continueOnCapturedContext, onException);
Ejemplo n.º 24
0
        /// <summary>
        /// Creates a new entry in the database
        /// </summary>
        /// <returns>The insert ID of the new entry</returns>
        public override int New()
        {
            base.New();

            // Set default values for the new Task
            CurrentRow = new task()
            {
                created = DateTime.Now,
                title = Translate.str("Untitled"),
                clerk_id = App.CurrentUser.id,
                assignee_id = Model.Person.ANONYMOUS,
                status_id = Model.TaskStatus.DEFAULT,
                category_id = Model.TaskCategory.DEFAULT
            };

            // Create new row in the DB
            CurrentConnection.tasks.InsertOnSubmit(CurrentRow);
            CurrentConnection.SubmitChanges();

            return CurrentRow.id;
        }
Ejemplo n.º 25
0
        private void DrawRect(LineT row, TaskT interval)
        {
            var task_draw_interval = interval;

            var x1 = DateTimeToXCoordinate(task_draw_interval.start);
            var x2 = DateTimeToXCoordinate(task_draw_interval.end);

            var y = PosToYCoordinate(row);

            Rectangle rect = new Rectangle(x1, y, x2 - x1, HBox);

            var MicrosoftProjectRectColour = Color.FromArgb(255, 138, 187, 237);

            if (mouse_current_state.hovered == row)
                MicrosoftProjectRectColour = Color.FromArgb(255, 96, 163, 230);

            var brush = new SolidBrush(MicrosoftProjectRectColour);
            g.FillRectangle(brush, rect);
        }
Ejemplo n.º 26
0
        public EditTask(BindingList <project> listProject, BindingList <taskType> listTaskType, task Task)
        {
            InitializeComponent();

            _Task = Task;

            setDataSource(listProject, listTaskType);

            if (!String.IsNullOrWhiteSpace(Task.Title))
            {
                TBX_Title.Text            = Task.Title;
                TBX_Percent.Text          = Convert.ToString(Task.PercentProg);
                DTP_DateStart.Value       = Task.DateStart;
                DTP_DateEnd.Value         = Task.DateEnd;
                RTB_Desc.Text             = Task.Desc;
                CBX_Project.SelectedItem  = Task.Project;
                CBX_TaskType.SelectedItem = Task.TaskType;
            }
        }
Ejemplo n.º 27
0
 => WithTimeout(task, TimeSpan.FromMilliseconds(milliseconds), exceptionFactory);
Ejemplo n.º 28
0
        public async Task <IActionResult> SaveTask(List <IFormFile> files, TaskVM taskVM)
        {
            if (ModelState.IsValid)
            {
                if (!adamUnit.TaskRepository.Exists(x => x.Name == taskVM.Name && x.ProjectId == taskVM.ProjectId))
                {
                    // Current login User Information
                    var CurrentUserEmial = User.Identity.Name;
                    var CurrentUserId    = adamUnit.AppUserRepository.SingleOrDefault(x => x.Email == CurrentUserEmial).Id;
                    var CurrentName      = adamUnit.AppUserRepository.SingleOrDefault(x => x.Email == CurrentUserEmial).FirstName;

                    var tas = new task();
                    taskVM.Development = Development.init;
                    tas = taskVM.ToEntity();
                    await adamUnit.TaskRepository.InserAsync(tas);

                    string recordId    = tas.Id.ToString();
                    string webRootPath = _hostingEnvironment.WebRootPath;
                    var    state       = adamUnit.AttachmentRepository.OnPostUpload(files, recordId,
                                                                                    AttachmentOwner.Tasks, AttachmentType.Photo, webRootPath);

                    var UserId   = adamUnit.EmployeeRepository.SingleOrDefault(x => x.Id == taskVM.EmployeeId).UserId;
                    var UserName = adamUnit.AppUserRepository.SingleOrDefault(x => x.Id == UserId).UserName;
                    // Retrive UserId of Admin
                    var UserIdOfAdmin = adamUnit.RoleRepository.GetUserIdOfRole();
                    var attachment    = "";
                    if (CurrentUserId == UserIdOfAdmin)
                    {
                        attachment = adamUnit.AttachmentRepository.FirstOrDefault(x => x.OwnerId == CurrentUserId).FileName;
                    }
                    else
                    {
                        var employeeId = adamUnit.EmployeeRepository.SingleOrDefault(x => x.UserId == CurrentUserId).Id;
                        attachment = adamUnit.AttachmentRepository
                                     .FirstOrDefault(x => x.OwnerId == employeeId.ToString()).FileName;
                    }
                    var notify = new Notfication();
                    notify.OwnerUserId = CurrentUserId;
                    notify.ToUserId    = UserId;
                    notify.TableName   = TableName.task;
                    notify.TablePkId   = taskVM.Id;
                    notify.Context     = "AddYouToTask";
                    await adamUnit.NotificationRepository.InserAsync(notify);

                    var Url = "/Admin/task/Details?Id=" + taskVM.Id;
                    if (adamUnit.TokenFireBaseRepository.Exists(x => x.UserId == UserId))
                    {
                        var tokens = adamUnit.TokenFireBaseRepository.GetAll(x => x.UserId == UserId).Select(x => x.token);
                        foreach (var token in tokens)
                        {
                            NotificationController.SendPushNotification(token, notify.Context, CurrentName, Url, attachment);
                        }
                    }

                    TempData["SuccessMessage"] = "Created Successfully";
                    return(RedirectToAction(nameof(Index)));
                }
                ViewBag.Name     = "Name is Exist Already";
                ViewBag.Project  = adamUnit.ProjectRepository.GetAll().ToList();
                ViewBag.Employee = adamUnit.EmployeeRepository.GetAllInclude().ToList();
                return(PartialView("_PartialTask", taskVM));
            }
            ViewBag.Project  = adamUnit.ProjectRepository.GetAll().ToList();
            ViewBag.Employee = adamUnit.EmployeeRepository.GetAllInclude().ToList();
            return(PartialView("_PartialTask", taskVM));
        }
Ejemplo n.º 29
0
 => WithTimeout(task, TimeSpan.FromMilliseconds(milliseconds), exceptionFactory, cancellationToken);
        public IEnumerable <SuiteCRMTaskDetailViewModel> CopyOrchardTicketsToSuite(CopyOrchardTasksToSuiteViewModel model)
        {
            List <SuiteCRMTaskDetailViewModel> returnValue = new List <SuiteCRMTaskDetailViewModel>();

            using (var connection = Helper.GetConnection(this.services, this.Logger))
                using (SuiteCRMTaskUnitOfWork taskRepository = new SuiteCRMTaskUnitOfWork(connection))
                    using (SuiteCRMEmailAddressBeanUnitOfWork suiteCRMEmailAddressBeanUnitOfWork = new SuiteCRMEmailAddressBeanUnitOfWork(taskRepository))
                        using (SuiteCRMEmailAddressUnitOfWork suiteCRMEmailAddressUnitOfWork = new SuiteCRMEmailAddressUnitOfWork(taskRepository))
                            using (SuiteCRMProjectTaskUnitOfWork projectTasksRepository = new SuiteCRMProjectTaskUnitOfWork(taskRepository))
                                using (var suiteCRMTransaction = taskRepository.BeginTransaction())
                                {
                                    TicketContext context = new TicketContext();
                                    context.ProjectTaskUnitOfWork = projectTasksRepository;
                                    context.Priorities            = this.priorityRepository.Table.ToList();
                                    context.StatusList            = this.statusRepository.Table.ToList();

                                    try
                                    {
                                        var taskIds           = model.Tasks.Where(c => !string.IsNullOrEmpty(c.SuiteCRMId)).Select(c => c.SuiteCRMId).ToArray();
                                        var suiteTasks        = taskRepository.GetTasks(taskIds);
                                        var suiteProjectTasks = projectTasksRepository.GetTasks(taskIds);
                                        var orchardTickets    = this.services
                                                                .ContentManager
                                                                .GetMany <SuiteCRMTaskPart>(
                                            model.Tasks.Where(c => c.OrchardCollaborationTicketId.HasValue).Select(c => c.OrchardCollaborationTicketId.Value),
                                            VersionOptions.Published,
                                            new QueryHints().ExpandParts <TicketPart>());

                                        foreach (var item in model.Tasks)
                                        {
                                            if (item.OrchardCollaborationTicketId == null)
                                            {
                                                continue;
                                            }

                                            var ticket = orchardTickets.FirstOrDefault(c => c.Id == item.OrchardCollaborationTicketId.Value);

                                            var        suiteCRMTaskPart = ticket.As <SuiteCRMTaskPart>();
                                            TicketPart ticketPart       = ticket.As <TicketPart>();
                                            ContentItemPermissionPart permissionPart      = ticket.As <ContentItemPermissionPart>();
                                            AttachToProjectPart       attachToProjectPart = ticket.As <AttachToProjectPart>();
                                            SuiteCRMProjectPart       projectPart         = null;

                                            if (!this.IsSyncingTicketValid(item, ticket, out projectPart))
                                            {
                                                continue;
                                            }

                                            project_task suiteCRMProjectTask = null;
                                            task         suiteCRMTask        = null;

                                            if (!string.IsNullOrEmpty(suiteCRMTaskPart.ExternalId) && item.IsProjectTask)
                                            {
                                                suiteCRMProjectTask = suiteProjectTasks.FirstOrDefault(c => c.id == suiteCRMTaskPart.ExternalId);
                                            }

                                            if (!string.IsNullOrEmpty(suiteCRMTaskPart.ExternalId) && !item.IsProjectTask)
                                            {
                                                suiteCRMTask = suiteTasks.FirstOrDefault(c => c.id == suiteCRMTaskPart.ExternalId);
                                            }

                                            if (suiteCRMProjectTask == null && item.IsProjectTask)
                                            {
                                                suiteCRMProjectTask            = new project_task();
                                                suiteCRMProjectTask.project_id = item.SuiteCRMId;
                                                projectTasksRepository.Add(suiteCRMProjectTask);
                                            }

                                            if (suiteCRMTask == null && !item.IsProjectTask)
                                            {
                                                suiteCRMTask = new task();
                                                taskRepository.Add(suiteCRMTask);
                                            }

                                            CommonPart commonPart = ticketPart.As <CommonPart>();
                                            DateTime?  lastOrchardTicketChangeDate = commonPart.ModifiedUtc ?? commonPart.CreatedUtc;
                                            if (suiteCRMProjectTask != null &&
                                                (
                                                    !item.DoNotOverrideNewerValues ||
                                                    suiteCRMProjectTask.date_modified == null ||
                                                    (lastOrchardTicketChangeDate.HasValue &&
                                                     suiteCRMProjectTask.date_modified.Value <= lastOrchardTicketChangeDate.Value)
                                                ))
                                            {
                                                this.Copy(ticketPart, permissionPart, suiteCRMProjectTask, context);
                                                suiteCRMProjectTask.project_id = projectPart.ExternalId;
                                                projectTasksRepository.Save();
                                            }

                                            if (suiteCRMTask != null &&
                                                (
                                                    !item.DoNotOverrideNewerValues ||
                                                    suiteCRMTask.date_modified == null ||
                                                    (lastOrchardTicketChangeDate.HasValue &&
                                                     suiteCRMTask.date_modified.Value <= lastOrchardTicketChangeDate.Value)
                                                ))
                                            {
                                                this.Copy(ticketPart, permissionPart, suiteCRMTask, context);

                                                // set  contact
                                                if (string.IsNullOrEmpty(suiteCRMTask.created_by) && commonPart.Owner != null)
                                                {
                                                    var emailAddress = suiteCRMEmailAddressUnitOfWork.GetByEmail(commonPart.Owner.Email);
                                                    if (emailAddress != null)
                                                    {
                                                        var contact = suiteCRMEmailAddressBeanUnitOfWork.GetBeanIdOfEmailAddress(Helper.ContactsModuleName, new[] { emailAddress.id }).FirstOrDefault();

                                                        if (contact != null)
                                                        {
                                                            suiteCRMTask.parent_id   = contact.id;
                                                            suiteCRMTask.parent_type = Helper.ContactsModuleName;
                                                        }
                                                    }
                                                }

                                                projectTasksRepository.Save();
                                            }

                                            suiteCRMTaskPart.ExternalId   = item.IsProjectTask ? suiteCRMProjectTask.id : suiteCRMTask.id;
                                            suiteCRMTaskPart.LastSyncTime = DateTime.UtcNow;
                                            suiteCRMTaskPart.TaskType     = item.IsProjectTask ? SuiteCRMTaskPart.SuiteCRMProjectTaskTypeValue : SuiteCRMTaskPart.SuiteCRMTaskTypeValue;
                                            this.services.ContentManager.Publish(ticket.ContentItem);

                                            SuiteCRMTaskDetailViewModel returnValueItem = new SuiteCRMTaskDetailViewModel();
                                            returnValueItem.OrchardCollaborationTicket = ticket.ContentItem;
                                            returnValueItem.IsSync         = true;
                                            returnValueItem.IsProjectTask  = item.IsProjectTask;
                                            returnValueItem.LastSyncTime   = suiteCRMTaskPart.LastSyncTime;
                                            returnValueItem.SuiteCRMTaskId = suiteCRMTaskPart.ExternalId;
                                            returnValue.Add(returnValueItem);
                                        }

                                        suiteCRMTransaction.Commit();
                                    }
                                    catch (Exception ex)
                                    {
                                        suiteCRMTransaction.Rollback();
                                        throw ex;
                                    }
                                }

            return(returnValue);
        }
        private void Copy(TicketPart source, ContentItemPermissionPart sourcePermissionPart, task destination, TicketContext context)
        {
            destination.name     = source.Record.Title.Length > 50 ? source.Record.Title.Substring(0, 50) : source.Record.Title;
            destination.date_due = source.Record.DueDate;

            // status
            if (source.Record.StatusRecord != null)
            {
                var status = context.StatusList.FirstOrDefault(c => c.Id == source.Record.StatusRecord.Id);
                if (status != null)
                {
                    destination.status = status.Name;
                }
            }

            // priority
            if (source.Record.PriorityRecord != null)
            {
                var priority = context.Priorities.FirstOrDefault(c => c.Id == source.Record.PriorityRecord.Id);
                if (priority != null)
                {
                    destination.priority = priority.Name;
                }
            }

            CommonPart commonPart = source.As <CommonPart>();

            if (commonPart != null && commonPart.ModifiedUtc.HasValue)
            {
                destination.date_modified = commonPart.ModifiedUtc;
            }

            destination.assigned_user_id = this.GetAssigneeUserExternalId(sourcePermissionPart);
            destination.created_by       = this.GetOwnerUserExternalId(commonPart);
        }
Ejemplo n.º 32
0
 0 => new NodeElement(task, _nodeRepository),
 1 => new AssignmentElement(task, _assignmentRepository),
Ejemplo n.º 33
0
 // gets the proficiency for the passed task.
 public int GetProficiency(task t)
 {
     return(_proficiencies [(int)t]);
 }
Ejemplo n.º 34
0
 1 => new AssignmentElement(task, _assignmentRepository),
Ejemplo n.º 35
0
        private void labelEx2_Click(object sender, EventArgs e)
        {
            EmptyNuGetInfo();
            InstalledPackages = new List <IPackage>();
            if (repo == null)
            {
                NuGets nuget = new NuGets();
                repo = nuget.GetRepository();
            }
            if (vs == null)
            {
                return;
            }
            tasks = task.installed;
            UnloadUpdate(tasks);

            dg.Controls.Clear();
            dg.Refresh();
            ArrayList L = vs.GetReferences();

            foreach (string p in L)
            {
                string hint = vs.GetPathHint(p);
                if (String.IsNullOrEmpty(hint))
                {
                    continue;
                }
                string folder = vs.vs.SolutionPath + hint;

                if (File.Exists(folder))
                {
                }

                string pp = "";

                string bg = vs.GetProjectFolder() + "\\" + hint;

                string[] cc = bg.Split("\\".ToCharArray());

                List <string> bb = new List <string>(cc);

                int i = bb.IndexOf("packages");

                int j = 0;
                foreach (string s in bb)
                {
                    if (j != 0)
                    {
                        pp += "\\" + s;
                    }
                    else
                    {
                        pp = s;
                    }

                    if (j > i)
                    {
                        break;
                    }
                    j++;
                }

                pp = Path.GetFullPath(pp);

                if (!Directory.Exists(pp))
                {
                    continue;
                }

                string[] dd = Directory.GetFiles(pp);

                IPackage package = null;

                foreach (string d in dd)
                {
                    if (d.EndsWith(".nupkg"))
                    {
                        package = NuGets.ReadNuSpec(d);

                        break;
                    }
                }

                if (package == null)
                {
                    continue;
                }

                InstalledPackages.Add(package);

                {
                    IPackage packages = NuGets.GetNuGetPackage(package.Id, package.Version.ToFullString());
                    if (packages != null)
                    {
                        AddNugetPackageInfo(packages);
                    }
                }
            }
        }
Ejemplo n.º 36
0
 /// <summary>
 /// Safely execute the Task without waiting for it to complete before moving to the next line of code; commonly known as "Fire And Forget". Inspired by John Thiriet's blog post, "Removing Async Void": https://johnthiriet.com/removing-async-void/.
 /// </summary>
 /// <param name="task">Task.</param>
 /// <param name="onException">If an exception is thrown in the Task, <c>onException</c> will execute. If onException is null, the exception will be re-thrown</param>
 /// <param name="continueOnCapturedContext">If set to <c>true</c>, continue on captured context; this will ensure that the Synchronization Context returns to the calling thread. If set to <c>false</c>, continue on a different context; this will allow the Synchronization Context to continue on a different thread</param>
 public static void SafeFireAndForget(this Task task, in Action <Exception> onException = null, in bool continueOnCapturedContext = false) => HandleSafeFireAndForget(task, continueOnCapturedContext, onException);
Ejemplo n.º 37
0
 WaitAll(task, valueTask.AsTask());
Ejemplo n.º 38
0
 /// <summary>
 /// Load the model with the specified ID
 /// </summary>
 /// <param name="TaskId">The ID of the row in the database</param>
 /// <returns>True on success, False on failure</returns>
 public override bool Load(int TaskId)
 {
     base.Load(TaskId);
     var q = from x in CurrentConnection.tasks where x.id.Equals(TaskId) && x.deleted.Equals(0) select x;
     CurrentRow = q.FirstOrDefault();
     return true;
 }