public void Execute(TaskComplete callback)
        {
            // Find all the matches we can to various weathers
            var match = WeatherUtils.OrderedMatches(phrase);

            // Debugging why we picked X
            if (debug)
            {
                Debug.Log("");
                Debug.Log("------ WEATHER CHOICE DEBUG ------");
                Debug.Log("found " + match.Count + " possible weather matches...");
                foreach (var m in match) { m.Debug(); }
            }

            // Select best match~
            selected = match.Count > 0 ? match[0] : null;
            var selectedId = match.Count > 0 ? match[0].weather.weather : WeatherId.FINE;

            // Update symbol phrase
            phrase.weather = selectedId;
            phrase.weatherPrefab = WeatherUtils.WeatherPrefab(phrase.weather);

            if (debug)
            {
                Debug.Log(string.Format("Pick weather for phrase: {0}", selected));
                Debug.Log("");
            }

            // Done~
            if (callback != null)
            { callback(this); }
        }
        public void Execute(TaskComplete callback)
        {
            player.ClearPhrase();

            // Shuffle components, then make sure at least 1 of each type is present
            // and the rest are all random.
            var components = Scene.FindComponents<SelectSymbol>();
            Jam.Utils.Random.Shuffle(components);

            /// Default symbol states we always expect
            var always = Scene.FindComponents<FixedSymbolBehaviour>();

            // Apply all then always that we can
            var offset = 0;
            foreach (var required in always)
            {
                if (components.Count > offset)
                {
                    components[offset].symbol.humidity = required.detail.humidity;
                    components[offset].symbol.temperature = required.detail.temperature;
                    components[offset].symbol.wind = required.detail.wind;
                }
                offset += 1;
            }

            // Do the rest~
            for (var i = always.Count; i < components.Count; ++i)
            { components[i].symbol.Randomize(); }

            // Done~
            if (callback != null)
            { callback(this); }
        }
Example #3
0
        public ArraysTurple A()
        {
            int[,] M1 = new int[n, n];
            int[] M2 = new int[n];

            Random rand = new Random();

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    M1[i, j] = rand.Next(n);
                }
            }
            for (int i = 0; i < M2.Length; i++)
            {
                M2[i] = rand.Next(0, 100);
            }

            var infoTask = new Info()
            {
                id = "A", time_end = "[TIME STOP]: " + DateTime.Now + ":" + DateTime.Now.Millisecond
            };

            TaskComplete?.Invoke(infoTask);
            return(new ArraysTurple {
                M1 = M1, M2 = M2
            });
        }
        public void Execute(TaskComplete callback)
        {
            // Change weather
            var weatherControl = Scene.FindComponent<WeatherSystem>();
            if (weatherControl != null)
            {
                weatherControl.TransitionTo(phrase.weather);
            }
            else { Debug.LogError("Missing WeatherSystem on scene"); }

            // Apply some ambient audio if there is any
            var ambientController = Scene.FindComponent<AmbienceController>();
            if (ambientController != null)
            {
                var sound = WeatherUtils.AmbientSoundFor(phrase.weather);
                if (sound != null)
                {
                    Debug.Log("Running");
                    Debug.Log(sound);
                    ambientController.PlaySound(sound);
                }
            }
            else { Debug.LogError("Missing AmbienceController"); }


            Debug.Log(string.Format("Execute weather change: {0}", phrase.weather));

            // Done~
            if (callback != null)
            { callback(this); }
        }
Example #5
0
        /// <summary>
        /// Add a task to the thread queue. When a thread is available, it will
        /// dequeue this task and run it. Once complete, the task will be marked
        /// complete, but your application won't be called back until the next
        /// time Update() is called (so that callbacks are from the main thread).
        /// </summary>
        /// <param name="function">The function to call within the thread.</param>
        /// <param name="completion">The callback to report results to, or null. If
        /// you care about which particular task has completed, use a different instance
        /// for this delegate per task (typically, a delegate on the task itself).</param>
        /// <param name="ctx">A previously allocated TaskContext, to allow for waiting
        /// on the task, or null. It cannot have been already used.</param>
        /// <returns>A Task identifier for the operation in question. Note: because
        /// of the threaded behavior, the task may have already completed when it
        /// is returned. However, if you AddTask() from the main thread, the completion
        /// function will not yet have been called.</returns>
        public Task AddTask(TaskFunction function, TaskComplete completion, TaskContext ctx)
        {
            if (function == null)
            {
                throw new System.ArgumentNullException("function");
            }
            Worker w;

            lock (this)
            {
                if (disposed_)
                {
                    throw new System.ObjectDisposedException("ParallelThreadPool");
                }
                qDepth_++;
                w = NewWorker(function, completion);
                if (ctx != null)
                {
                    ctx.Init(w);
                }
                if (workList_ == null)
                {
                    workList_ = w;
                }
                else
                {
                    workListEnd_.next_ = w;
                }
                workListEnd_ = w;
            }
            workEvent_.Set();
            return(w);
        }
Example #6
0
        /// <summary>
        /// Add a task to the thread queue. When a thread is available, it will
        /// dequeue this task and run it. Once complete, the task will be marked
        /// complete, but your application won't be called back until the next
        /// time Update() is called (so that callbacks are from the main thread).
        /// </summary>
        /// <param name="function">The function to call within the thread.</param>
        /// <param name="completion">The callback to report results to, or null. If
        /// you care about which particular task has completed, use a different instance
        /// for this delegate per task (typically, a delegate on the task itself).</param>
        /// <param name="ctx">A previously allocated TaskContext, to allow for waiting
        /// on the task, or null. It cannot have been already used.</param>
        /// <returns>A Task identifier for the operation in question. Note: because
        /// of the threaded behavior, the task may have already completed when it
        /// is returned. However, if you AddTask() from the main thread, the completion
        /// function will not yet have been called.</returns>
        public ITask AddTask(TaskFunction function, TaskComplete completion, TaskContext ctx)
        {
            if (function == null)
            {
                throw new ArgumentNullException("function");
            }

            Worker w;

            lock (this)
            {
                if (_disposed)
                {
                    throw new ObjectDisposedException("ParallelThreadPool");
                }
                _qDepth++;
                w = NewWorker(function, completion);
                if (ctx != null)
                {
                    ctx.Init(w);
                }
                if (_workList == null)
                {
                    _workList = w;
                }
                else
                {
                    _workListEnd.Next = w;
                }
                _workListEnd = w;
            }
            _workEvent.Set();
            return(w);
        }
Example #7
0
 public Task(IEnumerator task, TaskComplete taskComplete, TaskResult taskResult, string taskName = "defaultTaskName")
 {
     this.task         = task;
     this.taskResult   = taskResult;
     this.taskComplete = taskComplete;
     this.taskName     = taskName;
 }
        public void Execute(TaskComplete callback)
        {
            // Destroy old markers
            foreach (var slot in Scene.FindComponents<SlotMarker>())
            { GameObject.Destroy(slot.gameObject); }

            // Add currently selected
            var offset = 0;
            foreach (var symbol in phrase.symbols)
            {
                GameObject parent = null;
                switch (offset)
                {
                    case 0:
                        parent = slots.slot1;
                        break;
                    case 1:
                        parent = slots.slot2;
                        break;
                    case 2:
                        parent = slots.slot3;
                        break;
                }
                if (parent != null)
                {
                    if (symbol.symbolPrefab == null)
                    {
                        Debug.LogError(string.Format("Warning: Symbol {0} does not have a prefab assigned forward it's symbol", symbol));
                    }
                    else
                    {
                        Scene.Spawn(symbol.symbolPrefab).Then((gp) =>
                        {
                            gp.transform.position = parent.transform.position;

                            var rotation = parent.transform.rotation;
                            gp.transform.rotation = rotation;
                            gp.transform.localScale = new Vector3(0.12f, 0.12f, 0.12f);

                            gp.AddComponent<SlotMarker>();
                            symbol.SetHighlightState(gp, true, player);
                        });
                    }
                }
                offset += 1;
            }

            // Find all SelectSymbol components and update their display state
            foreach (var target in Scene.FindComponents<SelectSymbol>())
            {
                var item = target as SelectSymbol;
                item.currentlyHighlighted = phrase.Has(item.symbol);
                item.symbol.SetGlowColor(target.gameObject, player.GetSymbolColorFor(item.symbol));
            }

            // Done~
            if (callback != null)
            { callback(this); }
        }
        public void SetValue(int parentId, int fieldIndex, List <OSCValue> values, TaskComplete completeCallback)
        {
            var task = CreateTask(RECommand.SetValue, parentId, null, completeCallback);

            values.Insert(0, OSCValue.Int(fieldIndex));

            Send(Address, task, values.ToArray());
        }
Example #10
0
        public ITask AddTask(TaskFunction function, TaskComplete completion, TaskContext ctx)
        {
            //Just cycle to the next free one.
            lock (_nextThreadTargetLock)
                _nextThreadTarget = (ThreadTarget)(((int)(_nextThreadTarget) + 1) % _nThreads);

            return(AddTask(_nextThreadTarget, function, completion, ctx));
        }
Example #11
0
        private void OnFinished(int errorcode)
        {
            TaskComplete handler = Finished;

            if (handler != null)
            {
                handler(errorcode);
            }
        }
        public void Execute(TaskComplete callback)
        {
            // Update any plant on the scene
            foreach (var plant in Scene.FindComponents<UpdatePlantState>())
            { plant.UpdateState(delta); }

            // Done~
            if (callback != null)
            { callback(this); }
        }
Example #13
0
        private void Timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();

            foreach (var task in Tasks.Values)
            {
                if (!task.IsStart || task.IsStop || task.IsComplete)
                {
                    continue;
                }

                ThunderDll.QueryTaskInfo(task.ID, task.Info);

                if (task.Info.Status == ThunderDll.DOWN_TASK_STATUS.TSC_STOPENDING)
                {
                    task.IsStop = true;
                }

                if (task.Info.Status == ThunderDll.DOWN_TASK_STATUS.TSC_COMPLETE)
                {
                    TaskComplete?.Invoke(this, task);
                    task.IsComplete = true;
                }

                TaskInfoChange?.Invoke(this, task);
            }

            if (AutoManage)
            {
                int cnt = RunTaskCount();
                if (cnt < MaxTaskCount)
                {
                    foreach (var task in Tasks.Values)
                    {
                        if (!task.IsStart)
                        {
                            task.StartTask();
                            cnt++;
                        }

                        if (cnt >= MaxTaskCount)
                        {
                            break;
                        }
                    }
                }

                DeleteCompleted();
            }

            if (!Exit)
            {
                timer.Start();
            }
        }
Example #14
0
        public int E(int result)
        {
            var res      = result / 50;
            var infoTask = new Info()
            {
                id = "E", time_end = "[TIME STOP]: " + DateTime.Now + ":" + DateTime.Now.Millisecond
            };

            TaskComplete?.Invoke(infoTask);
            return(res);
        }
Example #15
0
        public int H(int resE, int resD)
        {
            int res      = resD * resE * 3;
            var infoTask = new Info()
            {
                id = "H", time_end = "[TIME STOP]: " + DateTime.Now + ":" + DateTime.Now.Millisecond
            };

            TaskComplete?.Invoke(infoTask);
            return(res);
        }
Example #16
0
        public void K(int resF, int resG, int resH)
        {
            //some func
            int res      = resF + resG + resH;
            var infoTask = new Info()
            {
                id = "K", time_end = "[TIME STOP]: " + DateTime.Now + ":" + DateTime.Now.Millisecond
            };

            TaskComplete?.Invoke(infoTask);
        }
        public void Execute(TaskComplete callback)
        {
            if (emitter != null)
            {
                emitter.enableEmission = ready;
            }

            // Done~
            if (callback != null)
            { callback(this); }
        }
 private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
 {
     IsComplete = !IsComplete;
     if (IsComplete)
     {
         TaskComplete.Begin();
     }
     else
     {
         TaskIncomplete.Begin();
     }
 }
 /// <summary>
 /// cancel a background task - or prevent a task from running
 /// </summary>
 public void Cancel()
 {
     lock (_lock)
     {
         if (_client != null)
         {
             _client.CancelAsync();
         }
         else
         {
             // probably an unstarted task or a task that has completed
             _complete = true;
             TaskComplete.Set();
         }
     }
 }
Example #20
0
        Worker NewWorker(TaskFunction tf, TaskComplete tc)
        {
            if (freeList_ == null)
            {
                freeList_ = new Worker(null, null);
            }
            Worker ret = freeList_;

            freeList_       = ret.next_;
            ret.function_   = tf;
            ret.completion_ = tc;
            ret.context_    = null;
            ret.error_      = null;
            ret.next_       = null;
            return(ret);
        }
        void ClientDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            StatusUpdateEventArgs args = null;

            lock (_lock)
            {
                var syncItem = e.UserState as SyncItem;
                if (syncItem == null)
                {
                    args = new StatusUpdateEventArgs(StatusUpdateLevel.Error, "Missing token from download completed", false, null);
                }
                else if (e.Cancelled)
                {
                    args = new StatusUpdateEventArgs(StatusUpdateLevel.Status, string.Format(CultureInfo.InvariantCulture, "{0} Cancelled", syncItem.EpisodeTitle), false, syncItem);
                }
                else if (e.Error != null && e.Error.InnerException != null)
                {
                    args = new StatusUpdateEventArgs(StatusUpdateLevel.Error, string.Format(CultureInfo.InvariantCulture, "Error in: {0}", syncItem.EpisodeTitle), e.Error.InnerException, false, syncItem);
                }
                else if (e.Error != null)
                {
                    args = new StatusUpdateEventArgs(StatusUpdateLevel.Error, string.Format(CultureInfo.InvariantCulture, "Error in: {0}", syncItem.EpisodeTitle), e.Error, false, syncItem);
                }
                else
                {
                    args = new StatusUpdateEventArgs(StatusUpdateLevel.Status, string.Format(CultureInfo.InvariantCulture, "{0} Completed", syncItem.EpisodeTitle), true, syncItem);

                    _fileUtilities.FileRename(GetDownloadFilename(), _syncItem.DestinationPath, true);
                    RecordHighTideMark(syncItem);
                    ExecutePostDownloadCommand();
                }

                OnStatusUpdate(args);

                _client.Dispose();
                _client = null;

                _complete = true;
                _counterFactory.CreateAverageCounter(Constants.PodcastUtilitiesCommonCounterCategory,
                                                     Constants.AverageTimeToDownload,
                                                     Constants.NumberOfDownloads).RegisterTime(_stopWatch);
                _counterFactory.CreateAverageCounter(Constants.PodcastUtilitiesCommonCounterCategory,
                                                     Constants.AverageMBDownload,
                                                     Constants.SizeOfDownloads).RegisterValue(ConvertBytesToMB(_bytesDownloaded));
                TaskComplete.Set();
            }
        }
Example #22
0
        private Worker NewWorker(TaskFunction tf, TaskComplete tc)
        {
            if (_freeList == null)
            {
                _freeList = new Worker(null, null);
            }

            var ret = _freeList;

            _freeList      = ret.Next;
            ret.Function   = tf;
            ret.Completion = tc;
            ret.Context    = null;
            ret.Error      = null;
            ret.Next       = null;
            return(ret);
        }
 /// <summary>
 /// Sets task's state to completed and
 /// </summary>
 /// <param name="taskComplete">Completed task</param>
 public void TaskRemove(TaskComplete taskComplete)
 {
     using (MySqlConnection connection = WebApiConfig.Connection())
     {
         connection.Open();
         if (taskComplete.IsSuccessfull)
         {
             using (MySqlCommand command = new MySqlCommand(@"UPDATE `tbTasks` SET `Completed`= 1 WHERE `Id` = @IdTask", connection))
             {
                 command.Parameters.AddWithValue("@IdTask", taskComplete.IDTask);
                 command.ExecuteNonQuery();
             }
         }
         string debugLog = "";
         if (taskComplete.DebugLog != null)
         {
             foreach (string item in taskComplete.DebugLog)
             {
                 debugLog += item + "\n";
             }
         }
         using (MySqlCommand command = new MySqlCommand($"INSERT INTO `tbTasksCompleted` VALUES (null,{GetDaemonId(taskComplete.DaemonInfo)},{taskComplete.IDTask},@backupjournal,@datetime,'{debugLog}',{taskComplete.IsSuccessfull},0)", connection))
         {
             command.Parameters.AddWithValue("@backupjournal", b.Base64Encode(JsonConvert.SerializeObject(taskComplete.DatFile)));
             command.Parameters.AddWithValue("@datetime", taskComplete.TimeOfCompletition);
             command.ExecuteNonQuery();
         }
         int        Id       = sqlAdmin.NextAutoIncrement("tbTasksCompleted") - 1;
         List <int> toInsert = new List <int>();
         using (MySqlCommand command = new MySqlCommand($"select Id from tbAdminAccounts where 1 order by Id", connection))
         {
             using (MySqlDataReader reader = command.ExecuteReader())
             {
                 while (reader.Read())
                 {
                     toInsert.Add((int)reader["Id"]);
                 }
             }
             foreach (int item in toInsert)
             {
                 command.CommandText = $"INSERT INTO `tbTasksCompletedAdminNOTNotified`(`IdTaskCompleted`, `IdAdmin`) VALUES({Id}, {item})";
                 command.ExecuteNonQuery();
             }
         }
     }
 }
Example #24
0
 public new void Execute(string input)
 {
     try
     {
         var cached = TaskBuffer.Get(input);
         cached.Update("status", "Published");
         _publisher.SendQueue(input, cached.ToString());
         UpdateCacheAndDatabase(input, cached);
         _complete = new TaskComplete();
         _complete.Execute(input);
     }
     catch (Exception e)
     {
         TaskCancel cancel = new TaskCancel(e);
         cancel.Execute(input);
     }
 }
Example #25
0
        public int C(ArraysTurple result)
        {
            var M1  = result.M1;
            var M2  = result.M2;
            int res = 0;

            for (int i = 0; i < M2.Length; i++)
            {
                res = M2[i] - 100;
            }

            var infoTask = new Info()
            {
                id = "C", time_end = "[TIME STOP]: " + DateTime.Now + ":" + DateTime.Now.Millisecond
            };

            TaskComplete?.Invoke(infoTask);
            return(res);
        }
Example #26
0
        public int B(ArraysTurple result)
        {
            var M1  = result.M1;
            var M2  = result.M2;
            int res = 0;

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    res = M1[i, j] + res;
                }
            }

            var infoTask = new Info()
            {
                id = "B", time_end = "[TIME STOP]: " + DateTime.Now + ":" + DateTime.Now.Millisecond
            };

            TaskComplete?.Invoke(infoTask);
            return(res);
        }
        public void Execute(TaskComplete callback)
        {
            // Push the history into the display?
            DeleteOldHistory();
            var offset = 0;
            var history = new List<SymbolPhrase>();
            history.AddRange(this.history.history);
            history.Reverse();
            foreach (var historyItem in history)
            {
                SpawnHistoryPrefabsAndLayout(historyItem, offset);
                offset += 1;
                if (offset >= this.history.historySize)
                {
                    break;
                }
            }

            Debug.Log(string.Format("Update history with {0} items", history.Count));

            // Done~
            if (callback != null)
            { callback(this); }
        }
 public void TaskCompletionRecieved(TaskComplete task, MySqlConnection connection)
 {
     using (MySqlCommand command = new MySqlCommand(@"SELECT `RepeatInJSON`,`TimeOfExecution` FROM `tbTasks` WHERE Id = @Id", connection))
     {
         command.Parameters.AddWithValue("@Id", task.IDTask);
         using (MySqlDataReader reader = command.ExecuteReader())
         {
             if (reader.Read())
             {
                 if (reader["RepeatInJSON"] == DBNull.Value || JsonSerializationUtility.Deserialize <TaskRepeating>((string)reader["RepeatInJSON"]).Repeating == new TimeSpan(0))
                 {
                     reader.Close();
                     TaskRemove(task);
                 }
                 else
                 {
                     string json = (string)reader["RepeatInJSON"];
                     reader.Close();
                     TaskExtend(task, json);
                 }
             }
         }
     }
 }
Example #29
0
 internal Worker(TaskFunction function, TaskComplete completion)
 {
     Function   = function;
     Completion = completion;
     Error      = null;
 }
        public void RefreshObjects(int parentId, TaskProcess processCallback, TaskComplete completeCallback)
        {
            var task = CreateTask(RECommand.GetObjects, parentId, processCallback, completeCallback);

            Send(Address, task, OSCValue.Int(0));
        }
        public void ClearObjects(TaskComplete completeCallback)
        {
            var task = CreateTask(RECommand.Clear, 0, null, completeCallback);

            Send(Address, task);
        }
        private Task CreateTask(RECommand command, int parentId, TaskProcess processCallback, TaskComplete completeCallback)
        {
            var taskId = string.Format("{0}_{1}", parentId, command);
            var task   = new Task(command, parentId, taskId);

            if (_tasksDictionary.ContainsKey(taskId))
            {
                _tasksDictionary.Remove(taskId);
            }

            _tasksDictionary.Add(taskId, task);

            task.ProcessCallback  = processCallback;
            task.CompleteCallback = completeCallback;

            return(task);
        }
        private void TryBackup(TaskInfo task)
        {
            DateTime now = DateTime.Now;

            if (existTask == null)//如果没有正在备份
            {
                //if (!Directory.Exists(task.TargetDirectory))//如果不存在目标目录
                //{
                //    try
                //    {
                //        //尝试去创建
                //        Directory.CreateDirectory(task.TargetDirectory);
                //    }
                //    catch
                //    {
                //        task.LastBackupTime = now;
                //        //  AppendLog(itemsName[i], "目标目录不存在且无法创建,将在下一个周期重试。");
                //        //  txtLogPanel.Text = log.ToString();
                //        //  lvwTasks.Items.Refresh();
                //        return;
                //    }

                //}
                //else//如果目录存在
                //{
                //如果校验失败

                task.Status = TaskInfo.Statuses.BackingUp;

                currentCore = new BackupCore(task);
                Task t = new Task(currentCore.Backup);
                existTask = t;
                t.ContinueWith(p =>
                {
                    existTask   = null;
                    task.Status = TaskInfo.Statuses.Waiting;
                    if (task.RealTime)
                    {
                        task.LastBackupTime = DateTime.MaxValue;

                        task.DisplayStatus = "正在侦测";
                    }
                    else
                    {
                        task.LastBackupTime = DateTime.Now;
                    }
                    if (needToStop)
                    {
                        timer.Stop();
                        needToStop = false;
                    }
                    App.Current?.Dispatcher.Invoke(() =>
                    {
                        if (App.Current.MainWindow as MainWindow != null && App.Current.MainWindow.Visibility == System.Windows.Visibility.Visible)
                        {
                            (App.Current.MainWindow as MainWindow).ResetButtons();
                        }
                    });
                    TaskComplete?.Invoke(this, new TaskCompleteEventArgs(task));
                });
                t.Start();

                // }
            }
            else//如果正在备份其他的东西
            {
                task.DisplayStatus = "排队中";

                LogHelper.AppendLog(task, "因已有工作中的备份任务,该任务正在排队等待");
                task.Status = TaskInfo.Statuses.InTheLine;
            }
        }
Example #34
0
 public void ForceComplete()
 {
     _complete = true;
     TaskComplete.Set();
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="iClient"></param>
        public void Start(IPresenter.ICalculatorClient iClient)
        {
            this.iClient = iClient;

            this.IsRunning = true;
            this.TaskName = this.iClient.TaskName;
            this.Comment = this.iClient.Comment;
            this.taskWork = this.iClient.TaskWork;

            if (this.task == null)
            {
                this.task = new Thread(new ThreadStart(this.Run));
                this.task.Start();
            }

            if (this.isPause)
            {
                this.isPause = false;
            }
        }
        /// <summary>
        /// If next execution time exists new task is created and current is marked as completed else task is removed with <see cref="TaskRemove(TaskComplete)"/>
        /// </summary>
        /// <param name="taskComplete">Completed task</param>
        /// <param name="JsonTime">T<see cref="TaskRepeating"/> in json</param>
        private void TaskExtend(TaskComplete taskComplete, string JsonTime)
        {
            using (MySqlConnection connection = WebApiConfig.Connection())
            {
                connection.Open();
                TaskRepeating repeat = JsonSerializationUtility.Deserialize <TaskRepeating>(JsonTime);
                repeat = timer.TaskExtend(repeat);
                if (repeat == null)
                {
                    TaskRemove(taskComplete);
                    return;
                }
                else
                {
                    foreach (var item in repeat.ExecutionTimes)
                    {
                        while (this.HasDateException(item, repeat.ExceptionDates))
                        {
                            item.Add(repeat.Repeating);
                        }
                    }
                }
                repeat = timer.TaskExtend(repeat);
                //new task
                Task   originalTask = null;
                Task   newTask;
                string order = "";
                //BackupType: 0=Full, 1=Incr, 2=Diff
                int previousTaskID = 0;
                using (MySqlCommand command = new MySqlCommand("SELECT * FROM `tbTasks` WHERE `Id` = @id", connection))
                {
                    command.Parameters.AddWithValue("@id", taskComplete.IDTask);
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            originalTask   = JsonSerializationUtility.Deserialize <Task>((string)reader["Task"]);
                            order          = (string)reader["BackupTypePlan"];
                            previousTaskID = (int)reader["Id"];
                        }
                    }
                }
                if (originalTask == null)
                {
                    throw new Exception("Task " + taskComplete.IDTask + "cannot be found in database");
                }

                TaskRemove(taskComplete);

                string newOrder = "";
                newOrder += order.Substring(1, order.Length - 1);
                newOrder += order[0];

                int       previousTaskIDLast   = previousTaskID;
                ISource[] previousTasksSources = new ISource[newOrder.Length];
                int[]     previousTasksIds     = new int[newOrder.Length];
                //List<string> previousTasksData = new List<string>(order.Length);
                //Dictionary<int, string> previousTasksData = new Dictionary<int, string>(order.Length);
                for (int i = 0; i < newOrder.Length; i++)
                {
                    using (MySqlCommand command = new MySqlCommand("SELECT Task, IdPreviousTask FROM `tbTasks` WHERE `Id` = " + previousTaskIDLast, connection))
                    {
                        using (MySqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                //previousTasksTypes.Add((int)reader["PreviousTaskID"], (byte)reader["BackupType"]);
                                previousTasksSources[i] = JsonSerializationUtility.Deserialize <Task>((string)reader["Task"]).Sources;
                                previousTasksIds[i]     = previousTaskIDLast;
                                previousTaskIDLast      = (int)reader["IdPreviousTask"];
                            }
                        }
                    }
                }

                if (newOrder != null && newOrder.Length > 0)
                {
                    newTask = originalTask;
                    newTask.TimeToBackup = repeat.ExecutionTimes[0];
                    if (newOrder[0] == '0')
                    {
                        for (int i = newOrder.Length - 1; i > 0; i--)
                        {
                            if (previousTasksSources[i] is SourceFolders)
                            {
                                newTask.Sources = previousTasksSources[i];
                                break;
                            }
                        }
                    }
                    else if (newOrder[0] == '1')
                    {
                        for (int i = newOrder.Length - 1; i > 0; i--)
                        {
                            if (previousTasksSources[i] is SourceFolders)
                            {
                                using (MySqlCommand command = new MySqlCommand("SELECT BackupJournal FROM tbTasksCompleted WHERE IdTask = " + previousTasksIds[i], connection))
                                {
                                    using (MySqlDataReader reader = command.ExecuteReader())
                                    {
                                        while (reader.Read())
                                        {
                                            newTask.Sources = JsonConvert.DeserializeObject <BackupJournalObject>((string)reader["BackupJournal"]);
                                        }
                                    }
                                }
                                break;
                            }
                        }
                        //int lastID = previousTasksIds[newOrder.Length - 1];
                        //int i = 0;
                        //while (lastID == 0)
                        //{
                        //    lastID = previousTasksIds[newOrder.Length - 1 - i];
                        //    i++;
                        //}
                        //using (MySqlCommand command = new MySqlCommand("SELECT BackupJournal FROM tbTasksCompleted WHERE IdTask = " + lastID, connection))
                        //{
                        //    using (MySqlDataReader reader = command.ExecuteReader())
                        //    {
                        //        while (reader.Read())
                        //        {
                        //            //previousTasksTypes.Add((int)reader["PreviousTaskID"], (byte)reader["BackupType"]);

                        //            newTask.Sources = JsonConvert.DeserializeObject<BackupJournalObject>(b.Base64Decode((string)reader["BackupJournal"]));
                        //        }
                        //    }

                        //}
                    }
                    else if (newOrder[0] == '2')
                    {
                        for (int i = newOrder.Length - 1; i > 0; i--)
                        {
                            int lastID = previousTasksIds[i];
                            int y      = 1;
                            while (lastID == 0)
                            {
                                lastID = previousTasksIds[i] - y;
                                y++;
                            }
                            if (newOrder[i] == '0')
                            {
                                using (MySqlCommand command = new MySqlCommand("SELECT BackupJournal FROM tbTasksCompleted WHERE IdTask = " + previousTasksIds[i], connection))
                                {
                                    using (MySqlDataReader reader = command.ExecuteReader())
                                    {
                                        while (reader.Read())
                                        {
                                            //previousTasksTypes.Add((int)reader["PreviousTaskID"], (byte)reader["BackupType"]);
                                            newTask.Sources = JsonConvert.DeserializeObject <BackupJournalObject>((string)reader["BackupJournal"]);
                                        }
                                    }
                                }
                                break;
                            }
                        }
                    }
                }
                else
                {
                    throw new Exception("Order is undefined");
                }
                newTask.IDTask = sqlAdmin.NextAutoIncrement("tbTasks");
                sqlAdmin.AlterTable(new Models.Tables.ChangeTable()
                {
                    ColumnName = "RepeatInJSON", Id = taskComplete.IDTask, TableName = "tbTasks", Value = JsonSerializationUtility.Serialize(repeat)
                });
                using (MySqlCommand command = new MySqlCommand("INSERT INTO `tbTasks`(`IdDaemon`, `Task`, `TimeOfExecution`, `IdPreviousTask`, `BackupTypePlan`, `RepeatInJSON`, `Completed`)" +
                                                               " VALUES (@IdDaemon, @Task, @TimeOfExecution, @IdPreviousTask, @BackupPlan, @Repeat, 0 )", connection))
                {
                    command.Parameters.AddWithValue("@IdDaemon", GetDaemonId(taskComplete.DaemonInfo));
                    command.Parameters.AddWithValue("@Task", JsonSerializationUtility.Serialize(newTask));
                    command.Parameters.AddWithValue("@TimeOfExecution", repeat.ExecutionTimes[0]);
                    command.Parameters.AddWithValue("@Repeat", JsonSerializationUtility.Serialize(repeat));
                    command.Parameters.AddWithValue("@IdPreviousTask", taskComplete.IDTask);
                    command.Parameters.AddWithValue("@BackupPlan", newOrder);
                    command.ExecuteNonQuery();
                }

                /*
                 * repeat.ExecutionTimes.Sort();
                 * DateTime nextDate = repeat.ExecutionTimes.Last();
                 * bool DateChanged = false;
                 * foreach (var item in repeat.ExecutionTimes)
                 * {
                 *  if (item > DateTime.Now)
                 *  {
                 *      bool NotException = HasDateException(item, repeat.ExceptionDates);
                 *      if (NotException)
                 *      {
                 *          nextDate = item;
                 *          DateChanged = true;
                 *          break;
                 *      }
                 *  }
                 * }
                 * if (!DateChanged)
                 * {
                 *  if (repeat.RepeatTill == null)
                 *  {
                 *      bool DateOk = true;
                 *      while (repeat.ExecutionTimes[0] < DateTime.Now || !DateOk)
                 *      {
                 *          for (int i = 0; i < repeat.ExecutionTimes.Count; i++)
                 *          {
                 *              repeat.ExecutionTimes[i] += repeat.Repeating;
                 *          }
                 *          DateOk = DateAvailable(repeat.ExecutionTimes, repeat.ExceptionDates);
                 *      }
                 *  }
                 *  else
                 *  {
                 *      bool DateOk = true;
                 *      while (repeat.ExecutionTimes[0] < DateTime.Now || !DateOk)
                 *      {
                 *          List<int> ToDelete = new List<int>();
                 *          for (int i = 0; i < repeat.ExecutionTimes.Count; i++)
                 *          {
                 *              if (repeat.ExecutionTimes[i] + repeat.Repeating < repeat.RepeatTill)
                 *                  repeat.ExecutionTimes[i] += repeat.Repeating;
                 *              else
                 *                  ToDelete.Add(i);
                 *          }
                 *          for (int i = ToDelete.Count - 1; i >= 0; i--)
                 *          {
                 *              repeat.ExecutionTimes.RemoveAt(ToDelete[i]);
                 *          }
                 *          if (repeat.ExecutionTimes.Count == 0)
                 *              break;
                 *          DateOk = DateAvailable(repeat.ExecutionTimes, repeat.ExceptionDates);
                 *      }
                 *  }
                 *  foreach (var item in repeat.ExecutionTimes)
                 *  {
                 *      if (item > DateTime.Now)
                 *      {
                 *          nextDate = item;
                 *          break;
                 *      }
                 *  }
                 * }
                 * if (repeat.ExecutionTimes.Count == 0)
                 * {
                 *  TaskRemove(taskComplete);
                 * }
                 * else
                 * {
                 *  using (MySqlCommand command = new MySqlCommand(@"SELECT * FROM `tbTasks` WHERE Id = @Id", connection))
                 *  {
                 *      int IdDaemon;
                 *      string Task;
                 *      DateTime TimeOfExecution;
                 *      string RepeatInJSON;
                 *      command.Parameters.AddWithValue("@Id", taskComplete.IDTask);
                 *      using (MySqlDataReader reader = command.ExecuteReader())
                 *      {
                 *          if (reader.Read())
                 *          {
                 *              IdDaemon = (int)reader["IdDaemon"];
                 *              Task = (string)reader["Task"];
                 *              TimeOfExecution = (DateTime)reader["TimeOfExecution"];
                 *              RepeatInJSON = (string)reader["RepeatInJSON"];
                 *          }
                 *          else
                 *          {
                 *              throw new Exception();
                 *          }
                 *      }
                 *      Task TaskClass = JsonSerializationUtility.Deserialize<Task>(Task);
                 *      TaskRemove(taskComplete);
                 *      command.CommandText = "SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = '3b1_kocourekmatej_db2' AND TABLE_NAME = 'tbTasks'";
                 *      using (MySqlDataReader reader = command.ExecuteReader())
                 *      {
                 *          if (reader.Read())
                 *              taskComplete.IDTask = Convert.ToInt32(reader["AUTO_INCREMENT"]);
                 *          else
                 *              throw new Exception();
                 *      }
                 *      TaskClass.IDTask = taskComplete.IDTask;
                 *      TaskClass.Sources = taskComplete.DatFile;
                 *      Task = JsonSerializationUtility.Serialize(TaskClass);
                 *      command.CommandText = "INSERT INTO `tbTasks` VALUES (null, @IdDaemon, @Task, @TimeOfExecution, @RepeatInJSON, @Completed)";
                 *      command.Parameters.AddWithValue("@IdDaemon", IdDaemon);
                 *      command.Parameters.AddWithValue("@Task", Task);
                 *      command.Parameters.AddWithValue("@TimeOfExecution", TimeOfExecution);
                 *      command.Parameters.AddWithValue("@RepeatInJSON", RepeatInJSON);
                 *      command.Parameters.AddWithValue("@Completed", 0);
                 *      command.ExecuteNonQuery();
                 *  }
                 * }*/
            }
        }
Example #37
0
 internal Worker(TaskFunction function, TaskComplete completion)
 {
     function_   = function;
     completion_ = completion;
     error_      = null;
 }
Example #38
0
 public ITask AddTask(ThreadTarget threadTarget, TaskFunction function, TaskComplete completion, TaskContext ctx)
 {
     return(_wrappers[(int)threadTarget].AddTask(function, completion, ctx));
 }
Example #39
0
 internal Worker(TaskFunction function, TaskComplete completion)
 {
     function_ = function;
     completion_ = completion;
     error_ = null;
 }
Example #40
0
 /// <summary>
 /// Add a task to the thread queue. When a thread is available, it will 
 /// dequeue this task and run it. Once complete, the task will be marked 
 /// complete, but your application won't be called back until the next 
 /// time Update() is called (so that callbacks are from the main thread).
 /// </summary>
 /// <param name="function">The function to call within the thread.</param>
 /// <param name="completion">The callback to report results to, or null. If 
 /// you care about which particular task has completed, use a different instance 
 /// for this delegate per task (typically, a delegate on the task itself).</param>
 /// <param name="ctx">A previously allocated TaskContext, to allow for waiting 
 /// on the task, or null. It cannot have been already used.</param>
 /// <returns>A Task identifier for the operation in question. Note: because
 /// of the threaded behavior, the task may have already completed when it 
 /// is returned. However, if you AddTask() from the main thread, the completion 
 /// function will not yet have been called.</returns>
 public Task AddTask(TaskFunction function, TaskComplete completion, TaskContext ctx, object argument)
 {
     if (function == null)
     throw new System.ArgumentNullException("function");
       Worker w;
       lock (this)
       {
     if (disposed_)
       throw new System.ObjectDisposedException("ParallelThreadPool");
     qDepth_++;
     w = NewWorker(function, completion, argument);
     if (ctx != null)
       ctx.Init(w);
     if (workList_ == null)
       workList_ = w;
     else
       workListEnd_.next_ = w;
     workListEnd_ = w;
       }
       workEvent_.Set();
       return w;
 }
Example #41
0
 Worker NewWorker(TaskFunction tf, TaskComplete tc, object argument)
 {
     if (freeList_ == null)
     freeList_ = new Worker(null, null);
       Worker ret = freeList_;
       freeList_ = ret.next_;
       ret.function_ = tf;
       ret.completion_ = tc;
       ret.context_ = null;
       ret.error_ = null;
       ret.next_ = null;
       ret.argument = argument;
       return ret;
 }