public TimeLogViewModel(TaskManager TaskManager) { taskMan = TaskManager; SelectedDate = DateTime.Now - new TimeSpan(1, 0, 0, 0); OnExportTimeLog = new RelayCommand(ExecuteExportTimeLog); GotMouseCapture = new RelayCommand<MouseEventArgs>(ExecuteGotMouseCapture); }
public Task( TaskManager taskManager, TaskPriority t_taskPriority ) { setTaskPriority ( t_taskPriority ); // the first signal will go nowhere registerObserver(Event.CHANGE_IN_TASK_PRIORITY, taskManager); taskManager.addTask((int) taskPriority, this); }
public MainWindow() { InitializeComponent(); List<AddressUnit> addressUnits = new List<AddressUnit> { new AddressUnit() {Id = 0, Area = "V", Address = 0, CommunicationTag = "D1", DataType = typeof (ushort), Zoom = 1}, new AddressUnit() {Id = 1, Area = "V", Address = 2, CommunicationTag = "D2", DataType = typeof (float), Zoom = 1} }; TaskManager task = new TaskManager(20, 300, true); task.AddMachine(new SimenseMachine(SimenseType.Tcp, "192.168.3.191",SimenseMachineModel.S7_200, addressUnits, true)); task.ReturnValues += (returnValues) => { value = new List<string>(); if (returnValues.Value != null) { value = from val in returnValues.Value select val.Key + val.Value; simenseItems.Dispatcher.Invoke(() => simenseItems.ItemsSource = value); } else { Console.WriteLine(String.Format("ip {0} not return value", returnValues.Key)); } }; task.TaskStart(); }
protected virtual uint queueTasks(Profile profile, TaskManager task_man) { uint level = 0; foreach (MapLayerLevelOfDetail i in map_layer.getLevels()) { MapLayerLevelOfDetail level_def = i; string s = level.ToString(); FilterEnv cell_env = getSession().createFilterEnv(); cell_env.setExtent(map_layer.getAreaOfInterest()); //GeoExtent.infinite() ); cell_env.setTerrainNode(getTerrainNode()); cell_env.setTerrainSRS(getTerrainSRS()); foreach (Property prop in level_def.getEnvProperties()) cell_env.setProperty(prop); Task task = new CellCompiler(s, s, level_def.getFeatureLayer(), level_def.getFilterGraph(), level_def.getMinRange(), level_def.getMaxRange(), cell_env, null, null, null); task_man.queueTask(task); } return level; }
public void CreateTask_TaskContainsMandatoryProperties_TaskIsFormattedToString() { var taskMgr = new TaskManager(); string testString = "Test"; //Arrange var taskdto = new TaskDTO { CreatedTime = 1234, LastChanged = 1337, NoOfWorkersRequired = 1, SourceSystem = "TaskManagement", TaskRequester = new TaskRequester { Name = "Anders", OrganizationUserId = "Ham Selv!", Phone = "12345678" }, TaskStatus = "UNAS", Type = "PT", UniqueId = new Guid().ToString(), Urgency = "DFLT" }; //Act var createdTask = taskMgr.CreateTask(taskdto); //Assert Assert.IsTrue(ReferenceEquals(createdTask.GetType(), testString.GetType())); }
/// <summary> /// this method show a customerFollowup /// </summary> private void ShowCustomerFollowup() { customerManager = new CustomerManager(this); var customerFollowup = customerManager.GetCustomerFollowup(Company.CompanyId, Convert.ToInt32(Page.ViewState["CustomerFollowupId"])); txtContactId.Value = customerFollowup.ContactId.ToString(); var taskManager = new TaskManager(this); var task = taskManager.GetTask(customerFollowup.CustomerFollowupId, "CustomerFollowUp.aspx"); if (task != null) { ucNextMeetingDate.DateTime = task.StartDate; txtAppoitmentSubject.Text = task.Name; } selContact.ShowContact(customerFollowup.Contact); if (customerFollowup.CustomerFollowupActionId.HasValue) cboCustomerFollowupAction.SelectedValue = customerFollowup.CustomerFollowupActionId.ToString(); txtEntryDate.Text = "Data de Entrada:<br/><b>" + customerFollowup.EntryDate.ToString("dd/MM/yyyy") + "</b>"; txtDescription.Text = customerFollowup.Description; Page.ViewState["CustomerId"] = customerFollowup.CustomerId; Page.ViewState["ContactId"] = customerFollowup.ContactId; }
public GameState(StateManager statemanager) { StateManager = statemanager; TaskManager = new TaskManager(statemanager); HasBeenInited = false; m_eventListeners = new Dictionary<string, EventCallback>(); }
public CharacterProfile() { Settings = new ProfileSettings(); Tasks = new ObservableCollection<BMTask>(); TaskManager = new TaskManager(this); ShoudPause = false; }
static void Main(string[] args) { string msg = ""; Console.WriteLine("Starting Task Manager"); TaskManager taskManager; try { var adressIp = IPAddress.Parse(args[0]); var port = int.Parse(args[1]); taskManager = new TaskManager(adressIp, port); } catch (Exception) { taskManager = new TaskManager("localhost", 12345); } Console.WriteLine("Task Manager created. Start working...\n"); Console.WriteLine("Type 'stop' to stop Task manager.\n"); taskManager.Start(); while (msg != null && msg.ToLower() != "stop") msg = Console.ReadLine(); Console.WriteLine("Task manager's work ended. Closing program."); }
protected static void setConfigFileAtRuntime(string[] args) { string componentToStart; Console.WriteLine("Please specify a component that you want to start:"); Console.WriteLine("1. Server"); Console.WriteLine("2. Task manager"); Console.WriteLine("3. Client"); Console.WriteLine("4. Computational node"); Console.Write("> "); componentToStart = Console.ReadLine(); componentToStart = componentToStart.Replace(" ", string.Empty); componentToStart = componentToStart.Replace(".", string.Empty); UInt16 port = 666; string hostName = Dns.GetHostName(); IPAddress ip = Shared.Connection.ConnectionHelpers.getIPAddressOfTheLocalMachine(); int result = 0; if (Int32.TryParse(componentToStart, out result)) { switch (result) { case 1: componentToStart = "SERVER"; break; case 2: componentToStart = "TASKMANAGER"; break; case 3: componentToStart = "CLIENT"; break; case 4: componentToStart = "COMPUTATIONALNODE"; break; } } switch (componentToStart.ToUpper()) { case "TASKMANAGER": TaskManager newTaskManagerInstance = new TaskManager(); newTaskManagerInstance.startInstance(port, ip); break; case "SERVER": Server newServerInstance = new Server(); newServerInstance.startInstance(port, ip); break; case "CLIENT": ComputationalCluster.Nodes.Client newClientInstance = new ComputationalCluster.Nodes.Client(); newClientInstance.startInstance(port, ip); break; case "COMPUTATIONALNODE": ComputationalNode newComputationalNodeInstance = new ComputationalNode(); newComputationalNodeInstance.startInstance(port, ip); break; } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { tasksManager = new TaskManager(); Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); }
void Start () { temp = new ArrayList(); taskManager = GameObject.Find("TaskManager").GetComponent<TaskManager>(); for(int i = 0; i < initialTasks; i++) { taskManager.AddTask(tasks[i]); counter++; } }
// Use this for initialization void Start () { Player = GameObject.Find("Player"); taskManager = GameObject.Find("Tasks").GetComponent<TaskManager>(); progress.fillAmount = 0; pressButtonNow.gameObject.SetActive (false); StartCoroutine ("StartQuickTime"); }
void Awake() { // If no other MonoBehaviour has requested Instance in an Awake() call executing // before this one, then we are it. There is no reason to search for an object if (_instance == null) { _instance = this as TaskManager; _instance.Initialize(); } }
public static TaskManager Instance() { if (m_Instance == null) { m_Instance = new TaskManager(); } return m_Instance; }
//コンストラクタ public NIDaqCommunicator(Sequences _seq) { seq = _seq; taskManager = TaskManager.GetInstance(); taskManager.addTaskEndEventHandler(TaskEnd); repeatCount = 0; currentRepeatCount = 0; isRepeatEnabled = false; }
static void Main(string[] args) { Console.WriteLine("Press enter to start Task Manager."); Console.ReadLine(); TaskManager tm = new TaskManager("localhost", 49712, 56000); tm.Start(); Console.ReadLine(); tm.Close(); }
public void Task_should_run_if_first_in_queue_and_started() { var unhandledExceptionPolicy = MockRepository.GenerateStub<IUnhandledExceptionPolicy>(); var taskManager = new TaskManager(unhandledExceptionPolicy); var manualResetEvent = new ManualResetEvent(false); taskManager.QueueTask(new DelegateCommand(pm => manualResetEvent.Set())); manualResetEvent.WaitOne(); }
public void TaskRunning_should_return_true_when_a_task_is_running() { var taskManager = new TaskManager(MockRepository.GenerateStub<IUnhandledExceptionPolicy>()); var mre = new ManualResetEvent(false); taskManager.Start(); taskManager.QueueTask(new DelegateCommand(pm => mre.WaitOne())); Assert.AreEqual(true, taskManager.TaskRunning); mre.Set(); }
public void CompleteTask(Int32 companyId, Int32 taskId, Int32 userId) { using (var manager = new TaskManager(null)) { Task originalTask = manager.GetTask(taskId); Task task = originalTask.Duplicate(); task.TaskStatusId = TaskStatus.Concluded; task.CreatorUserId = userId; manager.SaveTask(originalTask, task, null); } }
private void Awake() { _instance = this; taskDBController = this.GetComponent<TaskDBController>(); taskDBController.OnGetTaskDBList += this.OnGetTaskDBList; taskDBController.OnAddTaskDB += this.OnAddTaskDB; taskDBController.OnUpdateTaskDB += this.OnUpdateTaskDB; InitTask(); taskDBController.GetTaskDBList(); }
public void Should_stop_all_controllers() { var taskBag = MockRepository.GenerateMock<ITaskBag>(); var taskManager = new TaskManager(log, configController, path, stop, sleeper, 1); taskManager.TaskBag = taskBag; taskBag.Expect(x => x.Stop()); //Test taskManager.Stop(); //Assert taskBag.VerifyAllExpectations(); }
public Core() { var log = new ThreadSafeLog(SlaveCore.Properties.Settings.Default.MaxLogCount); this.pluginManager = new PluginManager(WcfService.Instance, log); this.taskManager = new TaskManager(pluginManager, log); log.MessageAdded += new EventHandler<EventArgs<string>>(log_MessageAdded); RegisterTaskManagerEvents(); this.configManager = new ConfigManager(taskManager); ConfigManager.Instance = this.configManager; }
// defaults to a real-time task -- now what happens when both this and Global are first put in queue ?? public GridNavigationTask(State t_startState, State t_goalState, float t_inflationFactor, ref List<State> t_path, float t_tunnelDistanceThreshold, float t_tunnelTimeThreshold, ref List<State> t_spaceTimePath, GridTimeDomain t_gridTimeDomain, TaskPriority t_taskPriority, TaskManager taskManager) : base(taskManager, t_taskPriority) { taskType = TaskType.GridNavigationTask; startState = t_startState; goalState = t_goalState; // EVENT : startState will trigger GridNavigationTask that STATE_CHANGED startState.registerObserver(Event.STATE_POSITION_CHANGED, this); // EVENT : goalState will trigger GridNavigationTask that STATE_CHANGED goalState.registerObserver(Event.STATE_POSITION_CHANGED, this); // EVENT : goalState will trigger GridNavigationTask that it is GOAL_INVALID or VALID goalState.registerObserver(Event.GOAL_INVALID, this); goalState.registerObserver(Event.GOAL_VALID, this); inflationFactor = t_inflationFactor; //planner = t_planner; outputPlan = new Dictionary<DefaultState, ARAstarNode>(); path = t_path; // TODO : deprecate these lists List<PlanningDomainBase> domainList = new List<PlanningDomainBase>(); ARAstarDomain araStarDomain = new ARAstarDomain (); araStarDomain.setPlanningTask(this); domainList.Add(araStarDomain); gridPlanner = new ARAstarPlanner(); gridPlanner.init(ref domainList, 100); initialized = true; obstacleChanged = false; obstacleChangedData = new List<object> (); // tunnel planner variables tunnelDistanceThreshold = t_tunnelDistanceThreshold; tunnelTimeThreshold = t_tunnelTimeThreshold; gridTimeDomain = t_gridTimeDomain; spaceTimePath = t_spaceTimePath; spaceTimePathStatus = false; dynamicChange = false; currentlyExecutingTask = false; gridPathStatus = PathStatus.NoPath; }
private void btn_savaSchedule_Click(object sender, EventArgs e) { Properties.Settings.Default.BreakTime = int.Parse(cb_restTime.Text.ToString()); Properties.Settings.Default.Interval = int.Parse(cb_interval.Text); Properties.Settings.Default.Save(); TaskManager Resettask = new TaskManager(); if (Properties.Settings.Default.AutoStart) Resettask.AutoRun(); else Resettask.ScheduleRun(); }
/// <summary> /// 初始化核心 /// </summary> public static void Initialize() { StartupPath = System.Environment.CurrentDirectory; LogManager = new LogManager(); ConfigManager = new ConfigManager(); ConfigManager.LoadSettings(); PluginManager = new PluginManager(); TaskManager = new TaskManager(); TaskManager.LoadAllTasks(); //XmlConfigurator.Configure(new FileInfo(Path.Combine(StartupPath, "LogConfig.xml"))); }
public static void DeleteCustomerFollowup(int customerFollowupId) { using (CustomerManager customerManager = new CustomerManager(null)) { var taskManager = new TaskManager(null); var task = taskManager.GetTask(customerFollowupId, "CustomerFollowUp.aspx"); if (task != null) taskManager.DeleteTask(task); customerManager.DeleteCustomerFollowup(customerManager.GetCustomerFollowup(customerFollowupId)); } }
public void TestTaskManagerOrderByTaskTarget() { TaskManager taskManager = new TaskManager(ChaosTheoryEnum.OrderByTaskDelegateTarget); taskManager.Execute<int, string, bool>(TaskGeneric, TaskGenericFinished, 1, "2"); taskManager.Execute<int, string, bool>(TaskGenericException, TaskGenericExceptionFinished, 1, "2"); taskManager.Execute<int, string>(TaskNonGeneric, TaskNonGenericFinished, 1, "2"); taskManager.Execute<int, string>(TaskNonGenericException, TaskNonGenericExceptionFinished, 1, "2"); mTestResult1.WaitOne(); mTestResult2.WaitOne(); mTestResult3.WaitOne(); mTestResult4.WaitOne(); }
public override void ViewDidLoad() { base.ViewDidLoad(); Label.Text = "Waiting..."; ActivityIndicator.StartAnimating(); var taskMan = new TaskManager(); var task = taskMan.GenerateText(); task.ContinueWith((t) => InvokeOnMainThread(() => { ActivityIndicator.StopAnimating(); Label.Text = t.IsCanceled ? "Canceled" : t.Result; })); CancelButton.TouchUpInside += (sender, e) => taskMan.Cancel(); }
static int Main(string[] args) { _manager = new TaskManager(Console.Out); var result = Parser.Default.ParseArguments<ListOptions, AddOrUpdateOptions, DeleteOptions, ShowUIOptions>(args); return result.MapResult( RunOptions(), RunAddOptions(), RunDeleteOptions(), RunShowUIOptions(), errs => 0); }
private StreamThread(string threadId, string clientId, TaskManager manager, IConsumer <byte[], byte[]> consumer, InternalTopologyBuilder builder, IStreamConfig configuration) : this(threadId, clientId, manager, consumer, builder, TimeSpan.FromMilliseconds(configuration.PollMs), configuration.CommitIntervalMs) { streamConfig = configuration; }
protected void InitializeTaskManager() { TaskManager = new TaskManager(); SyncContext = new ThreadSynchronizationContext(TaskManager.Token); TaskManager.UIScheduler = new SynchronizationContextTaskScheduler(SyncContext); }
public ActionResult ViewClient(string sessionid, string Clientid) { objResponse Response = new objResponse(); ClientModel model = new ClientModel(); session = new SessionHelper(); EventManager objEventManager = new EventManager(); TaskManager objTaskManager = new TaskManager(); DocumentManager objDocManager = new DocumentManager(); NoteManager objNoteManager = new NoteManager(); UserManager objUserManager = new UserManager(); List <Users> UserList = new List <Users>(); UserList = objUserManager.GetUsers(session.UserSession.PIN); try { Response = objClientsManager.ViewClients(Convert.ToInt64(Clientid)); if (Response.ErrorCode == 0) { model.Client_ID = Convert.ToInt64(Response.ResponseData.Tables[0].Rows[0]["Client_ID_Auto_PK"]); model.Date = Response.ResponseData.Tables[0].Rows[0]["Date"].ToString(); model.Name = Response.ResponseData.Tables[0].Rows[0]["Name"].ToString(); model.CompanyName = Response.ResponseData.Tables[0].Rows[0]["CompanyName"].ToString(); model.Email = Response.ResponseData.Tables[0].Rows[0]["Email"].ToString(); model.Alternate_Email = Response.ResponseData.Tables[0].Rows[0]["Alternate_Email"].ToString(); model.ContactNo = Response.ResponseData.Tables[0].Rows[0]["ContactNo"].ToString(); model.SkypeNo = Response.ResponseData.Tables[0].Rows[0]["SkypeNo"].ToString();; model.AddressLine1 = Response.ResponseData.Tables[0].Rows[0]["AddressLine1"].ToString(); model.AddressLine2 = Response.ResponseData.Tables[0].Rows[0]["AddressLine2"].ToString(); model.City = Response.ResponseData.Tables[0].Rows[0]["City"].ToString();; model.State = Response.ResponseData.Tables[0].Rows[0]["State"].ToString(); model.Country = Response.ResponseData.Tables[0].Rows[0]["Country"].ToString(); model.ZipCode = Response.ResponseData.Tables[0].Rows[0]["Zipcode"].ToString(); model.Client_Owner_Name = Response.ResponseData.Tables[0].Rows[0]["Owner"].ToString(); model.Source = Response.ResponseData.Tables[0].Rows[0]["Source"].ToString(); model.JobDescription = Response.ResponseData.Tables[0].Rows[0]["JobDescription"].ToString(); model.Events = objEventManager.getEventsByRelateToID(Convert.ToInt64(session.UserSession.PIN), session.UserSession.UserId, Convert.ToInt64(Clientid), "CLIENT"); model.activities = UtilityManager.getActivityByRelateToID(Convert.ToInt64(session.UserSession.PIN), Convert.ToInt64(Clientid), "CLIENT"); model.tasks = objTaskManager.getTasksByRelateToID(Convert.ToInt64(session.UserSession.PIN), Convert.ToInt64(Clientid), session.UserSession.UserId, "CLIENT"); model.Doc = objDocManager.getDocsRelatedToID(Convert.ToInt64(session.UserSession.PIN), Convert.ToInt64(Clientid), "CLIENT", session.UserSession.UserId); model.notes = objNoteManager.getNotesByRelateToID(Convert.ToInt64(session.UserSession.PIN), Convert.ToInt64(Clientid), session.UserSession.UserId, "CLIENT"); ViewBag.Users = UserList; return(View(model)); } else { ViewBag.Users = UserList; ViewBag.Error_Msg = "There is error in Fetching Client Details"; return(View(model)); } } catch (Exception ex) { ViewBag.Users = UserList; ViewBag.Error_Msg = ex.Message.ToString();; BAL.Common.LogManager.LogError("ViewClient Contro", 1, Convert.ToString(ex.Source), Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace)); return(View(model)); } }
public void CheckForSubtitlesNow() { TaskManager.AntecipateTask <CheckForVideosJob>(true); }
/// <summary> /// Stops the window service /// </summary> void IService.OnStop() { TaskManager.Stop(); }
public ActionResult RefreshNavigation() { TaskManager = (TaskManager)Session["TaskManager"]; return(PartialView("_uploadWizardNav", TaskManager)); }
public ActionResult RefreshTaskList() { TaskManager = (TaskManager)Session["TaskManager"]; return(PartialView("_taskListView", TaskManager.GetStatusOfStepInfos())); }
private void button2_Click(object sender, EventArgs e) { TaskManager.AddTask(Task2()); TaskManager.RunTasks(); }
public static async Task OnExit() { Logger.Log("Shutting down..."); if (ModuleLoader != null) { await ModuleLoader.ExecuteAsyncEvent(Enums.AsyncModuleContext.AssistantShutdown).ConfigureAwait(false); } if (TaskManager != null) { TaskManager.OnCoreShutdownRequested(); } if (Update != null) { Update.StopUpdateTimer(); Logger.Log("Update timer disposed!", Enums.LogLevels.Trace); } if (RefreshConsoleTitleTimer != null) { RefreshConsoleTitleTimer.Dispose(); Logger.Log("Console title refresh timer disposed!", Enums.LogLevels.Trace); } if (ConfigWatcher != null && ConfigWatcher.ConfigWatcherOnline) { ConfigWatcher.StopConfigWatcher(); } if (ModuleWatcher != null && ModuleWatcher.ModuleWatcherOnline) { ModuleWatcher.StopModuleWatcher(); } if (AssistantStatus != null) { AssistantStatus.Dispose(); } if (KestrelServer.IsServerOnline) { await KestrelServer.Stop().ConfigureAwait(false); } if (ModuleLoader != null) { ModuleLoader.OnCoreShutdown(); } if (Controller != null) { Controller.InitGpioShutdownTasks(); } if (Config != null) { Config.ProgramLastShutdown = DateTime.Now; Config.SaveConfig(Config); } Logger.Log("Finished on exit tasks.", Enums.LogLevels.Trace); }
internal WurmCharacterLogFiles([NotNull] CharacterName characterName, [NotNull] string fullDirPathToCharacterLogsDir, [NotNull] IWurmApiLogger logger, [NotNull] LogFileInfoFactory logFileInfoFactory, [NotNull] IInternalEventInvoker internalEventInvoker, [NotNull] TaskManager taskManager) { if (characterName == null) { throw new ArgumentNullException(nameof(characterName)); } if (fullDirPathToCharacterLogsDir == null) { throw new ArgumentNullException(nameof(fullDirPathToCharacterLogsDir)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } if (logFileInfoFactory == null) { throw new ArgumentNullException(nameof(logFileInfoFactory)); } if (internalEventInvoker == null) { throw new ArgumentNullException(nameof(internalEventInvoker)); } if (taskManager == null) { throw new ArgumentNullException(nameof(taskManager)); } this.logger = logger; this.logFileInfoFactory = logFileInfoFactory; this.taskManager = taskManager; CharacterName = characterName; FullDirPathToCharacterLogsDir = fullDirPathToCharacterLogsDir; onFilesAddedOrRemoved = internalEventInvoker.Create(() => new CharacterLogFilesAddedOrRemoved(CharacterName)); try { Refresh(); } catch (Exception exception) { logger.Log(LogLevel.Error, "Error at initial WurmCharacterLogFiles refresh: " + CharacterName, this, exception); } directoryWatcher = new FileSystemWatcher(fullDirPathToCharacterLogsDir) { Filter = "*.txt", NotifyFilter = NotifyFilters.FileName }; directoryWatcher.Created += DirectoryWatcherOnChanged; directoryWatcher.Deleted += DirectoryWatcherOnChanged; directoryWatcher.Renamed += DirectoryWatcherOnChanged; directoryWatcher.Changed += DirectoryWatcherOnChanged; directoryWatcher.EnableRaisingEvents = true; taskHandle = new TaskHandle(Refresh, "WurmCharacterLogFiles refresh: " + CharacterName); taskManager.Add(taskHandle); taskHandle.Trigger(); }
// Start is called before the first frame update void Start() { _taskManager = FindObjectOfType <TaskManager>(); _player = FindObjectOfType <PlayerController>(); _rigidbody = GetComponent <Rigidbody2D>(); }
protected void Page_Load(object sender, EventArgs e) { TaskManager TM = new TaskManager(); listtask = TM.GetList(); }
public static ResultObject DeleteBlackBerryUser(int itemId, int accountId) { ResultObject res = TaskManager.StartResultTask <ResultObject>("BLACKBERRY", "DELETE_BLACKBERRY_USER"); BlackBerry blackBerry; try { blackBerry = GetBlackBerryProxy(itemId); } catch (Exception ex) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_BLACKBERRY_PROXY, ex); return(res); } OrganizationUser user; try { user = OrganizationController.GetAccount(itemId, accountId); if (user == null) { throw new ApplicationException( string.Format("User is null. ItemId={0}, AccountId={1}", itemId, accountId)); } } catch (Exception ex) { TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT, ex); return(res); } try { ResultObject bbRes = blackBerry.DeleteBlackBerryUser(user.PrimaryEmailAddress); res.ErrorCodes.AddRange(bbRes.ErrorCodes); if (!bbRes.IsSuccess) { TaskManager.CompleteResultTask(res); return(res); } } catch (Exception ex) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_DELETE_BLACKBERRY_USER, ex); return(res); } try { DataProvider.DeleteBlackBerryUser(accountId); } catch (Exception ex) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_DELETE_BLACKBERRY_USER_FROM_METADATA, ex); return(res); } TaskManager.CompleteResultTask(); return(res); }
public ShoppingOriginRebateResult(TaskContext context) { Context = context; _taskManager = Context.HttpContextAccessor.HttpContext.RequestServices.GetService <TaskManager>(); }
protected void Application_Start() { try { Action <long, string> logger = (ms, name) => { $"{nameof(Application_Start)}|耗时:{ms}毫秒".AddBusinessInfoLog(); }; using (var timer = new CpuTimeLogger(logger)) { /* * if (!("config_1.json", "config_2.json").SameJsonStructure()) * { * throw new Exception("正式机和测试机配置文件结构不相同"); * }*/ //添加依赖注入 AppContext.AddExtraRegistrar(new CommonDependencyRegister()); AppContext.AddExtraRegistrar(new FullDependencyRegistrar()); AppContext.OnContainerBuilding = (ref ContainerBuilder builder) => { //sso //builder.Register(_ => new LoginStatus("auth_sso_uid", "auth_sso_token", "auth_sso_session", "")).Named<LoginStatus>("sso").SingleInstance(); //builder.RegisterType<SSOValidationProvider>().Named<TokenValidationProviderBase>("sso").SingleInstance(); builder.UseAccountSystem <QPLUserLoginService>(); //builder.AuthUseAuthServerValidation(() => new AuthServerConfig() { }); builder.AuthUseLoginStatus(() => new LoginStatus($"auth_user_uid", $"auth_user_token", $"auth_user_session")); builder.AuthUseValidationDataProvider <AppOrWebAuthDataProvider>(); builder.AuthClientUseCustomValidation <AuthBasicValidationProvider>(); //auth 功能逻辑 builder.AuthUseServerApiAccessService <AuthApiServiceFromDB_>(); }; //disable "X-AspNetMvc-Version" header name MvcHandler.DisableMvcResponseHeader = true; AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); //用AutoFac接管控制器生成,从而实现依赖注入 //ControllerBuilder.Current.SetControllerFactory(typeof(AutoFacControllerFactory)); //使用autofac生成控制器 DependencyResolver.SetResolver(AppContext.Container.AutofacDependencyResolver_()); try { //断网的情况下这里不会抛异常,会长时间等待 Policy.Timeout(TimeSpan.FromSeconds(6), TimeoutStrategy.Pessimistic).Execute(() => { //加速首次启动EF //EFManager.SelectDB(null).FastStart(); EFManager.FastStart <EntityDB>(); //汽配龙数据库 EFManager.FastStart <QPLEntityDB>(); //SSO数据库 EFManager.FastStart <SSODB>(); }); } catch (Exception err) { throw new Exception("设置EF快速启动失败", err); } #if DEBUG //安装数据库 this.InstallDatabase(); #endif //启动后台服务 TaskManager.StartAllTasks(new Assembly[] { typeof(CleanDatabaseTask).Assembly }); } } catch (Exception e) { e.AddErrorLog("网站启动异常"); throw e; } }
public bool SaveData() { if (!ValidateData()) { return(false); } var settings = new TaskSqlSettings(); var item = new TaskSqlSetting(); //html item.Enabled = chbEnabledHtml.Checked; item.JobType = typeof(GenerateHtmlMapJob).ToString(); item.TimeInterval = txtTimeIntervalHtml.Text.TryParseInt(); item.TimeType = (TimeIntervalType)Enum.Parse(typeof(TimeIntervalType), ddlTypeHtml.SelectedValue, true); if (item.TimeType == TimeIntervalType.Days) { item.TimeHours = txtHoursHtml.Text.TryParseInt(); item.TimeMinutes = txtMinutesHtml.Text.TryParseInt(); } settings.Add(item); //xml item = new TaskSqlSetting(); item.Enabled = chbEnabledXml.Checked; item.JobType = typeof(GenerateXmlMapJob).ToString(); item.TimeInterval = txtTimeIntervalXml.Text.TryParseInt(); item.TimeType = (TimeIntervalType)Enum.Parse(typeof(TimeIntervalType), ddlTypeXml.SelectedValue, true); if (item.TimeType == TimeIntervalType.Days) { item.TimeHours = txtHoursXml.Text.TryParseInt(); item.TimeMinutes = txtMinutesXml.Text.TryParseInt(); } settings.Add(item); //yandex item = new TaskSqlSetting(); item.Enabled = chbEnabledYandex.Checked & ShowYaMarket; item.JobType = typeof(GenerateYandexMarketJob).ToString(); item.TimeInterval = txtTimeIntervalYandex.Text.TryParseInt(); item.TimeType = (TimeIntervalType)Enum.Parse(typeof(TimeIntervalType), ddlTypeYandex.SelectedValue, true); if (item.TimeType == TimeIntervalType.Days) { item.TimeHours = txtHoursYandex.Text.TryParseInt(); item.TimeMinutes = txtMinutesYandex.Text.TryParseInt(); } settings.Add(item); //Added by Evgeni. Amount update item = new TaskSqlSetting(); item.Enabled = chbEnableAmountUpdate.Checked; item.JobType = typeof(GenerateNesProductAmountUpdateJob).ToString(); item.TimeInterval = txtTimeIntervalAmountUpdate.Text.TryParseInt(); item.TimeType = (TimeIntervalType)Enum.Parse(typeof(TimeIntervalType), ddlTypeAmountUpdate.SelectedValue, true); if (item.TimeType == TimeIntervalType.Days) { item.TimeHours = txtHoursAmountUpdate.Text.TryParseInt(); item.TimeMinutes = txtMinutesAmountUpdate.Text.TryParseInt(); } settings.Add(item); /// TaskSqlSettings.TaskSettings = settings; TaskManager.TaskManagerInstance().ManagedTask(settings); LoadData(); return(true); }
private void EndDownloadFile(DownloadFile_v1 <TKey> downloadFile) { try { DownloadedFile_v1 <TKey> downloadedFile = new DownloadedFile_v1 <TKey> { key = downloadFile.key, downloadLinks = downloadFile.downloadLinks, downloadLink = downloadFile.downloadLink, file = downloadFile.file, state = downloadFile.state, requestTime = downloadFile.requestTime, startDownloadTime = downloadFile.startDownloadTime, endDownloadTime = DateTime.Now, downloadDuration = DateTime.Now - downloadFile.startDownloadTime }; string downloadedPath = _downloadClient.GetDownloadLocalFileById(downloadFile.downloadId); string downloadDirectory = zPath.GetDirectoryName(downloadFile.file); //if (_trace) //{ // pb.Trace.WriteLine("ManageEndDownloadFiles() : downloadFile.file : \"{0}\"", downloadFile.file); // pb.Trace.WriteLine("ManageEndDownloadFiles() : _downloadClient.GetDownloadLocalFileById() : \"{0}\"", downloadedPath); //} downloadedFile.downloadedFile = zpath.PathSetDirectory(downloadedPath, downloadDirectory); downloadedFile.id = _mongoDownloadedFileManager.GetNewId(); _mongoDownloadedFileManager.Save(downloadedFile.id, downloadedFile); _mongoQueueDownloadFileManager.Remove(downloadFile.id); _downloadClient.RemoveDownloadById(downloadFile.downloadId); // _uncompressFile if (downloadFile.state == DownloadState.DownloadCompleted && _uncompressManager != null && CompressManager.IsCompressFile(downloadedPath)) { TaskManager.AddTask(new Task { name = "Uncompress download file", task = () => { UncompressFile(downloadedPath, downloadedFile, downloadDirectory); _mongoDownloadedFileManager.Save(downloadedFile.id, downloadedFile); } }); if (_onDownloaded != null) { TaskManager.AddTask(new Task { name = "onDownloaded", task = () => _onDownloaded(downloadedFile) }); } } else if (_onDownloaded != null) { _onDownloaded(downloadedFile); } DownloadFile_v1 <TKey> downloadFile2; if (!_downloadFiles.TryRemove(downloadFile.id, out downloadFile2)) { pb.Trace.WriteLine("error unable to remove downloadFile with id {0} from ConcurrentDictionary _downloadFiles (DownloadManager<TKey>.ManageEndDownloadFiles())", downloadFile.id); } } catch (Exception exception) { pb.Trace.WriteLine("error in DownloadManager_v1.EndDownloadFile() : {0}", exception.Message); pb.Trace.WriteLine(exception.StackTrace); } }
public void DeleteTaskRow(int rowId) { TaskManager.DeleteTask(tasks[rowId].ID); }
private bool GetAllListPageUrl(IListSheet listSheet) { string exportDir = this.RunPage.GetExportDir(); string pageSourceDir = this.RunPage.GetDetailSourceFileDir(); string[] resultColumns = new string[] { "detailPageUrl", "detailPageName", "cookie", "grabStatus", "giveUpGrab", "fullCategoryName", "category1Code", "category2Code", "category3Code", "category1Name", "category2Name", "category3Name", "district" }; Dictionary <string, int> resultColumnDic = CommonUtil.InitStringIndexDic(resultColumns); string resultFilePath = Path.Combine(exportDir, this.RunPage.Project.Name + "_AllListPageUrl.xlsx"); ExcelWriter resultEW = new ExcelWriter(resultFilePath, "List", resultColumnDic, null); string detailPageUrlColumnName = SysConfig.DetailPageUrlFieldName; string categoryNameColumnName = SysConfig.DetailPageNameFieldName; for (int i = 0; i < listSheet.RowCount; i++) { Dictionary <string, string> row = listSheet.GetRow(i); bool giveUp = "Y".Equals(row[SysConfig.GiveUpGrabFieldName]); if (!giveUp) { string fullCategoryName = row[categoryNameColumnName]; string url = row[detailPageUrlColumnName]; string category1Code = row["category1Code"]; string category2Code = row["category2Code"]; string category3Code = row["category3Code"]; string category1Name = row["category1Name"]; string category2Name = row["category2Name"]; string category3Name = row["category3Name"]; string detailPageUrlPrefix = "http://www.yummy77.com"; string localFilePath = this.RunPage.GetFilePath(url, pageSourceDir); TextReader tr = null; try { tr = new StreamReader(localFilePath); string webPageHtml = tr.ReadToEnd(); HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument(); htmlDoc.LoadHtml(webPageHtml); HtmlNode pageNode = htmlDoc.DocumentNode.SelectSingleNode("//div[@class=\"smallpage\"]"); int pageCount = 1; if (pageNode != null) { string pageCountStr = pageNode.ChildNodes[2].InnerText.Trim().Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[1]; pageCount = int.Parse(pageCountStr); } for (int j = 0; j < pageCount; j++) { string pageIndexStr = (j + 1).ToString(); string detailPageName = fullCategoryName + "_" + pageIndexStr; string detailPageUrl = detailPageUrlPrefix + "/category/" + pageIndexStr + "-" + category1Code + "-" + category2Code + "-" + category3Code + "-5-p-.html"; Dictionary <string, string> f2vs = new Dictionary <string, string>(); f2vs.Add("detailPageUrl", detailPageUrl); f2vs.Add("detailPageName", detailPageName); f2vs.Add("fullCategoryName", fullCategoryName); f2vs.Add("category1Code", category1Code); f2vs.Add("category2Code", category2Code); f2vs.Add("category3Code", category3Code); f2vs.Add("category1Name", category1Name); f2vs.Add("category2Name", category2Name); f2vs.Add("category3Name", category3Name); resultEW.AddRow(f2vs); } } catch (Exception ex) { if (tr != null) { tr.Dispose(); tr = null; } this.RunPage.InvokeAppendLogText("读取出错. " + ex.Message + " LocalPath = " + localFilePath, LogLevelType.Error, true); throw ex; } } } resultEW.SaveToDisk(); //执行后续任务 TaskManager.StartTask("易果", "美味77获取所有列表页", resultFilePath, null, null, false); return(true); }
public async Task ShouldAddAndCommitFiles() { await Initialize(TestRepoMasterCleanSynchronized); var repositoryManagerListener = Substitute.For <IRepositoryManagerListener>(); repositoryManagerListener.AttachListener(RepositoryManager, repositoryManagerEvents); var expectedAfterChanges = new GitStatus { Behind = 1, LocalBranch = "master", RemoteBranch = "origin/master", Entries = new List <GitStatusEntry> { new GitStatusEntry("Assets\\TestDocument.txt", TestRepoMasterCleanSynchronized.Combine("Assets", "TestDocument.txt"), "Assets\\TestDocument.txt", GitFileStatus.Modified), new GitStatusEntry("foobar.txt", TestRepoMasterCleanSynchronized.Combine("foobar.txt"), "foobar.txt", GitFileStatus.Untracked) } }; var result = new GitStatus(); RepositoryManager.OnStatusUpdated += status => { result = status; }; var foobarTxt = TestRepoMasterCleanSynchronized.Combine("foobar.txt"); foobarTxt.WriteAllText("foobar"); var testDocumentTxt = TestRepoMasterCleanSynchronized.Combine("Assets", "TestDocument.txt"); testDocumentTxt.WriteAllText("foobar"); await TaskManager.Wait(); RepositoryManager.WaitForEvents(); WaitForNotBusy(repositoryManagerEvents, 1); repositoryManagerListener.Received().OnStatusUpdate(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnActiveBranchChanged(Arg.Any <ConfigBranch?>()); repositoryManagerListener.DidNotReceive().OnActiveRemoteChanged(Arg.Any <ConfigRemote?>()); repositoryManagerListener.DidNotReceive().OnLocalBranchListChanged(); repositoryManagerListener.DidNotReceive().OnRemoteBranchListChanged(); repositoryManagerListener.ReceivedWithAnyArgs().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); result.AssertEqual(expectedAfterChanges); repositoryManagerListener.ClearReceivedCalls(); repositoryManagerEvents.Reset(); await RepositoryManager .CommitFiles(new List <string>() { "Assets\\TestDocument.txt", "foobar.txt" }, "IntegrationTest Commit", string.Empty) .StartAsAsync(); await TaskManager.Wait(); RepositoryManager.WaitForEvents(); WaitForNotBusy(repositoryManagerEvents, 1); repositoryManagerEvents.OnStatusUpdate.WaitOne(TimeSpan.FromSeconds(1)); repositoryManagerListener.Received().OnStatusUpdate(Args.GitStatus); repositoryManagerListener.DidNotReceive().OnActiveBranchChanged(Arg.Any <ConfigBranch?>()); repositoryManagerListener.DidNotReceive().OnActiveRemoteChanged(Arg.Any <ConfigRemote?>()); repositoryManagerListener.DidNotReceive().OnLocalBranchListChanged(); repositoryManagerListener.DidNotReceive().OnRemoteBranchListChanged(); repositoryManagerListener.Received().OnIsBusyChanged(Args.Bool); repositoryManagerListener.DidNotReceive().OnLocksUpdated(Args.EnumerableGitLock); }
private void Awake() { Instance = this; }
/// <summary> /// 创建撤销处理运行时 /// </summary> /// <param name="runner">撤销人</param> /// <param name="result">创建结果</param> /// <returns>运行时管理器</returns> internal static WfRuntimeManager CreateRuntimeInstanceWithdraw(WfAppRunner runner, ref WfExecutedResult result) { var rmins = new WfRuntimeManagerSendBack(); rmins.WfExecutedResult = result = new WfExecutedResult(); if (runner.TaskID == null) { result.Status = WfExecutedStatus.Exception; result.ExceptionType = WfExceptionType.Withdraw_ErrorArguments; result.Message = LocalizeHelper.GetEngineMessage("wfruntimemanagerfactory.CreateRuntimeInstanceWithdraw.missingtaskid.error"); return(rmins); } //获取已经完成任务的信息 var tm = new TaskManager(); var taskDone = tm.GetTaskView(runner.TaskID.Value); if (tm.IsMine(taskDone, runner.UserID) == false) { result.Status = WfExecutedStatus.Exception; result.ExceptionType = WfExceptionType.Sendback_NotMineTask; result.Message = LocalizeHelper.GetEngineMessage("wfruntimemanagerfactory.CreateRuntimeInstanceWithdraw.nonetask.error"); return(rmins); } //赋值下一步办理列表 runner.NextActivityPerformers = NextStepUtility.CreateNextStepPerformerList(taskDone.ActivityGUID, taskDone.AssignedToUserID, taskDone.AssignedToUserName); //没有指定退回节点信息 if (runner.NextActivityPerformers == null || runner.NextActivityPerformers.Count == 0) { result.Status = WfExecutedStatus.Exception; result.ExceptionType = WfExceptionType.Sendback_IsNull; result.Message = LocalizeHelper.GetEngineMessage("wfruntimemanagerfactory.CreateRuntimeInstanceWithdraw.noneperformer.error"); return(rmins); } //获取待办任务 var tim = new TransitionInstanceManager(); var nextStepList = tim.GetTargetActivityInstanceList(taskDone.ActivityInstanceID).ToList(); ActivityInstanceEntity runningNode = nextStepList.Count > 0 ? nextStepList[0] : null; if (runningNode == null) { result.Status = WfExecutedStatus.Exception; result.ExceptionType = WfExceptionType.Sendback_NotInRunning; result.Message = LocalizeHelper.GetEngineMessage("wfruntimemanagerfactory.CreateRuntimeInstanceWithdraw.nonerun.error"); return(rmins); } var activityType = EnumHelper.ParseEnum <ActivityTypeEnum>(runningNode.ActivityType.ToString()); if (XPDLHelper.IsSimpleComponentNode(activityType) == false) { result.Status = WfExecutedStatus.Exception; result.ExceptionType = WfExceptionType.Sendback_NotTaskNode; result.Message = LocalizeHelper.GetEngineMessage("wfruntimemanagerfactory.CreateRuntimeInstanceWithdraw.nottask.error"); return(rmins); } //获取待办任务(模拟待办任务用户做退回处理) var taskToDo = tm.GetTaskViewByActivity(runningNode.ProcessInstanceID, runningNode.ID); runner.UserID = taskToDo.AssignedToUserID; runner.UserName = taskToDo.AssignedToUserName; //获取上一步节点信息 var hasGatewayPassed = false; var processInstance = (new ProcessInstanceManager()).GetById(runningNode.ProcessInstanceID); var previousStepChecker = new PreviousStepChecker(); var processModel = ProcessModelFactory.Create(taskToDo.ProcessGUID, taskToDo.Version); var previousActivityList = previousStepChecker.GetPreviousActivityList(runningNode, processModel, out hasGatewayPassed); //判断退回是否有效 if (previousActivityList == null || previousActivityList.Count == 0) { result.Status = WfExecutedStatus.Exception; result.ExceptionType = WfExceptionType.Sendback_IsNull; result.Message = LocalizeHelper.GetEngineMessage("wfruntimemanagerfactory.CreateRuntimeInstanceWithdraw.empty.error"); return(rmins); } //检查节点是否一致 if (previousActivityList.Count == 1) { var onlyActivityGUID = previousActivityList[0].ActivityGUID; var isOnly = true; foreach (var step in runner.NextActivityPerformers) { if (step.Key != onlyActivityGUID) { isOnly = false; break; } } //存在不一致的退回节点 if (isOnly == false) { result.Status = WfExecutedStatus.Exception; result.ExceptionType = WfExceptionType.Sendback_IsTooManyPrevious; result.Message = LocalizeHelper.GetEngineMessage("wfruntimemanagerfactory.CreateRuntimeInstanceWithdraw.notunique.error"); return(rmins); } } //创建运行时 rmins.TaskView = taskToDo; rmins.RunningActivityInstance = runningNode; rmins.ProcessInstanceID = runningNode.ProcessInstanceID; rmins.ProcessInstance = processInstance; rmins.ProcessModel = processModel; rmins.AppRunner.AppName = runner.AppName; rmins.AppRunner.AppInstanceID = runner.AppInstanceID; rmins.AppRunner.UserID = runner.UserID; rmins.AppRunner.UserName = runner.UserName; rmins.AppRunner.NextActivityPerformers = runner.NextActivityPerformers; //设置退回选项类 var sendbackOperation = new SendBackOperation(); sendbackOperation.BackwardType = BackwardTypeEnum.Withdrawed; sendbackOperation.ProcessInstance = processInstance; sendbackOperation.BackwardFromActivityInstance = runningNode; sendbackOperation.HasGatewayPassed = hasGatewayPassed; sendbackOperation.ActivityResource = new ActivityResource(runner, rmins.AppRunner.NextActivityPerformers); sendbackOperation.ProcessModel = processModel; sendbackOperation.IsCancellingBrothersNode = true; //撤销时默认撤销各个并行分支 rmins.SendBackOperation = sendbackOperation; return(rmins); }
public void StartThread() { TaskManager.StartTaskManager(); base.Start(); }
public SharesValueChangeResult(TaskContext context) { Context = context; _taskManager = Context.HttpContextAccessor.HttpContext.RequestServices.GetService <TaskManager>(); }
private async void CheckWorker_DoWork(object sender, DoWorkEventArgs e) { this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { //Добавляем задачу обновления TaskManager.AquireLock(UpdateTask); ProfileManager.OnProfileLocked(true); EnvironmentManager.OnFileSystemLocked(true); EnvironmentManager.OnClosingLocked(true); UpdateRequired = false; StartButton.IsEnabled = false; StartButton.SetBinding(Button.ContentProperty, WaitingButtonBinding); })); GameModel model = ProfileManager.CurrentProfile.GameModel; //Проверяем наличие необходимых файлов игры if (!ConfigurationManager.CheckGame(model)) { SetStartEnabled(false); //Если необходимых файлов нет, просто вызываю этот метод. он при вышеуказанном условии покажет неактивную кнопку и сообщение о неправильном пути return; //Далее идти нет смысла } //Проверяем наличие обновления Pack01 файлами. Возвражающее значение говорит, можно ли проходить далее по алгоритму if (!await ImportPackages()) { this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate() { RemoveTask(); ProfileManager.OnProfileLocked(false); EnvironmentManager.OnFileSystemLocked(false); EnvironmentManager.OnClosingLocked(false); })); return; } //Проверяем наличие новых обновлений VersionPair pair = UpdateManager.CheckUpdates(ProfileManager.CurrentProfile.GameModel); if (pair == null) { SetStartEnabled(false); DialogManager.ShowMessageDialog(LanguageManager.Model.ErrorOccured, LanguageManager.Model.ConnectionError); return; } //Если обновление требуется if (pair.IsUpdateRequired) { //Если включен интегрированных движок обновления, пытаемся обновиться if (ProfileManager.CurrentProfile.UpdateEngineEnabled) { ShowProgressBar(); SetStartEnabled(await BeginUpdate(pair)); } else //Если интегрированный движок отключен - показываем кнопку "Обновить игру" { SetUpdateEnabled(true); } } else //Если обновление не требуется, показываем кнопку "Начать игру". { SetStartEnabled(true); } }
public RecycleAppPoolResolver(TaskManager manager) { mManager = manager; }
public static LyncUserResult CreateLyncUser(int itemId, int accountId, int lyncUserPlanId) { LyncUserResult res = TaskManager.StartResultTask <LyncUserResult>("LYNC", "CREATE_LYNC_USER"); int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive); if (accountCheck < 0) { TaskManager.CompleteResultTask(res, LyncErrorCodes.NOT_AUTHORIZED); return(res); } LyncUser retLyncUser = new LyncUser(); bool isLyncUser; isLyncUser = DataProvider.CheckLyncUserExists(accountId); if (isLyncUser) { TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_IS_ALREADY_LYNC_USER); return(res); } OrganizationUser user; user = OrganizationController.GetAccount(itemId, accountId); if (user == null) { TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT); return(res); } user = OrganizationController.GetUserGeneralSettings(itemId, accountId); if (string.IsNullOrEmpty(user.FirstName)) { TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_FIRST_NAME_IS_NOT_SPECIFIED); return(res); } if (string.IsNullOrEmpty(user.LastName)) { TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_LAST_NAME_IS_NOT_SPECIFIED); return(res); } bool quota = CheckQuota(itemId); if (!quota) { TaskManager.CompleteResultTask(res, LyncErrorCodes.USER_QUOTA_HAS_BEEN_REACHED); return(res); } LyncServer lync; try { bool bReloadConfiguration = false; Organization org = (Organization)PackageController.GetPackageItem(itemId); if (org == null) { throw new ApplicationException( string.Format("Organization is null. ItemId={0}", itemId)); } int lyncServiceId = GetLyncServiceID(org.PackageId); lync = GetLyncServer(lyncServiceId, org.ServiceId); if (string.IsNullOrEmpty(org.LyncTenantId)) { PackageContext cntx = PackageController.GetPackageContext(org.PackageId); org.LyncTenantId = lync.CreateOrganization(org.OrganizationId, org.DefaultDomain, Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_CONFERENCING].QuotaAllocatedValue), Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ALLOWVIDEO].QuotaAllocatedValue), Convert.ToInt32(cntx.Quotas[Quotas.LYNC_MAXPARTICIPANTS].QuotaAllocatedValue), Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_FEDERATION].QuotaAllocatedValue), Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ENTERPRISEVOICE].QuotaAllocatedValue)); if (string.IsNullOrEmpty(org.LyncTenantId)) { TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ENABLE_ORG); return(res); } else { DomainInfo domain = ServerController.GetDomain(org.DefaultDomain); //Add the service records if (domain != null) { if (domain.ZoneItemId != 0) { ServerController.AddServiceDNSRecords(org.PackageId, ResourceGroups.Lync, domain, ""); } } PackageController.UpdatePackageItem(org); bReloadConfiguration = true; } } if (lync.GetOrganizationTenantId(org.OrganizationId) == string.Empty) { PackageContext cntx = PackageController.GetPackageContext(org.PackageId); org.LyncTenantId = lync.CreateOrganization(org.OrganizationId, org.DefaultDomain, Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_CONFERENCING].QuotaAllocatedValue), Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ALLOWVIDEO].QuotaAllocatedValue), Convert.ToInt32(cntx.Quotas[Quotas.LYNC_MAXPARTICIPANTS].QuotaAllocatedValue), Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_FEDERATION].QuotaAllocatedValue), Convert.ToBoolean(cntx.Quotas[Quotas.LYNC_ENTERPRISEVOICE].QuotaAllocatedValue)); if (string.IsNullOrEmpty(org.LyncTenantId)) { TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ENABLE_ORG); return(res); } else { PackageController.UpdatePackageItem(org); bReloadConfiguration = true; } } LyncUserPlan plan = GetLyncUserPlan(itemId, lyncUserPlanId); if (!lync.CreateUser(org.OrganizationId, user.UserPrincipalName, plan)) { TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_USER); return(res); } if (bReloadConfiguration) { LyncControllerAsync userWorker = new LyncControllerAsync(); userWorker.LyncServiceId = lyncServiceId; userWorker.OrganizationServiceId = org.ServiceId; userWorker.Enable_CsComputerAsync(); } } catch (Exception ex) { TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_USER, ex); return(res); } try { DataProvider.AddLyncUser(accountId, lyncUserPlanId, user.UserPrincipalName); } catch (Exception ex) { TaskManager.CompleteResultTask(res, LyncErrorCodes.CANNOT_ADD_LYNC_USER_TO_DATABASE, ex); return(res); } res.IsSuccess = true; TaskManager.CompleteResultTask(); return(res); }
protected void Application_End(object sender, EventArgs e) { TaskManager.Stop(); }
/// <summary> /// Stops the windows service /// </summary> void IService.OnShutdown() { TaskManager.Stop(); }
public static ResultObject CreateBlackBerryUser(int itemId, int accountId) { ResultObject res = TaskManager.StartResultTask <ResultObject>("BLACBERRY", "CREATE_BLACKBERRY_USER"); bool isBlackBerryUser; try { isBlackBerryUser = DataProvider.CheckBlackBerryUserExists(accountId); } catch (Exception ex) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_CHECK_IF_BLACKBERRY_USER_EXISTS, ex); return(res); } if (isBlackBerryUser) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.USER_IS_ALREADY_BLAKBERRY_USER); return(res); } OrganizationUser user; try { user = OrganizationController.GetAccount(itemId, accountId); if (user == null) { throw new ApplicationException( string.Format("User is null. ItemId={0}, AccountId={1}", itemId, accountId)); } } catch (Exception ex) { TaskManager.CompleteResultTask(res, ErrorCodes.CANNOT_GET_ACCOUNT, ex); return(res); } if (user.AccountType != ExchangeAccountType.Mailbox) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.ACCOUNT_TYPE_IS_NOT_MAILBOX); return(res); } try { user = OrganizationController.GetUserGeneralSettings(itemId, accountId); if (string.IsNullOrEmpty(user.FirstName)) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.USER_FIRST_NAME_IS_NOT_SPECIFIED); return(res); } if (string.IsNullOrEmpty(user.LastName)) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.USER_LAST_NAME_IS_NOT_SPECIFIED); return(res); } } catch (Exception ex) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_USER_GENERAL_SETTINGS, ex); return(res); } BlackBerry blackBerry; try { blackBerry = GetBlackBerryProxy(itemId); } catch (Exception ex) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_GET_BLACKBERRY_PROXY, ex); return(res); } try { bool quota = CheckQuota(itemId); if (!quota) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.USER_QUOTA_HAS_BEEN_REACHED); return(res); } } catch (Exception ex) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_CHECK_QUOTA, ex); return(res); } try { ResultObject userRes = blackBerry.CreateBlackBerryUser(user.PrimaryEmailAddress); res.ErrorCodes.AddRange(userRes.ErrorCodes); if (!userRes.IsSuccess) { TaskManager.CompleteResultTask(res); return(res); } } catch (Exception ex) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_ADD_BLACKBERRY_USER, ex); return(res); } try { DataProvider.AddBlackBerryUser(accountId); } catch (Exception ex) { TaskManager.CompleteResultTask(res, BlackBerryErrorsCodes.CANNOT_ADD_BLACKBERRY_USER_TO_DATABASE, ex); return(res); } TaskManager.CompleteResultTask(); return(res); }