Esempio n. 1
0
        public void Execute(TaskContext context, TaskAction action)
        {
            if (action.Items == null || action.Items.Length == 0)
            {
                action.Items = context.JobOption.SlnFiles;
            }

            if (action.Items == null || action.Items.Length == 0)
            {
                return;
            }


            foreach (string path in action.Items)
            {
                string        commandArgs = $"  \"{path}\"  /t:Rebuild /p:Configuration=\"Debug\" /consoleloggerparameters:ErrorsOnly /nologo /m";
                ExecuteResult result      = CommandLineHelper.Execute(s_msbuildPath, commandArgs);
                context.ConsoleWrite(result.ToString());

                // 注意:
                // 有些分支下面可能包含多个解决方案文件 sln,会导致编译多次
                // 这里的判断逻辑是:只要有一个项目没有编译通过,就认为是编译失败

                if (context.TotalResult.BuildIsOK.HasValue == false ||  // 还没有赋值过(第一次进入)
                    context.TotalResult.BuildIsOK.Value                 // 前面编译成功
                    )
                {
                    string text = result.Output.Trim(' ', '\r', '\n', '\t');
                    context.TotalResult.BuildIsOK = string.IsNullOrEmpty(text);
                }
            }
        }
Esempio n. 2
0
        internal static void ShareExecute(TaskContext context, TaskAction action, Action <string> callback)
        {
            if (action.Items == null || action.Items.Length == 0)
            {
                action.Items = context.JobOption.SlnFiles;
            }

            if (action.Items == null || action.Items.Length == 0)
            {
                return;
            }

            foreach (string sln in action.Items)
            {
                List <string> projectFiles = SlnFileHelper.GetProjectFiles(sln);

                foreach (string file in projectFiles)
                {
                    string projectName = Path.GetFileNameWithoutExtension(file);
                    if (projectName.EndsWith("Test"))
                    {
                        continue;
                    }

                    // 忽略WEB项目
                    if (file.IndexOf(".Web") > 0)
                    {
                        continue;
                    }

                    callback(file);
                }
            }
        }
Esempio n. 3
0
        public void FinishTask(Guid taskInstanceID, int taskActionId, string userName, string newPerformerID, string comment)
        {
            TaskAction   action = wfs.GetTaskActionByID(taskActionId);
            TaskInstance ts     = wfs.GetTaskInstanceByID(taskInstanceID);

            FinishTask(ts, action, userName, newPerformerID, comment, null);
        }
Esempio n. 4
0
        public TaskEventArgs([NotNull] Task task, [NotNull] TaskAction action)
        {
            Task   = task;
            Action = action;

            Version = GetAssemblyVersion();
        }
Esempio n. 5
0
        public static TaskAction <R> StartNew <R>(TaskAction <R> function)
        {
            R      retv      = (R)default(R);
            bool   completed = false;
            object sync      = new object();

            function.BeginInvoke(delegate(IAsyncResult iAsyncResult)
            {
                lock (sync)
                {
                    completed = true;
                    retv      = (R)function.EndInvoke(iAsyncResult);
                    Monitor.Pulse(sync);
                }
            }, null);
            return(delegate
            {
                lock (sync)
                {
                    if (!completed)
                    {
                        Monitor.Wait(sync);
                    }
                    return (R)retv;
                }
            });
        }
Esempio n. 6
0
        public static Task Register(string Name, TaskAction Act)
        {
            lock (Lock) {
                Task T = GetByName(Name);
                if (T != null)
                {
                    if (Program.DEBUG_NAMES)
                    {
                        Console.WriteLine("Removing task '{0}'", Name);
                    }

                    Remove(T);
                }

                if (Program.DEBUG_NAMES)
                {
                    Console.WriteLine("Registering task '{0}'", Name);
                }

                T = new Task(Name, Act);
                T.ScheduleNext(DateTime.Now);
                TaskList.Add(T);

                return(T);
            }
        }
Esempio n. 7
0
        public void Execute(TaskContext context, TaskAction action)
        {
            if (action.Items == null || action.Items.Length == 0)
            {
                action.Items = context.JobOption.SlnFiles;
            }

            if (action.Items == null || action.Items.Length == 0)
            {
                return;
            }

            TotalResult totalResult             = context.TotalResult;
            List <VsRuleCheckResult> resultList = new List <VsRuleCheckResult>();

            try {
                foreach (string path in action.Items)
                {
                    VsRuleScaner             scaner = new VsRuleScaner();
                    List <VsRuleCheckResult> list   = scaner.Execute(context.Branch, path);
                    resultList.AddRange(list);
                }
                totalResult.VsRuleCheckResults.AddRange(resultList);
                context.ConsoleWrite("VsRuleScanTask OK");
            }
            catch (Exception ex) {
                totalResult.VsRuleCheckException = ex.ToString();
                context.ProcessException(ex);
            }
        }
Esempio n. 8
0
        internal void LoadData(TaskAction action, IRTask task)
        {
            IRWorkflow workflow = null;

            if (action == TaskAction.Send)
            {
                workflow = NewWorkflowData(task);
            }
            else
            {
                if (!task.InstID.HasValue)
                {
                    throw new ArgumentException("Argument(task.InstID) is null!", "task");
                }
                workflow = FetchWorkflowData(task.InstID.Value);
            }

            if (workflow == null)
            {
                throw new ApplicationException("Laoding WorkFlow Data Failed!");
            }


            ClearData();
            Task = task;
            Data = workflow;
        }
Esempio n. 9
0
        public bool IsUserAllowedToDo(int taskId, int userId, TaskAction action)
        {
            bool result = false;
            var  task   = GetTask(taskId);

            switch (action)
            {
            case TaskAction.Show:
                result = task.Project.Workspace.Owner.Id == userId ||
                         task.Project.Team.Any(t => t.UserId == userId && t.AccessLevel != AccessLevel.Partial) ||
                         task.ResponsibleId.GetValueOrDefault() == userId;
                break;

            case TaskAction.Accept:
                result = task.Project.Team.Any(t => t.UserId == userId && t.AccessLevel != AccessLevel.Partial);
                break;

            case TaskAction.Start:
            case TaskAction.Complete:
                result = task.ResponsibleId == userId;
                break;

            case TaskAction.Delete:
                result =
                    task.Project.Team.Any(t => t.UserId == userId && t.AccessLevel == AccessLevel.ProjectManager);
                break;
            }
            return(result);
        }
Esempio n. 10
0
 public void TaskDone(TaskAction doneTaskAction)
 {
     if (dailyTask.taskType == TaskType.Action && dailyTask.taskAction == doneTaskAction)
     {
         GetReward();
     }
 }
Esempio n. 11
0
        protected void Session_End(object sender, EventArgs e)
        {
            //下面的代码是关键,可解决IIS应用程序池自动回收的问题
            System.Threading.Thread.Sleep(1000);
            //触发事件, 写入提示信息
            TaskAction.SetContent();
            //这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start
            //使用您自己的URL
//#if DEBUG
//            string url = "http://localhost:25664//api/OnLinePlay/GetOnLineUser?pageSize=112&pageIndex=1";
//#endif
//#if R17
//           string url = "http://192.168.1.17:8017/api/OnLinePlay/GetOnLineUser?pageSize=112&pageIndex=1";
//#endif
//#if Release
//             string url = "http://api.515.com/api/OnLinePlay/GetOnLineUser?pageSize=10&pageIndex=1";
//#endif
//#if Test
//            string url = "http://tapi.515.com/api/OnLinePlay/GetOnLineUser?pageSize=10&pageIndex=1";
//#endif

            string url = PubConstant.GetConnectionString("homeUrl");


            System.Net.HttpWebRequest  myHttpWebRequest  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
            System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
            System.IO.Stream           receiveStream     = myHttpWebResponse.GetResponseStream();//得到回写的字节流

            // 在会话结束时运行的代码。
            // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 InProc 时,才会引发 Session_End 事件。
            // 如果会话模式设置为 StateServer
            // 或 SQLServer,则不会引发该事件。
        }
Esempio n. 12
0
        public void Execute(TaskContext context, TaskAction action)
        {
            string[] files = Directory.GetFiles(context.TempPath, "*.*", SearchOption.TopDirectoryOnly);
            if (files.Length == 0)
            {
                return;
            }


            // 获取所有日志文件,仅包含:xml, txt
            string[] logFiles = (from f in files
                                 where f.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) ||
                                 f.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)
                                 select f).ToArray();

            string zipFile = context.Branch.Id.ToString() + "__log.zip";
            string zipPath = Path.Combine(context.TempPath, zipFile);

            // 创建压缩包文件
            ZipHelper.CreateZipFile(zipPath, logFiles);

            // 上传日志
            string     website = ConfigurationManager.AppSettings["ServiceWebsite"];
            HttpOption option  = new HttpOption {
                Method = "POST",
                Url    = website.TrimEnd('/') + "/ajax/scan/Upload/UploadClientLog.ppx",
                Data   = new { logFile = new FileInfo(zipPath), flag = context.Branch.Id }
            };

            option.GetResult();

            context.ConsoleWrite("UploadClientLogTask OK");
        }
Esempio n. 13
0
 public override void SaveForm()
 {
     try
     {
         WorkflowService wfs = new WorkflowService();
         using (wfs)
         {
             if (this.IsInsertMode)
             {
                 TaskAction dto = wfs.ObjectContext.TaskAction.CreateObject();
                 dto.InsertUser = this.CurrentUserCode;
                 dto.InsertDate = DateTime.Now;
                 this.GetDataFromControls(dto);
                 wfs.ObjectContext.TaskAction.AddObject(dto);
             }
             else
             {
                 TaskAction dto = wfs.ObjectContext.TaskAction.First(w => w.TaskActionID == this.RecordID);
                 dto.UpdateUser = this.CurrentUserCode;
                 dto.UpdateDate = DateTime.Now;
                 this.GetDataFromControls(dto);
             }
             wfs.ObjectContext.SaveChanges();
             NotifyMessage("اطلاعات با موفقيت ثبت شد", NotifyTypeEnum.Info);
         }
     }
     catch (Exception ex)
     {
         ShowException(ex);
     }
 }
Esempio n. 14
0
 public void Add(TaskAction action)
 {
     if (action == null)
     {
         return;
     }
     tasks.Add(action);
 }
Esempio n. 15
0
 /// <summary>
 /// Action the specified builder and action.
 /// </summary>
 /// <returns>The action.</returns>
 /// <param name="builder">Builder.</param>
 /// <param name="action">Action.</param>
 /// <typeparam name="T">The 1st type parameter.</typeparam>
 public static TaskBuilder <T> Action <T>
 (
     this TaskBuilder <T> builder,
     TaskAction <T> .Delegate action
 )
 {
     return(builder.Push(new TaskAction <T>(action)));
 }
Esempio n. 16
0
 public Task(TaskAction when, int delay, string command)
 {
     IsEnabled   = true;
     When        = when;
     SecondDelay = delay;
     Command     = command;
     TaskId      = "" + ++TaskIdCount;
 }
Esempio n. 17
0
        public static bool IsEqualsTo(this ITask task,
                                      string title, string note, string tags,
                                      DateTime?due, DateTime?start, DateTime?alarm,
                                      ICustomFrequency customFrequency, bool useFixedDate,
                                      TaskPriority priority, double?progress, bool isCompleted,
                                      TaskAction action, string actionName, string actionValue,
                                      IContext context,
                                      IFolder folder,
                                      IList <ITask> subtasks)
        {
            bool match = string.Equals(task.Title, title) &&
                         task.Note.IsEqualsOrEmptyTo(note) &&
                         task.Tags.IsEqualsOrEmptyTo(tags) &&
                         ((!task.Due.HasValue && !due.HasValue) || (task.Due.HasValue && due.HasValue && task.Due.Value.Date.Equals(due.Value.Date))) &&
                         ((!task.Start.HasValue && !start.HasValue) || (task.Start.HasValue && start.HasValue && task.Start.Equals(start))) &&
                         task.Completed.HasValue.Equals(isCompleted) &&
                         (
                (task.CustomFrequency == null && (customFrequency == null || customFrequency is OnceOnlyFrequency)) ||
                ((task.CustomFrequency is OnceOnlyFrequency || task.CustomFrequency == null) && (customFrequency == null)) ||
                (task.CustomFrequency != null && task.CustomFrequency.Equals(customFrequency) && task.UseFixedDate.Equals(useFixedDate))
                         ) &&
                         task.Priority == priority &&
                         task.Action == action &&
                         task.ActionName.IsEqualsOrEmptyTo(actionName) &&
                         task.ActionValue.IsEqualsOrEmptyTo(actionValue) &&
                         task.Alarm.Equals(alarm) &&
                         task.Progress.Equals(progress) &&
                         Equals(task.Context, context) &&
                         Equals(task.Folder, folder);

            if (!match)
            {
                return(false);
            }

            if (task.Children.Count != subtasks.Count)
            {
                return(false);
            }

            for (int i = 0; i < task.Children.Count; i++)
            {
                var  subtask      = task.Children[i];
                var  other        = subtasks[i];
                bool subtaskMatch = IsEqualsTo(subtask, other.Title, other.Note, other.Tags, other.Due, other.Start,
                                               other.Alarm, other.CustomFrequency, other.UseFixedDate, other.Priority, other.Progress, other.IsCompleted,
                                               other.Action, other.ActionName, other.ActionValue, other.Context, subtask.Folder, EmptyTasks);
                // use subtask.Folder while it should be other.Folder because we want to skip the folder comparison
                // reason is that when we edit a task, we edit a copy of its subtask and the folder is not set

                if (!subtaskMatch)
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 18
0
        public async override Task Run()
        {
            await base.Run();

            try
            {
                IsContinue();
                DateTime dateTime = _paramDescriptors.ConvertDate(RunDateTime);
                Log.Info($"Задача {TaskId} : Загрузка валют за дату {dateTime.ToShortDateString()}");
                var xmlDocument = await _cbrDownloader.DownloadForeignExchange(dateTime);

                Log.Info($"Задача {TaskId} : Загрузка валют завершена");

                IsContinue();
                var saverJson = TaskAction.GetSaverJson(TaskId);
                if (saverJson is not null)
                {
                    Log.Info($"Задача {TaskId} : Сохранение значений");
                    _xmlSaver.Deserialize(saverJson).Save(xmlDocument);
                    Log.Info($"Задача {TaskId} : Значения сохранены");

                    var connection = _xmlSaver.Deserialize(saverJson).Connection;

                    var task       = TaskAction.GetKarmaDownloadJob().FirstOrDefault(z => z.TaskId == TaskId);
                    var template   = TaskAction.GetCalculationJson(task.TaskTemplateId);
                    var saveTask   = new SaveForeignExchange(null, null, null, null, null);
                    var parameters = saveTask.GetParamDescriptors();

                    parameters.SetDat(SaveForeignExchange.RunDateTime, dateTime);
                    parameters.SetStr(SaveForeignExchange.File, connection);
                    var json = parameters.SerializeJson();

                    Log.Info($"Создаем задачу {saveTask.TaskTypes.ToDbAttribute()} с параметрами {json}");
                    var newTaskId = TaskAction.CreateTaskAction(TaskStatuses.Creating,
                                                                TaskTypes.DownloadCurrenciesCbrf.ToDbAttribute(),
                                                                template.TaskTemplateFolderId,
                                                                json,
                                                                TaskTypes.SaveForeignExchange);

                    TaskAction.InsertPipelineTasks(TaskId, newTaskId);
                    Log.Info($"Создали зависимость между {TaskId}->{newTaskId}");
                }
                Log.Info($"Задача {TaskId} : Задачи завершена");
                Finished();
            }
            catch (OperationCanceledException)
            {
                Log.Info($"Задача отменена {TaskId}");
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
            finally
            {
                IsAliveTokenSource.Cancel();
            }
        }
Esempio n. 19
0
        public Task(string Name, TaskAction A)
        {
            this.Name   = Name;
            this.Action = A;

            Delete        = false;
            RepeatSeconds = 0;
            Userdata      = null;
        }
Esempio n. 20
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     TaskAction.TaskRegister();
 }
Esempio n. 21
0
        public void LoadFormByRecordID()
        {
            WorkflowService wfs = new WorkflowService();

            using (wfs)
            {
                TaskAction dto = wfs.ObjectContext.TaskAction.First(w => w.TaskActionID == this.RecordID);
                SetDataToControls(dto);
            }
        }
Esempio n. 22
0
        public override void GetDataFromControls(object obj)
        {
            TaskAction o = (TaskAction)obj;

            //o.TaskActionID = FieldGetValue.ToInt32(TaskActionIDTextBox.Text, TaskActionIDLabel.Text);
            o.TaskID          = FieldGetValue.ToInt32(TaskIDComboBox.SelectedValue, TaskIDLabel.Text);
            o.ToTaskID        = FieldGetValue.ToInt32(ToTaskIDComboBox.SelectedValue, ToTaskIDLabel.Text);
            o.TaskActionCode  = FieldGetValue.ToString(TaskActionCodeTextBox.Text, TaskActionCodeLabel.Text, 100);
            o.TaskActionTitle = FieldGetValue.ToString(TaskActionTitleTextBox.Text, TaskActionTitleLabel.Text, 100);
            o.HasProgramming  = FieldGetValue.ToBoolean(HasProgrammingComboBox.SelectedItem.Value, HasProgrammingLabel.Text);
        }
Esempio n. 23
0
        static void Main(string[] args)
        {
            TaskClass  task1  = new TaskClass("FirstTask");
            TaskClass  task2  = new TaskClass("SecondTask");
            TaskAction action = new TaskAction();

            action.Add(task1);
            action.Add(task2);

            action.Delete("FirstTask");
        }
Esempio n. 24
0
        static TaskAction Next(ActionQueue actions)
        {
            TaskAction action = null;

            if (actions.HasNext())
            {
                action = actions.tasks[actions.current];
                actions.current++;
                Save();
            }
            return(action);
        }
Esempio n. 25
0
        public async Task <IJsonResponse <TaskResponse> > CreateTask(
            [FromRoute] string name, [FromBody] TaskRequest request)
        {
            var command  = request.ToCommand(name);
            var response = await RequestAsync(command);

            return(response switch {
                TaskAction r => Result(r.ToResponse()),
                TaskNotFound e => NotFound(e),
                IError e => BadRequest(e),
                var m => Unexpected(m),
            });
Esempio n. 26
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            log4netRegister.Register();

            TaskAction.TaskRegister();

            //HibernatingRhinos.Profiler.Appender.EntityFramework.EntityFrameworkProfiler.Initialize();
        }
        /// <summary>
        /// Closes every possible connections from this object to the server.
        /// This method also set appropriate flags for stored game data on server,
        /// as well as (might be) triggering GC with null values
        /// </summary>
        public void Close(bool deleteData = false)
        {
            if (!IsConnectionClosed)
            {
                string role   = _role.ToString();
                bool   isHost = _role == MultiplayerRole.Host;

                // sudden close
                if (CurrentData?.State == GameState.Playing)
                {
                    CurrentData?.ChangeGameState(
                        isHost ? GameState.HostExited : GameState.GuestExited,
                        true, true
                        );
                }

                // stop the stop watch
                _stopWatch.Stop();

                // cancel the token source first
                _tokenSource.Cancel();
                _mainTask.Wait();
                _mainTask.Dispose();
                Logger.Log($"Main task finished from {role}");

                // then free up every tasks
                _uploadTask.Close();
                _downloadTask.Close();
                Logger.Log($"Other tasks also finished from {role}");

                // set to null for next check / gc invoker
                _tokenSource  = null;
                _mainTask     = null;
                _uploadTask   = null;
                _downloadTask = null;

                // leave only settings and game state behind, not deleting all of it...
                if (deleteData)
                {
                    // delete parts of the game
                    Firebase.Delete(GetLink("host")).Wait(Constants.TIMEOUT);
                    Firebase.Delete(GetLink("opponent")).Wait(Constants.TIMEOUT);
                }

                // set flag
                IsConnectionClosed = true;

                // log
                Logger.Log($"Successfully closed connection to the server from {role}");
            }
        }
Esempio n. 28
0
        public ProcessingBigTaskDialog(MainForm owner, string caption, string desc, TaskAction task, object data)
        {
            this.InitializeComponent();

            this.owner       = owner;
            this.taskCaption = caption;
            this.taskDesc    = desc;
            this.task        = task;
            this.data        = data;

            this.Text                = this.taskCaption;
            this.descLabel.Text      = this.taskDesc;
            this.stateDescLabel.Text = "";
        }
		public ProcessingBigTaskDialog(MainForm owner, string caption, string desc, TaskAction task, object data)
		{
			this.InitializeComponent();

			this.owner = owner;
			this.taskCaption = caption;
			this.taskDesc = desc;
			this.task = task;
			this.data = data;

			this.Text = this.taskCaption;
			this.descLabel.Text = this.taskDesc;
			this.stateDescLabel.Text = "";
		}
Esempio n. 30
0
        /// <summary>
        /// Создать задачу
        /// </summary>
        /// <param name="category">Выбранная категория</param>
        /// <param name="person">Выбранный персон</param>
        static void CreateTask(Category category, Person person)
        {
            var task = new TaskAction()
            {
                Id         = ListTask.Count + 1,
                Category   = category,
                Person     = person,
                IsFinished = false,
                PlanStart  = DateTime.Now
            };


            ListTask.Add(task);
        }
Esempio n. 31
0
        //执行任务列表
        private void button2_Click(object sender, EventArgs e)
        {
            //ExcuteTask()
            List <TaskModel> tasks = TaskAction.GetTaskList();

            new Thread(() =>
            {//开启新线程,避免与主线程UI冲突,导致界面假死
                foreach (TaskModel item in tasks)
                {
                    ExcuteTask(item);
                    Thread.Sleep((int)numericUpDown1.Value * BASENUM);
                }
            }).Start();
        }
Esempio n. 32
0
		public ProcessingBigTaskDialog(MainForm owner, string caption, string desc, TaskAction task, object data)
		{
			this.InitializeComponent();

			if (owner == null) this.StartPosition = FormStartPosition.CenterScreen;

			this.targetForm = (Form)owner ?? this;
			this.taskCaption = caption;
			this.taskDesc = desc;
			this.task = task;
			this.data = data;

			this.Text = this.taskCaption;
			this.descLabel.Text = this.taskDesc;
			this.stateDescLabel.Text = "";
		}
Esempio n. 33
0
        public void OperationsTest() {
            var results = new List<Result>();
            var queue = new IdleTimeAsyncTaskQueue(_editorShell);

            var ta = new TaskAction(1, results);
            queue.Enqueue(ta.Action, ta.CallBackAction, typeof(TaskAction));

            ta = new TaskAction(2, results);
            queue.Enqueue(ta.Action, ta.CallBackAction, typeof(TaskAction));

            ta = new TaskAction(3, results);
            queue.Enqueue(ta.Action, ta.CallBackAction, typeof(TaskAction));

            RunThreads();

            results.Count.Should().Be(3);
            results[0].Id.Should().Be(1);
            results[1].Id.Should().Be(2);
            results[2].Id.Should().Be(3);

            results.Clear();

            ta = new TaskAction(1, results);
            object o1 = 1;
            queue.Enqueue(ta.Action, ta.CallBackAction, o1);

            ta = new TaskAction(2, results);
            object o2 = 2;
            queue.Enqueue(ta.Action, ta.CallBackAction, o2);

            ta = new TaskAction(3, results);
            object o3 = 3;
            queue.Enqueue(ta.Action, ta.CallBackAction, o3);

            queue.IncreasePriority(o3);
            RunThreads();

            results.Count.Should().Be(3);
            results[0].Id.Should().Be(3);
            results[1].Id.Should().Be(1);
            results[2].Id.Should().Be(2);
        }
        /// <summary>
        /// Starts the normal search for the KSP install folder.
        /// </summary>
        public static void FolderSearch4KSPPath()
        {
            if (View.btnKSPFolderSearch.Tag != null && View.btnKSPFolderSearch.Tag.ToString() == STOP)
            {
                OptionsController.StopSearch4KSPPath();
                return;
            }

            Messenger.AddInfo(Messages.MSG_KSP_SEARCH_STARTED);

            mStopSearch = false;
            mTaskAction = TaskAction.FolderSearch;
            EventDistributor.InvokeAsyncTaskStarted(Instance);
            AsyncTask<List<string>>.DoWork(() =>
            {
                string adminDir = Path.GetDirectoryName(Application.ExecutablePath);

                int depth = 1;
                bool done = false;
                DirectoryInfo dirInfo = Directory.GetParent(adminDir);
                while ((depth <= View.SearchDepth || 0 == View.SearchDepth) && !done && !mStopSearch)
                {
                    if (dirInfo == null || dirInfo.Root.FullName == dirInfo.FullName)
                    {
                        done = true;
                        break;
                    }

                    dirInfo = dirInfo.Parent;
                    ++depth;
                }

                List<string> list = new List<string>();
                if (dirInfo != null)
                    SearchSubDirs(dirInfo.FullName, View.SearchDepth * 2, ref list);

                return list;
            }, (list, ex) =>
            {
                EventDistributor.InvokeAsyncTaskDone(Instance);

                if (ex != null)
                {
                    MessageBox.Show(View.ParentForm, ex.Message);
                    Messenger.AddError(Messages.MSG_ERROR_WHILE_FOLDER_SEARCH, ex);
                }
                else
                {
                    if (!mStopSearch)
                    {
                        TryAddPaths(list.ToArray());

                        if (list.Count == 0)
                            Messenger.AddInfo(Messages.MSG_KSP_FOLDER_NOT_FOUND);
                        else
                            Messenger.AddInfo(Messages.MSG_KSP_SEARCH_DONE);
                    }
                }
            });
        }
Esempio n. 35
0
		public ProcessingBigTaskDialog(string caption, string desc, TaskAction task, object data) : this(null, caption, desc, task, data) {}
        /// <summary>
        /// Starts an async Job.
        /// Gets the current version from "www.services.mactee.de/..."
        /// and asks to start a download if new version is available.
        /// </summary>
        public static void Check4AppUpdatesAsync()
        {
            Messenger.AddInfo(Messages.MSG_KSPMA_UPDATE_CHECK_STARTED);
            mTaskAction = TaskAction.AppUpdateCheck;
            EventDistributor.InvokeAsyncTaskStarted(Instance);
            AsyncTask<WebResponse>.DoWork(
                () => GetAdminVersionFromWeb(),
                (WebResponse response, Exception ex) =>
                {
                    EventDistributor.InvokeAsyncTaskDone(Instance);

                    if (ex != null)
                        Messenger.AddError(Messages.MSG_KSPMA_UPDATE_ERROR, ex);
                    else
                        HandleAdminVersionWebResponse(response);
                });
        }
        /// <summary>
        /// Opens a FolderBrowser to select a Download destination. 
        /// Starts a AsyncJob to download the new version.
        /// </summary>
        private static void DownloadNewAdminVersion()
        {
            // get valid download path.
            if (string.IsNullOrEmpty(DownloadPath) || !Directory.Exists(DownloadPath))
                SelectNewDownloadPath();

            if (!string.IsNullOrEmpty(DownloadPath) && Directory.Exists(DownloadPath))
            {
                string filename = View.llblAdminDownload.Text;
                string url = string.Empty;
                if (PlatformHelper.GetPlatform() == Platform.OsX || PlatformHelper.GetPlatform() == Platform.Linux)
                    url = Constants.SERVICE_DOWNLOAD_LINK_MONO;
                else
                    url = Constants.SERVICE_DOWNLOAD_LINK_WIN;

                int index = 1;
                string downloadDest = Path.Combine(DownloadPath, filename);
                while (File.Exists(downloadDest))
                {
                    string temp = Path.GetFileNameWithoutExtension(downloadDest).Replace("_(" + index++ + ")", string.Empty);
                    string newFilename = string.Format("{0}_({1}){2}", temp, index, Path.GetExtension(downloadDest));
                    downloadDest = Path.Combine(Path.GetDirectoryName(downloadDest), newFilename);
                }

                mTaskAction = TaskAction.DownloadApp;
                EventDistributor.InvokeAsyncTaskStarted(Instance);
                AsyncTask<bool>.RunDownload(url, downloadDest,
                                            delegate(bool result, Exception ex)
                                            {
                                                EventDistributor.InvokeAsyncTaskDone(Instance);
                                                
                                                if (ex != null)
                                                    MessageBox.Show(View.ParentForm, ex.Message);
                                                else
                                                {
                                                    switch (PostDownloadAction)
                                                    {
                                                        case PostDownloadAction.Ask:
                                                            if (MessageBox.Show(View.ParentForm, Messages.MSG_DOWNLOAD_COMPLETE_INSTALL, Messages.MSG_DOWNLOAD_COMPLETE, MessageBoxButtons.YesNo) == DialogResult.Yes)
                                                                AutoUpdateKSPMA(downloadDest);
                                                            break;
                                                        case PostDownloadAction.AutoUpdate:
                                                            AutoUpdateKSPMA(downloadDest);
                                                            break;
                                                        default: // case Views.PostDownloadAction.Ignore:
                                                            break;
                                                    }
                                                }
                                            },
                                            delegate(int progressPercentage)
                                            {
                                                View.prgBarAdminDownload.Value = progressPercentage;
                                            });
            }
        }
		public ProcessingBigTaskDialog(string caption, string desc, TaskAction task, object data) : this(DualityEditorApp.MainForm, caption, desc, task, data) {}
        /// <summary>
        /// Starts the steam search for the KSP install folder.
        /// </summary>
        public static void SteamSearch4KSPPath()
        {
            if (View.btnSteamSearch.Tag != null && View.btnSteamSearch.Tag.ToString() == STOP)
            {
                OptionsController.StopSearch4KSPPath();
                return;
            }

            Messenger.AddInfo(Messages.MSG_STEAM_SEARCH_STARTED);

            mStopSearch = false;
            mTaskAction = TaskAction.SteamSearch;
            EventDistributor.InvokeAsyncTaskStarted(Instance);
            AsyncTask<string[]>.DoWork(() =>
            {
                string steamPath = string.Empty;
                if (PlatformHelper.GetPlatform() == Platform.OsX)
                    steamPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), STEAM_PATH_MAC);
                else if (PlatformHelper.GetPlatform() == Platform.Linux)
                    steamPath = Path.Combine(Environment.GetEnvironmentVariable(Constants.HOME), STEAM_PATH_LINUX);
                else
                {
                    steamPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), STEAM_PATH);
                    if (!Directory.Exists(steamPath))
                        steamPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), STEAM_PATH);
                }

                List<string> kspPaths = new List<string>();
                if (!string.IsNullOrEmpty(steamPath) && Directory.Exists(steamPath))
                {
                    string[] dirs = Directory.GetDirectories(steamPath, KSP_SEARCH_PATTERN, SearchOption.TopDirectoryOnly);
                    foreach (string dir in dirs)
                    {
                        if (KSPPathHelper.IsKSPInstallFolder(dir))
                            kspPaths.Add(dir);
                        else
                        {
                            string[] subDirs = Directory.GetDirectories(dir);
                            foreach (string subDir in subDirs)
                            {
                                if (KSPPathHelper.IsKSPInstallFolder(subDir))
                                    kspPaths.Add(subDir);
                            }
                        }
                    }
                }
                else
                    Messenger.AddInfo(Messages.MSG_STEAM_FOLDER_NOT_FOUND);

                return kspPaths.ToArray();
            }, (paths, ex) =>
            {
                EventDistributor.InvokeAsyncTaskDone(Instance);

                if (ex != null)
                {
                    MessageBox.Show(View.ParentForm, ex.Message);
                    Messenger.AddError(Messages.MSG_ERROR_WHILE_STEAM_SEARCH, ex);
                }
                else
                {
                    foreach (string path in paths)
                    {
                        bool stop = false;
                        switch (AskUser(path))
                        {
                            case DialogResult.Yes:
                                TryAddPaths(new[] { path });
                                break;
                            case DialogResult.Cancel:
                                stop = true;
                                break;
                        }
                        if (stop)
                            break;
                    }

                    if (paths.Length > 0)
                        Messenger.AddInfo(Messages.MSG_STEAM_SEARCH_DONE);
                    else
                        Messenger.AddInfo(Messages.MSG_KSP_FOLDER_NOT_FOUND);
                }
            });
        }
Esempio n. 40
0
        public bool IsUserAllowedToDo(int taskId, int userId, TaskAction action)
        {
            bool result = false;
            var task = GetTask(taskId);
            switch (action)
            {
                case TaskAction.Show:
                    result = task.Project.Workspace.Owner.Id == userId ||
                             task.Project.Team.Any(t => t.UserId == userId && t.AccessLevel != AccessLevel.Partial) ||
                             task.ResponsibleId.GetValueOrDefault() == userId;
                    break;

                case TaskAction.Accept:
                    result = task.Project.Team.Any(t => t.UserId == userId && t.AccessLevel != AccessLevel.Partial);
                    break;
                case TaskAction.Start:
                case TaskAction.Complete:
                    result = task.ResponsibleId == userId;
                    break;
                case TaskAction.Delete:
                    result =
                        task.Project.Team.Any(t => t.UserId == userId && t.AccessLevel == AccessLevel.ProjectManager);
                    break;
            }
            return result;
        }
        /// <summary>
        /// Callback function for the AsyncTaskDone event.
        /// Should enable all controls of the BaseView.
        /// </summary>
        protected static void AsyncTaskDone(object sender)
        {
            if (sender == Instance)
            {
                switch (mTaskAction)
                {
                    case TaskAction.AppUpdateCheck:
                        View.gbPaths.Enabled = true;
                        View.btnUpdate.Enabled = true;
                        View.btnUpdate.Text = Messages.MSG_CHECK_FOR_KSPMA_UPDATES;
                        View.btnCheckModUpdates.Enabled = false;
                        View.pbUpdateLoad.Visible = false;
                        View.cbPostDownloadAction.Enabled = true;
                        View.btnCheckModUpdates.Enabled = true;
                        View.llblAdminDownload.Enabled = true;
                        break;
                    case TaskAction.DownloadApp:
                        View.gbPaths.Enabled = true;
                        View.btnUpdate.Enabled = true;
                        View.btnUpdate.Text = Messages.MSG_CHECK_FOR_KSPMA_UPDATES;
                        View.btnCheckModUpdates.Enabled = false;
                        View.pbUpdateLoad.Visible = false;
                        View.cbPostDownloadAction.Enabled = true;
                        View.btnCheckModUpdates.Enabled = true;
                        View.llblAdminDownload.Visible = true;
                        View.prgBarAdminDownload.Visible = false;
                        View.prgBarAdminDownload.Value = 0;
                        break;
                    case TaskAction.ModsUpdateCheck:
                        View.gbPaths.Enabled = true;
                        View.btnUpdate.Enabled = true;
                        View.llblAdminDownload.Enabled = true;
                        View.btnCheckModUpdates.Enabled = true;
                        View.btnCheckModUpdates.Text = Messages.MSG_CHECK_FOR_KSPMA_UPDATES;
                        View.pbUpdateLoad.Visible = false;
                        View.cbPostDownloadAction.Enabled = true;
                        View.cbModUpdateInterval.Enabled = true;
                        View.cbModUpdateBehavior.Enabled = true;
                        View.btnUpdate.Enabled = true;
                        break;
                    case TaskAction.SteamSearch:
                        View.btnUpdate.Enabled = true;
                        View.btnCheckModUpdates.Enabled = true;
                        View.btnOpenDownloads.Enabled = true;
                        View.llblAdminDownload.Visible = true;
                        View.cbKSPPath.Enabled = true;
                        View.btnOpenKSPRoot.Enabled = true;
                        View.btnAddPath.Enabled = true;
                        View.btnRemove.Enabled = true;
                        View.btnSteamSearch.Image = Properties.Resources.folder_tool;
                        View.btnSteamSearch.Tag = START;
                        View.btnKSPFolderSearch.Enabled = true;
                        View.tbDepth.Enabled = true;
                        View.btnDownloadPath.Enabled = true;
                        View.btnOpenDownloadFolder.Enabled = true;
                        View.splitContainer1.Enabled = true;
                        View.tlpSearchBG.Visible = false;
                        break;
                    case TaskAction.FolderSearch:
                        View.btnUpdate.Enabled = true;
                        View.btnCheckModUpdates.Enabled = true;
                        View.btnOpenDownloads.Enabled = true;
                        View.llblAdminDownload.Visible = true;
                        View.cbKSPPath.Enabled = true;
                        View.btnOpenKSPRoot.Enabled = true;
                        View.btnAddPath.Enabled = true;
                        View.btnRemove.Enabled = true;
                        View.btnSteamSearch.Enabled = true;
                        View.btnKSPFolderSearch.Image = Properties.Resources.folder_view;
                        View.btnKSPFolderSearch.Tag = START;
                        View.tbDepth.Enabled = true;
                        View.btnDownloadPath.Enabled = true;
                        View.btnOpenDownloadFolder.Enabled = true;
                        View.splitContainer1.Enabled = true;
                        View.tlpSearchBG.Visible = false;
                        break;
                    default:
                        break;
                }
            }
            else
            {
                View.btnUpdate.Enabled = true;
                View.btnCheckModUpdates.Enabled = true;
                View.btnOpenDownloads.Enabled = true;
                View.llblAdminDownload.Visible = true;
                View.gbPaths.Enabled = true;
            }

            mTaskAction = TaskAction.None;
        }