Esempio n. 1
0
        /// <summary>
        /// StartTask a new <c>task</c>.
        /// </summary>
        /// <param name="task">The <c>task</c>.</param>
        /// <returns>The task's identifier.</returns>
        public Int64 StartTask(Expression <Action> task) //TODO: (task, queue)
        {
            if (taskManagerState == TaskManagerState.ServerOnly)
            {
                throw new InvalidOperationException("taskManagerState == TaskManagerState.ServerOnly");
            }

            logger.WriteDebug("Preparing a new task... Getting a default queue...");

            QueueModel defaultQueue = queueManager.GetDefaultQueue();

            logger.WriteTrace("The default queue ({0}) has been got. Converting expression into the task model...");

            ActivationData      activationData = expressionConverter.Convert(task);
            ScheduleInformation schedule       = new ScheduleInformation(maxRerunCount);
            TaskModel           taskModel      = new TaskModel(defaultQueue.Id, activationData, schedule);

            logger.WriteTrace("The expression has been converted. Inserting the task into the database...");

            Int64 taskId = taskDataContext.InsertTask(taskModel);

            logger.WriteDebug("The task has been inserted. Task identifier = {0}", taskId);

            return(taskId);
        }
        public void CancelInSetupWorksAsExpected()
        {
            // --- Arrange
            using (s_SetupAutoResetEvent = new AutoResetEvent(false))
            {
                var schedule = new ScheduleInformation
                {
                    FrequencyType = TaskFrequencyType.Second,
                    Frequency     = 2,
                };
                s_Context = new DefaultTaskExecutionContext(new MemoryNamedQueueProvider());
                var processor =
                    new ScheduledTaskProcessor <TaskWithSetupAutoResetEvent>(s_Context)
                {
                    ScheduleInfo = schedule
                };
                TaskWithSetupAutoResetEvent.Counter = 0;

                // --- Act
                processor.Start();
                s_SetupAutoResetEvent.WaitOne(5000).ShouldBeTrue("Task did not get to setup phase in 5 seconds");
                processor.Stop();

                // --- Assert
                TaskWithSetupAutoResetEvent.Counter.ShouldEqual(0);
            }
        }
Esempio n. 3
0
        private async void ExecuteSendTweetCommand()
        {
            IsSending = true;
            List <Tuple <ulong, ulong> > statusIds = new List <Tuple <ulong, ulong> >();

            if (ScheduleInformation?.IsTweetScheduled == true)
            {
                var accountIds = Accounts.Where(a => a.Use).Select(a => a.Context.UserId);
                var fileNames  = AttachedMedias.Select(m => m.FileName);
                ScheduleInformation.ScheduleTweet(Text, InReplyTo?.Id, accountIds, fileNames);
            }
            else
            {
                var statuses = await SendTweet();

                statusIds.AddRange(statuses);
            }

            if (ScheduleInformation?.IsDeletionScheduled == true)
            {
                ScheduleInformation.ScheduleDeletion(statusIds, Text);
            }

            if (ScheduleInformation?.IsTweetScheduled == true)
            {
                await CloseOrReload();
            }

            IsSending = false;
        }
Esempio n. 4
0
        public List <ScheduleInformation> GetScheduleInformation(int departmentId)
        {
            string query = "SELECT * FROM VW_ScheduleInformation WHERE DepartmentId='" + departmentId + "'";

            SqlCommand.CommandText = query;
            SqlConnection.Open();
            SqlDataReader reader = SqlCommand.ExecuteReader();
            List <ScheduleInformation> roomAllocationInfoList = new List <ScheduleInformation>();

            while (reader.Read())
            {
                ScheduleInformation roomAllocationInfo = new ScheduleInformation()
                {
                    Code           = reader["Code"].ToString(),
                    Name           = reader["Name"].ToString(),
                    Day            = reader["Day"].ToString() != "" ? reader["Day"].ToString().Substring(0, 3) : reader["Day"].ToString(),
                    RoomName       = reader["RoomNo"].ToString(),
                    ClassStartFrom = reader["ClassStartFrom"].ToString(),
                    ClassEndAt     = reader["ClassEndAt"].ToString(),
                };
                roomAllocationInfoList.Add(roomAllocationInfo);
            }
            reader.Close();
            SqlConnection.Close();
            return(roomAllocationInfoList);
        }
Esempio n. 5
0
        public ActionResult Create(string roomId, string day, string time, string classId)
        {
            ScheduleInformation scheduleinformation = new ScheduleInformation();
            var date       = time.Split('-');
            var rMRoomId   = Convert.ToInt64(roomId);
            var sHFromTime = Convert.ToDateTime(date[0]);
            var sHToTime   = Convert.ToDateTime(date[1]);
            var dpRoom     = db.ScheduleInformations.Where(w => w.RmRoomId == rMRoomId && w.ShDay == day &&
                                                           (w.ShFromTime >= sHFromTime && w.ShToTime <= sHToTime)).ToList();

            var data = db.ScheduleInformations.Where(w => w.RmRoomId == rMRoomId && w.ShDay == day && w.ShClass == classId &&
                                                     (w.ShFromTime >= sHFromTime && w.ShToTime <= sHToTime)).ToList();

            if (data.Count == 0 && dpRoom.Count == 0)
            {
                var year = DateTime.Now.Year;

                scheduleinformation.RmRoomId   = Convert.ToInt64(roomId);
                scheduleinformation.ShDay      = day;
                scheduleinformation.ShFromTime = Convert.ToDateTime(date[0]);
                scheduleinformation.ShToTime   = Convert.ToDateTime(date[1]);
                scheduleinformation.ShClass    = classId;
                scheduleinformation.Year       = Convert.ToString(year);
                db.ScheduleInformations.Add(scheduleinformation);
                db.SaveChanges();
            }
            return(Json(new { result = "success" }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 6
0
        public ActionResult DeleteConfirmed(long id)
        {
            ScheduleInformation scheduleInformation = db.ScheduleInformations.Find(id);

            db.ScheduleInformations.Remove(scheduleInformation);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Esempio n. 7
0
            /// <summary>
            /// Initializes a new instance of the <see cref="ScheduleMap"/> class.
            /// </summary>
            /// <param name="information">The information describing the schedule.</param>
            /// <param name="schedule">The schedule.</param>
            public ScheduleMap(ScheduleInformation information, ISchedule schedule)
            {
                {
                    Debug.Assert(information != null, "The schedule information should not be a null reference.");
                    Debug.Assert(schedule != null, "The schedule should not be a null reference.");
                }

                m_Info     = information;
                m_Schedule = schedule;
            }
Esempio n. 8
0
        private static Task <ValidateResult> ValidateEnd(ScheduleInformation state, object response)
        {
            DateTime typedText = (DateTime)response;
            var      result    = new ValidateResult {
                IsValid = false, Value = typedText
            };

            result.IsValid  = (!typedText.Date.Equals(DateTime.MinValue.Date) && typedText > DateTime.Now && typedText > state.Start);
            result.Feedback = result.IsValid ? string.Empty :$"{typedText} must be greater than current or start date.";
            return(Task.FromResult(result));
        }
Esempio n. 9
0
 public ActionResult Edit([Bind(Include = "ShScheduleId,RmRoomId,ShClass,ShDay,ShFromTime,ShToTime,ShCourse,ShSection")] ScheduleInformation scheduleInformation)
 {
     if (ModelState.IsValid)
     {
         db.Entry(scheduleInformation).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.RmRoomId = new SelectList(db.RoomInformations, "RmRoomId", "RmRoomNo", scheduleInformation.RmRoomId);
     return(View(scheduleInformation));
 }
Esempio n. 10
0
        private static Task <ValidateResult> ValidateLocation(ScheduleInformation state, object response)
        {
            string typedText = (string)response;
            var    result    = new ValidateResult {
                IsValid = false, Value = typedText
            };

            result.IsValid  = (!string.IsNullOrEmpty(typedText) && ValidateLocation(typedText));
            result.Feedback = result.IsValid ? string.Empty : $"{typedText} is not a conference room option.";
            return(Task.FromResult(result));
        }
Esempio n. 11
0
        // GET: ScheduleInformation/Details/5
        public ActionResult Details(long?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ScheduleInformation scheduleInformation = db.ScheduleInformations.Find(id);

            if (scheduleInformation == null)
            {
                return(HttpNotFound());
            }
            return(View(scheduleInformation));
        }
Esempio n. 12
0
        // GET: ScheduleInformation/Edit/5
        public ActionResult Edit(long?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ScheduleInformation scheduleInformation = db.ScheduleInformations.Find(id);

            if (scheduleInformation == null)
            {
                return(HttpNotFound());
            }
            ViewBag.RmRoomId = new SelectList(db.RoomInformations, "RmRoomId", "RmRoomNo", scheduleInformation.RmRoomId);
            return(View(scheduleInformation));
        }
Esempio n. 13
0
        public async Task OnLoad(object data)
        {
            bool loadImage = data as bool? ?? true;

            foreach (var acc in Accounts)
            {
                acc.UseChanged -= Acc_UseChanged;
            }

            Accounts = ContextList?.Contexts?.Select(c => new AccountEntry(c, loadImage)).ToList();
            if (Accounts == null)
            {
                LogTo.Warn("No accounts found");
                return;
            }

            foreach (var acc in Accounts)
            {
                acc.UseChanged += Acc_UseChanged;
            }

            var defAccount = Accounts.FirstOrDefault(a => a.IsDefault) ?? Accounts.First();

            defAccount.Use = true;

            if (PreSelectedAccounts.Any())
            {
                foreach (var acc in Accounts)
                {
                    acc.Use = PreSelectedAccounts.Contains(acc.Context.UserId);
                }
            }

            RaisePropertyChanged(nameof(Accounts));

            InitializeText();
            ConfirmationSet = false;

            Medias.Clear();
            AttachedMedias.Clear();

            KnownUserNames = (await Cache.GetKnownUsers().ConfigureAwait(false)).Select(u => u.UserName).ToList();
            RaisePropertyChanged(nameof(KnownUserNames));
            KnownHashtags = (await Cache.GetKnownHashtags().ConfigureAwait(false)).ToList();
            RaisePropertyChanged(nameof(KnownHashtags));

            ScheduleInformation?.ResetSchedule();
        }
Esempio n. 14
0
        /// <summary>
        /// Adds the <see cref="ISchedule"/> object with the variables it affects and the dependencies for that schedule.
        /// </summary>
        /// <param name="schedule">The schedule that should be stored.</param>
        /// <param name="name">The name of the schedule that is being described by this information object.</param>
        /// <param name="description">The description of the schedule that is being described by this information object.</param>
        /// <returns>An object identifying and describing the schedule.</returns>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="schedule"/> is <see langword="null" />.
        /// </exception>
        public ScheduleInformation Add(
            ISchedule schedule,
            string name,
            string description)
        {
            {
                Lokad.Enforce.Argument(() => schedule);
            }

            var id   = new ScheduleId();
            var info = new ScheduleInformation(id, name, description);

            m_Schedules.Add(id, new ScheduleMap(info, schedule));

            return(info);
        }
Esempio n. 15
0
        public void Should_be_possible_to_schedule_a_request_collect_in_specific_date()
        {
            var collectRequest      = new CollectRequestFactory().CreateCollectRequest(DataProvider.GetSession()).Item2;
            var scheduleInformation = new ScheduleInformation()
            {
                ScheduleDate = DateTime.Now.AddSeconds(1)
            };
            var scheduler          = new StdSchedulerFactory().GetScheduler();
            var scheduleController = new ScheduleController(scheduler)
            {
                TypeOfExecutionJob = typeof(TestJob)
            };

            scheduleController.ScheduleCollection(collectRequest.Oid.ToString(), "", scheduleInformation.ScheduleDate);

            Assert.AreEqual(1, scheduleController.GetNumberOfCollectRequestScheduled());
            scheduler.Shutdown();
        }
Esempio n. 16
0
        /// <summary>
        /// Replaces the schedule current stored against the given ID with a new one.
        /// </summary>
        /// <param name="scheduleToReplace">The ID of the schedule that should be replaced.</param>
        /// <param name="newSchedule">The new schedule.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="scheduleToReplace"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="newSchedule"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="UnknownScheduleException">
        ///     Thrown if <paramref name="scheduleToReplace"/> is not linked to a known schedule.
        /// </exception>
        public void Update(
            ScheduleId scheduleToReplace,
            ISchedule newSchedule)
        {
            {
                Lokad.Enforce.Argument(() => scheduleToReplace);
                Lokad.Enforce.Argument(() => newSchedule);
                Lokad.Enforce.With <UnknownScheduleException>(
                    m_Schedules.ContainsKey(scheduleToReplace),
                    Resources.Exceptions_Messages_UnknownSchedule);
            }

            var oldInfo = m_Schedules[scheduleToReplace].Information;
            var info    = new ScheduleInformation(
                scheduleToReplace,
                oldInfo.Name,
                oldInfo.Description);

            m_Schedules[scheduleToReplace] = new ScheduleMap(info, newSchedule);
        }
Esempio n. 17
0
        /// <summary>
        /// Convert task entity into the task model.
        /// </summary>
        /// <param name="taskEntity">The <see cref="TaskEntity"/> instance.</param>
        /// <returns>The <see cref="TaskModel"/> instance.</returns>
        public TaskModel Convert(TaskEntity taskEntity)
        {
            string instanceTypeJson = jsonConverter.ConvertFromJson <string>(taskEntity.InstanceType);
            Type   instanceType     = Type.GetType(instanceTypeJson, throwOnError: true, ignoreCase: true);

            Type[]     argumentTypes = jsonConverter.ConvertFromJson <Type[]>(taskEntity.ParametersTypes);
            MethodInfo method        = expressionConverter.GetNonOpenMatchingMethod(instanceType, taskEntity.Method, argumentTypes);

            string[] serializedArguments = jsonConverter.ConvertFromJson <string[]>(taskEntity.Arguments);

            object[] arguments = expressionConverter.DeserializeArguments(method, serializedArguments);

            ActivationData activationData = new ActivationData(instanceType, method, arguments, argumentTypes);

            ScheduleInformation scheduleInformation = new ScheduleInformation(taskEntity.RepeatCrashCount);

            TaskModel taskModel = new TaskModel(taskEntity.Id, taskEntity.QueueId, taskEntity.ServerId, activationData, taskEntity.TaskState, scheduleInformation);

            return(taskModel);
        }
Esempio n. 18
0
        public void Should_not_possible_schedule_the_collectRequest_if_already_exists_a_job_defined()
        {
            var scheduleInformation = new ScheduleInformation()
            {
                ScheduleDate = DateTime.Now.AddSeconds(1)
            };
            var collectRequest = new CollectRequestFactory().CreateCollectRequest(DataProvider.GetSession()).Item2;

            this.SaveCollectRequest(collectRequest);
            var scheduler          = new StdSchedulerFactory().GetScheduler();
            var scheduleController = new ScheduleController(scheduler)
            {
                TypeOfExecutionJob = typeof(TestJob)
            };
            var collectRequestId = collectRequest.Oid.ToString();

            scheduleController.ScheduleCollection(collectRequestId, "", scheduleInformation.ScheduleDate);
            scheduleController.ScheduleCollection(collectRequestId, "", scheduleInformation.ScheduleDate);

            Assert.AreEqual(1, scheduleController.GetNumberOfCollectRequestScheduled());
            scheduler.Shutdown();
        }
Esempio n. 19
0
        public void Should_be_possible_get_the_collectRequestIds_that_are_executing_in_the_scheduler()
        {
            var collectRequest      = new CollectRequestFactory().CreateCollectRequest(DataProvider.GetSession()).Item2;
            var scheduleInformation = new ScheduleInformation()
            {
                ScheduleDate = DateTime.Now.AddSeconds(1)
            };

            this.SaveCollectRequest(collectRequest);
            var scheduler          = new StdSchedulerFactory().GetScheduler();
            var scheduleController = new ScheduleController(scheduler)
            {
                TypeOfExecutionJob = typeof(TestJob)
            };

            scheduleController.ScheduleCollection(collectRequest.Oid.ToString(), "", scheduleInformation.ScheduleDate);
            Thread.Sleep(1000);

            var collectRequestIds = scheduleController.GetCollectRequestIdRunning();

            Assert.IsTrue(collectRequestIds.Count() > 0);
            scheduler.Shutdown();
        }
        public void FaultyScheduledTaskWorksAsExpected()
        {
            // --- Arrange
            var schedule = new ScheduleInformation
            {
                FrequencyType = TaskFrequencyType.Second,
                Frequency     = 2,
            };
            var context   = new DefaultTaskExecutionContext(new MemoryNamedQueueProvider());
            var processor =
                new ScheduledTaskProcessor <FaultyTask>(context)
            {
                ScheduleInfo = schedule
            };

            // --- Act
            FaultyTask.Counter = 0;
            processor.Start();
            Thread.Sleep(5000);
            processor.Stop();

            // --- Assert
            FaultyTask.Counter.ShouldBeLessThanOrEqualTo(3);
        }
Esempio n. 21
0
 public Schedule(ScheduleInformation scheduleInfo)
 {
     this.ScheduleId = scheduleInfo.ScheduleId;
     LoadAvailabilityMap(scheduleInfo.AvailabilityView);
 }