コード例 #1
0
ファイル: Main.cs プロジェクト: tjcomserv/SuperGrate
 /// <summary>
 /// This event will open the User Properties dialog box.
 /// </summary>
 private async void OpenUserProperties_Event(object sender, EventArgs e)
 {
     if (listUsers.SelectedItems.Count == 1)
     {
         Running = RunningTask.Unknown;
         Logger.Information("Retrieving user properties...");
         UserRow row      = null;
         UserRow template = null;
         if (CurrentListSource == ListSources.MigrationStore)
         {
             template = ULControl.HeaderRowStoreSource;
             row      = await Misc.GetUserFromStore(template, (string)listUsers.SelectedItems[0].Tag);
         }
         if (CurrentListSource == ListSources.SourceComputer)
         {
             template = ULControl.HeaderRowComputerSource;
             row      = await Misc.GetUserFromHost(template, tbSourceComputer.Text, (string)listUsers.SelectedItems[0].Tag);
         }
         if (Canceled)
         {
             Running = RunningTask.None;
             Logger.Information("Canceled.");
             return;
         }
         Running = RunningTask.None;
         Logger.Success("Done!");
         new UserProperties(template, row).ShowDialog();
     }
 }
コード例 #2
0
ファイル: Tasks.cs プロジェクト: 3lpsy/FactionMarauder
        public override CommandOutput Execute(Dictionary <string, string> Parameters = null)
        {
            CommandOutput output = new CommandOutput();

            output.Complete = true;
            output.Success  = true;
            string task_id = "";

            if (Parameters.ContainsKey("Kill"))
            {
                task_id = Parameters["Kill"];
            }

            try
            {
                if (!String.IsNullOrEmpty(task_id) && Parameters.ContainsKey("Kill"))
                {
                    RunningTask task = State.RunningTasks.Find(x => x.Id == task_id);
                    task.CancellationTokenSource.Cancel();
                    output.Message = $"Requested task {task_id} to cancel";
                }
                else
                {
                    output.Message = JsonConvert.SerializeObject(State.RunningTasks);
                }
            }
            catch (Exception e)
            {
                output.Complete = true;
                output.Success  = false;
                output.Message  = e.Message;
            }
            return(output);
        }
コード例 #3
0
 private void AddRunningTask(RunningTask runningTask)
 {
     lock (_runningTasks)
     {
         _runningTasks.Add(runningTask);
     }
 }
コード例 #4
0
ファイル: TaskManager.cs プロジェクト: huchao007/bbsmax
        public static bool BeginTask(int userID, StepByStepTaskBase taskAction, string param)
        {
            Type taskType = taskAction.GetType();

            Guid taskID = Guid.NewGuid();

            RunningTask task = new RunningTask(taskAction);

            int totalCount = 0;
            long offset = 0;
            string title;
            if (task.Task.BeforeExecute(userID, param, ref offset, ref totalCount, out title) == false)
                return false;


            int result = StepByStepTaskDao.Instance.BeginTask(taskID, taskType, userID, param, totalCount, offset, title, taskAction.InstanceMode);

            switch (result)
            {
                case 0:
                    return true;

                case 1:
                case 2:
                    return false;
            
                default:
                    return false;
            }
        }
コード例 #5
0
 private void RemoveRunningTask(RunningTask runningTask)
 {
     lock (_runningTasks)
     {
         _runningTasks.Remove(runningTask);
     }
 }
コード例 #6
0
        public async Task StartCommandAsync(Func <ICommandStatus, Task> action, string maintext = null, string subtext = null)
        {
            var task = new RunningTask("console", maintext, subtext);

            if (!_tasks.TryGetValue("console", out TaskContext c))
            {
                c = new TaskContext
                {
                    Tasks = { task }
                };
                _tasks.TryAdd("console", c);
            }
            else
            {
                lock (c)
                {
                    c.Tasks.Add(task);
                }
                c.FireChanged();
            }

            try
            {
                await action(task);

                task.Dispose();
            }
            catch (Exception ex)
            {
                task.Exception = ex;
            }
        }
コード例 #7
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var taskName = request.DataStore.GetValue("TaskName");

            TaskCollection tasks = null;

            using (TaskService ts = new TaskService())
            {
                tasks = ts.RootFolder.GetTasks(new Regex(taskName));
                foreach (Task task in tasks)
                {
                    try
                    {
                        RunningTask runningTask = task.Run();
                        return(new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject()));
                    }
                    catch (Exception e)
                    {
                        if (NTHelper.IsCredentialGuardEnabled())
                        {
                            return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "CredentialGuardEnabled"));
                        }

                        return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), e, "RunningTaskFailed"));
                    }
                }
            }

            // We should never return this
            return(new ActionResponse(ActionStatus.Failure, JsonUtility.GetEmptyJObject(), "SccmTaskNotFound"));
        }
コード例 #8
0
ファイル: AsyncLoop.cs プロジェクト: CryptoEnder/x42-Server
 /// <summary>
 ///     Wait for the loop task to complete.
 /// </summary>
 public void Dispose()
 {
     if (!RunningTask.IsCanceled)
     {
         logger.LogInformation("Waiting for {0} to finish.", Name);
         RunningTask.Wait();
     }
 }
コード例 #9
0
        public RunningTaskViewModel(RunningTask model)
        {
            this.model = model;

            ViewModelHelper.BindNotifyChanged(model, this, (sender, e) =>
            {
                if (e.PropertyName == "Description")
                    this.RaisePropertyChanged(() => this.Description);
            });
        }
コード例 #10
0
        /// <summary>
        ///   Stops the partition pump.  In case it isn't running, nothing happens.
        /// </summary>
        ///
        /// <param name="reason">The reason why the processing for the associated partition is being stopped.  In case it's <c>null</c>, the internal close reason set by this pump is used.</param>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        ///
        public async Task StopAsync(CloseReason?reason)
        {
            if (RunningTask != null)
            {
                await RunningTaskSemaphore.WaitAsync().ConfigureAwait(false);

                try
                {
                    if (RunningTask != null)
                    {
                        RunningTaskTokenSource.Cancel();
                        RunningTaskTokenSource = null;

                        try
                        {
                            // RunningTask is only expected to fail when the event processor throws while processing
                            // an error, but unforeseen scenarios might happen.

                            await RunningTask.ConfigureAwait(false);
                        }
                        catch (Exception)
                        {
                            // TODO: delegate the exception handling to an Exception Callback.
                        }

                        RunningTask = null;

                        // It's important to close the consumer as soon as possible.  Failing to do so multiple times
                        // would make it impossible to create more consumers for the associated partition as there's a
                        // limit per client.

                        await InnerConsumer.CloseAsync().ConfigureAwait(false);

                        // In case an exception is encountered while the processing is stopping, don't catch it and let
                        // the event processor handle it.  The pump has no way to guess when a partition was lost or when
                        // a shutdown request was sent to the event processor, so it expects a "reason" parameter to provide
                        // this information.  However, in case of pump failure, the external event processor does not have
                        // enough information to figure out what failure reason to use, as this information is only known
                        // by the pump.  In this case, we expect the processor-provided reason to be null, and the private
                        // CloseReason is used instead.

                        if (OwnerEventProcessor.ProcessingForPartitionStoppedAsync != null)
                        {
                            var stopContext = new PartitionProcessingStoppedContext(Context, reason ?? CloseReason);
                            await OwnerEventProcessor.ProcessingForPartitionStoppedAsync(stopContext).ConfigureAwait(false);
                        }
                    }
                }
                finally
                {
                    RunningTaskSemaphore.Release();
                }
            }
        }
コード例 #11
0
 public void TaskWatcher(object sender, DecryptedMessageArgs args)
 {
     foreach (AgentTask agentTask in args.AgentTasks)
     {
         RunningTask runningTask = new RunningTask();
         runningTask.Command  = agentTask.Command;
         runningTask.TaskName = agentTask.Name;
         runningTask.Task     = new Task(() => ProcessCommand(agentTask), runningTask.CancellationTokenSource.Token);
         runningTask.Task.Start();
         State.RunningTasks.Add(runningTask);
     }
 }
コード例 #12
0
ファイル: Main.cs プロジェクト: tjcomserv/SuperGrate
        /// <summary>
        /// This event will fire whenever the btnListStore is clicked. This will refresh or re-list the listUsers control with users from the store.
        /// </summary>
        private async void BtnListStore_Click(object sender, EventArgs e)
        {
            Running = RunningTask.Unknown;
            miAddRemoveCol.Enabled = true;
            lblUserList.Text       = "Users in Migration Store:";
            listUsers.SetViewMode(Config.Settings["ULViewMode"]);
            listUsers.SetColumns(ULControl.HeaderRowStoreSource, Config.Settings["ULStoreColumns"]);
            CurrentUserRows = await Misc.GetUsersFromStore();

            listUsers.SetRows(CurrentUserRows, CurrentSortColumn[ListSources.MigrationStore], CurrentSortDirection[ListSources.MigrationStore]);
            CurrentListSource = ListSources.MigrationStore;
            Running           = RunningTask.None;
        }
コード例 #13
0
ファイル: Main.cs プロジェクト: tjcomserv/SuperGrate
        /// <summary>
        /// This event will fire whenever the btnListSource is clicked. This will refresh or re-list the listUsers control with users from the source computer.
        /// </summary>
        private async void BtnListSource_Click(object sender, EventArgs e)
        {
            Running = RunningTask.Unknown;
            miAddRemoveCol.Enabled = true;
            listUsers.SetViewMode(Config.Settings["ULViewMode"]);
            listUsers.SetColumns(ULControl.HeaderRowComputerSource, Config.Settings["ULSourceColumns"]);
            lblUserList.Text = "Users on Source Computer:";
            CurrentUserRows  = await Misc.GetUsersFromHost(tbSourceComputer.Text);

            listUsers.SetRows(CurrentUserRows, CurrentSortColumn[ListSources.SourceComputer], CurrentSortDirection[ListSources.SourceComputer]);
            CurrentListSource = ListSources.SourceComputer;
            Running           = RunningTask.None;
        }
コード例 #14
0
ファイル: Run.cs プロジェクト: alexfordc/Au
 /// <summary>
 /// Ends single task, if still running.
 /// If rt==null, ends the green task, if running.
 /// </summary>
 public void EndTask(RunningTask rt = null)
 {
     if (rt == null)
     {
         rt = Program.Tasks.GetGreenTask(); if (rt == null)
         {
             return;
         }
     }
     if (_a.Contains(rt))
     {
         _EndTask(rt);
     }
 }
コード例 #15
0
            public async Task ReturnsFalseForNonExpiredTaskAsync()
            {
                var timeService = new TimeService(TimeSpan.FromSeconds(1));

                var scheduledTask = new ScheduledTask
                {
                    MaximumDuration = TimeSpan.FromMinutes(2)
                };

                var runningTask = new RunningTask(scheduledTask, DateTime.Now);

                await TaskShim.Delay(TimeSpan.FromSeconds(1));

                Assert.IsFalse(runningTask.IsExpired(timeService));
            }
コード例 #16
0
        private RunningTask GetRunningTask <T>(string key, IEnumerable <KeyValuePair <string, string> > attributes, TimeSpan maxAge)
        {
            RunningTask runningTask       = null;
            var         orderedAttributes = attributes.OrderBy(a => a.Key);

            lock (_runningTasks)
            {
                runningTask = _runningTasks.FirstOrDefault(
                    r => r.Key == key &&
                    r.MaxAge == maxAge &&
                    r.Attributes.OrderBy(a => a.Key).SequenceEqual(orderedAttributes)
                    );
            }
            return(runningTask);
        }
コード例 #17
0
ファイル: Run.cs プロジェクト: alexfordc/Au
    bool _CanRunNow(FileNode f, Compiler.CompResults r, out RunningTask running, bool runFromEditor = false)
    {
        running = null;
        switch (r.runMode)
        {
        case ERunMode.green:
            running = GetGreenTask();
            break;

        case ERunMode.blue when !(r.ifRunning == EIfRunning.run || (r.ifRunning == EIfRunning.run_restart && !runFromEditor)):
            running = _GetRunning(f);
            break;

        default: return(true);
        }
        return(running == null);
    }
コード例 #18
0
ファイル: Main.cs プロジェクト: tjcomserv/SuperGrate
        /// <summary>
        /// This event will fire when the btnDelete button is clicked, and will start the deletion process for the selected users.
        /// </summary>
        private async void BtnDelete_Click(object sender, EventArgs e)
        {
            int           selectedCount = listUsers.SelectedItems.Count;
            ConfirmDialog confirm       = null;

            if (selectedCount == 1)
            {
                confirm = new ConfirmDialog("Delete User", "Are you sure you want to delete this user?", Properties.Resources.trash_16_32_ico);
            }
            else
            {
                confirm = new ConfirmDialog("Delete Users", "Are you sure you want to delete these " + selectedCount + " users?", Properties.Resources.trash_16_32_ico);
            }
            confirm.ShowDialog();
            if (confirm.DialogResult != DialogResult.OK)
            {
                return;
            }
            Running = RunningTask.RemoteProfileDelete;
            List <string> IDs = new List <string>();

            foreach (int index in listUsers.SelectedIndices)
            {
                IDs.Add((string)listUsers.Items[index].Tag);
            }
            if (CurrentListSource == ListSources.MigrationStore)
            {
                await Misc.DeleteFromStore(IDs.ToArray());

                Running = RunningTask.None;
                btnListStore.PerformClick();
            }
            else if (CurrentListSource == ListSources.SourceComputer)
            {
                await Misc.DeleteFromSource(SourceComputer, IDs.ToArray());

                Running = RunningTask.None;
                btnListSource.PerformClick();
            }
            else
            {
                Running = RunningTask.None;
            }
        }
コード例 #19
0
        public async Task <T> ExecuteWithCache <T>(CancellationToken ct, string cacheKey, Func <Task <T> > execute, TimeSpan maxAge, IDictionary <string, string> attributes = null)
        {
            attributes = attributes ?? new Dictionary <string, string>();
            var semaphore = AcquireRunningSemaphore(cacheKey, attributes, maxAge);
            await semaphore.Semaphore.WaitAsync(ct);

            var runningTask = GetRunningTask <T>(cacheKey, attributes, maxAge);

            if (runningTask != null)
            {
                semaphore.Semaphore.Release();
                return(await((Task <T>)runningTask.Task));
            }
            var taskCompletionSource = new TaskCompletionSource <T>();

            runningTask = new RunningTask()
            {
                Key        = cacheKey,
                Attributes = attributes,
                MaxAge     = maxAge,
                Task       = taskCompletionSource.Task
            };
            AddRunningTask(runningTask);
            semaphore.Semaphore.Release();
            try
            {
                var result = await ExecuteWithCacheInternal(ct, cacheKey, execute, maxAge, attributes);

                taskCompletionSource.SetResult(result);
                return(result);
            }
            catch (Exception ex)
            {
                taskCompletionSource.SetException(ex);
                throw;
            }
            finally
            {
                RemoveRunningTask(runningTask);
                RemoveSemaphore(semaphore);
            }
        }
コード例 #20
0
        public async Task StartTaskAsync(Func <ITaskStatus, Task> action, string context = null, string maintext = null, string subtext = null)
        {
            if (context == null)
            {
                context = string.Empty;
            }

            var task = new RunningTask(context, maintext, subtext);

            if (!_dict.TryGetValue(context, out TaskContext c))
            {
                c = new TaskContext
                {
                    Tasks = { task }
                };
                _dict.TryAdd(context, c);
            }
            else
            {
                lock (c)
                {
                    c.Tasks.Add(task);
                }
                c.FireChanged();
            }

            try
            {
                await action(task);

                task.Dispose();
            }
            catch (Exception ex)
            {
                task.Exception = ex;
                if (DumpExceptionsToConsole)
                {
                    Console.Error.Write(ex);
                }
            }
        }
コード例 #21
0
ファイル: StepByStepTaskDao.cs プロジェクト: huchao007/bbsmax
        public override RunningTask GetRunningTask(int userID, Guid taskID)
        {
            RunningTask task = null;

            using (SqlQuery query = new SqlQuery())
            {
                query.CommandType = CommandType.StoredProcedure;
                query.CommandText = "bx_GetRunningStepByStepTask";

                query.CreateParameter<int>("@UserID", userID, SqlDbType.Int);
                query.CreateParameter<Guid>("@TaskID", taskID, SqlDbType.UniqueIdentifier);

                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    if (reader.Read())
                        task = new RunningTask(reader);
                }

                return task;
            }
        }
コード例 #22
0
        public void RunNextTask()
        {
            //--- Check task in task wait list exists
            if (TaskWaitList.Count == 0)
            {
                return;
            }

            //--- Step the task timer
            TaskTimer.Stop();

            //--- Get and remove the first task of the task wait list
            RunningTask = TaskWaitList[0];
            TaskWaitList.RemoveAt(0);

            //--- Run the task and clear the running task
            RunningTask.Run();
            RunningTask = null;

            //--- Start the task timer
            TaskTimer.Start();
        }
コード例 #23
0
ファイル: Main.cs プロジェクト: tjcomserv/SuperGrate
        /// <summary>
        /// This event will fire whenever the btStartStop button is clicked, starting or stopping whatever task is queued to happen.
        /// </summary>
        private async void BtStartStop_Click(object sender, EventArgs e)
        {
            if (Running != RunningTask.None)
            {
                Canceled = true;
            }
            else
            {
                Running = RunningTask.USMT;
                List <string> IDs = new List <string>();
                foreach (int index in listUsers.SelectedIndices)
                {
                    IDs.Add((string)listUsers.Items[index].Tag);
                }
                bool setting;
                bool success;
                if (CurrentListSource == ListSources.SourceComputer)
                {
                    success = await USMT.Do(USMTMode.ScanState, IDs.ToArray());

                    if (bool.TryParse(Config.Settings["AutoDeleteFromSource"], out setting) && setting && success)
                    {
                        await Misc.DeleteFromSource(SourceComputer, IDs.ToArray());
                    }
                }
                if (tbDestinationComputer.Text != "" && Running == RunningTask.USMT)
                {
                    success = await USMT.Do(USMTMode.LoadState, IDs.ToArray());

                    if (bool.TryParse(Config.Settings["AutoDeleteFromStore"], out setting) && setting && success)
                    {
                        await Misc.DeleteFromStore(IDs.ToArray());
                    }
                }
                Running = RunningTask.None;
                Logger.Information("Done.");
            }
        }
コード例 #24
0
        public override RunningTask GetRunningTask(int userID, Guid taskID)
        {
            RunningTask task = null;

            using (SqlQuery query = new SqlQuery())
            {
                query.CommandType = CommandType.StoredProcedure;
                query.CommandText = "bx_GetRunningStepByStepTask";

                query.CreateParameter <int>("@UserID", userID, SqlDbType.Int);
                query.CreateParameter <Guid>("@TaskID", taskID, SqlDbType.UniqueIdentifier);

                using (XSqlDataReader reader = query.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        task = new RunningTask(reader);
                    }
                }

                return(task);
            }
        }
コード例 #25
0
 /// <summary>
 /// Run Task registered in task scheduler
 /// </summary>
 private void RunZingitTaskScheduler()
 {
     using (TaskService ts = new TaskService())
     {
         try
         {
             Task zingitTask = TaskManager.getTask(TASK_NAME, ts);
             if (zingitTask != null)
             {
                 RunningTask runningTask = zingitTask.Run();
                 Thread.Sleep(1000);
                 if (runningTask.State == TaskState.Running)
                 {
                     MessageBox.Show("Task started successfully.");
                 }
             }
             else
             {
                 MessageBox.Show("Task is not created yet. Please create the task through scheduler configuration screen and try again.");
             }
         }
         catch (Exception ex)
         {
             if (ex.Message.Contains("0x80070002") == true)
             {
                 string errMessage = ex.Message + Environment.NewLine +
                                     "Looks like the task is already running. Please check.";
                 MessageBox.Show(errMessage);
             }
             else
             {
                 MessageBox.Show(ex.Message);
             }
         }
     }
 }
コード例 #26
0
ファイル: Run.cs プロジェクト: alexfordc/Au
 bool _EndTask(RunningTask rt, bool onExit = false)
 {
     Debug.Assert(_a.Contains(rt));
     return(rt.End(onExit));
 }
コード例 #27
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Menu_Mouse_Down(object sender, RoutedEventArgs e)
        {
            FrameworkElement feSource = e.Source as FrameworkElement;
            switch (feSource.Name)
            {
                case "Connect":
                    if(!init)
                        Init_Connect_Window();
                    else
                    {
                         portWindow.Visibility = Visibility.Visible;

                     }
                    break;
                case "Bluetooth":
                    BluetoothWindow b_w = new BluetoothWindow(this);
                    b_w.Show();
                    break;
                case "Draw":
                    if (tetris != null)
                    {
                        tetris.Stop_Tetris();

                    }
                    if (video != null)
                        video.RunVideo = false;
                    if (webcam != null)
                        webcam.closeWebcam();

                    runningTask = RunningTask.Draw;
                    drawAccept = true;

                    draw = new Draw(drawlayer,monitorImg,monitor);
                    ex_eff = draw.Draw_execute;

                    draw.setColor = Color.FromArgb(255, 0, 0, 255);
                    draw.setDrawtype = Drawtype.rectangle;

                    Binding ColorBinding = new Binding("setColor");
                    ColorBinding.Source = draw;
                    ColorBinding.Mode = BindingMode.TwoWay;
                    DrawingColorPicker.SetBinding(Xceed.Wpf.Toolkit.ColorCanvas.SelectedColorProperty, ColorBinding);

                    break;
                case "Effects":
                    if (tetris != null)
                    {
                        tetris.Stop_Tetris();

                    }
                    if (video != null)
                        video.RunVideo = false;
                    if (webcam != null)
                        webcam.closeWebcam();

                    runningTask = RunningTask.Effect;
                    drawAccept = false;
                    ex_eff = plasma.Plasma_execute;

                    monitorTimer.IsEnabled = true;

                    break;
                case "Images":
                    if (tetris != null)
                    {
                        tetris.Stop_Tetris();
                        monitor = BitmapFactory.New(68, 42);
                        monitorImg.Source = monitor;

                    }
                    if (webcam != null)
                        webcam.closeWebcam();
                    if (video != null)
                        video.RunVideo = false;

                    drawAccept = false;
                    monitorImg.Source = monitor;
                    runningTask = RunningTask.Image;

                    ip = new ImagePixelate(monitor);
                    ex_eff = ip.execute;

                    break;

                case "Video":
                    if (tetris != null)
                    {
                        tetris.Stop_Tetris();

                        monitorImg.Source = monitor;

                    }
                    if (webcam != null)
                        webcam.closeWebcam();
                    runningTask = RunningTask.Video;

                    CentralMonitor.IsEnabled = false;
                    drawAccept = false;

                    video = new Video(monitor);
                    ex_eff = video.video_execute;

                    video.RunVideo = true;

                    break;
                case "Tetris":

                    if (webcam != null)
                        webcam.closeWebcam();
                    if (video != null)
                        video.RunVideo = false;
                    runningTask = RunningTask.Tetris;
                    drawAccept = false;

                    if (tetris == null)
                    {

                        tetris = new TetrisExecute(monitor, monitorTimer, AuroraWindow);
                        ex_eff = tetris.tetris_exe;

                    }
                    else
                    {
                        tetris.Stop_Tetris();
                        tetris = new TetrisExecute(monitor, monitorTimer, AuroraWindow);
                        ex_eff = tetris.tetris_exe;

                    }
                    break;
                case "Webcam":
                    runningTask = RunningTask.Webcam;
                    CentralMonitor.IsEnabled = false;
                    drawAccept = false;

                    if (tetris != null)
                        tetris.Stop_Tetris();
                    if (webcam == null)
                    {
                        webcam = new Webcam(monitor);
                    }
                    if (video != null)
                        video.RunVideo = false;
                    webcam.resumeWebcam(monitor);
                    ex_eff = webcam.Webcam_execute;

                    break;

            }
            SetUserControls();
        }
コード例 #28
0
        private void Bluetooth_Command_Listener(object sender, PropertyChangeArgs command)
        {
            try
            {
                int Mode = -1;
                string comm = command.mesg;
                System.Diagnostics.Debug.WriteLine("Command wurde übergeben: " + comm);
                switch (comm)
                {
                    case "Paint":         //Paint
                        {
                            Mode = 0;
                            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)delegate
                            {
                                if (tetris != null)
                                {
                                    tetris.Stop_Tetris();
                                    monitor = BitmapFactory.New(68, 42);
                                    monitorImg.Source = monitor;

                                }

                                runningTask = RunningTask.Draw;
                                drawAccept = true;
                                if (video != null)
                                    video.RunVideo = false;
                                if (webcam != null)
                                    webcam.closeWebcam();

                                try
                                {
                                    draw = new Draw(drawlayer, monitorImg, monitor);
                                }
                                catch (Exception exc)
                                {
                                }
                                ex_eff = draw.Draw_execute;

                                draw.setColor = Color.FromArgb(0, 200, 0, 255);
                                draw.setDrawtype = Drawtype.point;

                                Binding ColorBinding = new Binding("setColor");
                                ColorBinding.Source = draw;
                                ColorBinding.Mode = BindingMode.TwoWay;
                                DrawingColorPicker.SetBinding(Xceed.Wpf.Toolkit.ColorCanvas.SelectedColorProperty, ColorBinding);

                                SetUserControls();

                                //object GlassOfSugar = new  Object();
                                //Slider slider = new Slider();
                                //Binding AmountBinding = new Binding("Amount");
                                ////AmountBinding.Source = GlassOfSugar;
                                ////AmountBinding.Mode = BindingMode.TwoWay;
                                //slider.SetBinding(Slider.ValueProperty, AmountBinding);

                            });

                            break;
                        }
                    case "Fotobearbeitung":       //Pixelated Picture
                        {
                            Mode = 1;

                            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)delegate
                            {
                                if (tetris != null)
                                {
                                    tetris.Stop_Tetris();
                                    monitor = BitmapFactory.New(68, 42);
                                    monitorImg.Source = monitor;

                                }

                                runningTask = RunningTask.Draw;
                                drawAccept = true;
                                if (video != null)
                                    video.RunVideo = false;
                                if (webcam != null)
                                    webcam.closeWebcam();

                                try
                                {
                                    draw = new Draw(drawlayer, monitorImg, monitor);
                                }
                                catch (Exception exc)
                                {
                                }
                                ex_eff = draw.Draw_execute;

                                draw.setColor = Color.FromArgb(0, 200, 0, 255);
                                draw.setDrawtype = Drawtype.point;

                                Binding ColorBinding = new Binding("setColor");
                                ColorBinding.Source = draw;
                                ColorBinding.Mode = BindingMode.TwoWay;
                                DrawingColorPicker.SetBinding(Xceed.Wpf.Toolkit.ColorCanvas.SelectedColorProperty, ColorBinding);

                                SetUserControls();

                                //object GlassOfSugar = new Object();
                                //Slider slider = new Slider();
                                //Binding AmountBinding = new Binding("Amount");
                                //AmountBinding.Source = GlassOfSugar;
                                //AmountBinding.Mode = BindingMode.TwoWay;
                                //slider.SetBinding(Slider.ValueProperty, AmountBinding);

                            });

                            break;
                        }
                    case "Tetris":       //Tetris
                        {
                            Mode = 2;

                            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)delegate
                            {
                                if (webcam != null)
                                    webcam.closeWebcam();

                                runningTask = RunningTask.Tetris;
                                drawAccept = false;
                                //Versuchsweise eingebaut -> dt_m.Tick ist fehlerquelle -.-  -> sollte eigentlich nicht sein
                                //dt_m.IsEnabled = false;

                                if (tetris == null)
                                {
                                    monitor = BitmapFactory.New(68, 42);
                                    monitorImg.Source = monitor;
                                    tetris = new TetrisExecute(monitor, monitorTimer, AuroraWindow);
                                    ex_eff = tetris.tetris_exe;

                                    Binding ScoreBinding = new Binding("Score");
                                    ScoreBinding.Mode = BindingMode.OneWay;
                                    ScoreBinding.Source = tetris.t;
                                    Points.SetBinding(Label.ContentProperty, ScoreBinding);

                                    Binding LevelBinding = new Binding("Level");
                                    LevelBinding.Mode = BindingMode.OneWay;
                                    LevelBinding.Source = tetris.t;
                                    Level.SetBinding(Label.ContentProperty, LevelBinding);

                                }
                                else
                                {
                                    tetris.Stop_Tetris();
                                    tetris = new TetrisExecute(monitor, monitorTimer, AuroraWindow);
                                    ex_eff = tetris.tetris_exe;

                                    Binding ScoreBinding = new Binding("Score");
                                    ScoreBinding.Mode = BindingMode.TwoWay;
                                    ScoreBinding.Source = tetris.t;
                                    Points.SetBinding(Label.ContentProperty, ScoreBinding);
                                }
                                SetUserControls();
                            });

                            break;
                        }

                    default:
                        {
                            //hier wäre normalerweise ein switch(mode) -> unnötig?

                            break;
                        }
                }

            }
            catch (Exception exc)
            {

            }
        }
コード例 #29
0
        /// <summary>
        /// <list type="bullet">
        /// <item>
        /// <description>AuroraWindow size is suitet to the user display</description>
        /// </item>
        /// <item>
        /// <description>The rgb mask and brigthness is set to 256 default</description>
        /// </item>
        /// <item>
        /// <description>The monitorImg <see cref=""/> gets initialised in proportion to the AuroraWindow </description>
        /// </item>
        /// <item>
        /// <description>The portWindow <seealso cref=""/> is initialised and the eventhandler data changed add, which is interrupted if the connection
        /// is cancelated or startet</description>
        /// </item>
        /// <item>
        /// <description>A very important point in InitMainWindow is to set the monitorImg.Source to monitor, otherwise nothing appears on the surface</description>
        /// </item>
        /// <item>
        /// <description>The RenderOptions.SetEdgeMode(monitorImg, EdgeMode.Aliased) EdgeMode property squares the pixel and guarantes clear edges on the 68 x 42 resolution</description>
        /// </item>
        /// <item>
        /// <description>The monitorTimer.Tick event has a frequence of 40 Hz</description>
        /// </item>
        /// </list>
        /// </summary>
        public void InitMainWindow()
        {
            Point screenSize = new Point(System.Windows.SystemParameters.FullPrimaryScreenWidth, System.Windows.SystemParameters.FullPrimaryScreenHeight);
            AuroraWindow.Width = screenSize.X * 0.4;
            AuroraWindow.Height = screenSize.Y * 0.9;

            redMask = 255;
            greenMask = 255;
            blueMask = 255;
            bright = 255;

            monitorImg.Width = AuroraWindow.Width * 0.85;
            monitorImg.Height = monitorImg.Width / 1.618;

            //Das SerialportWindow initialisiern
            portWindow = new PortWindow();
            portWindow.data.Changed += new ChangedEventhandler(StatusChanged);

            //Das Rechteck für die Blit funktion festlegen
            r = new Rect(0, 0, 68, 42);

            //Writeable Bitmaps initialisiern
            monitor = BitmapFactory.New(68, 42);
            drawlayer = BitmapFactory.New(68, 42);

            monitorImg.Source = monitor;

            RenderOptions.SetBitmapScalingMode(monitorImg, BitmapScalingMode.NearestNeighbor);
            RenderOptions.SetEdgeMode(monitorImg, EdgeMode.Aliased);

            monitorTimer = new DispatcherTimer(DispatcherPriority.Render);
            monitorTimer.Interval = new TimeSpan(0, 0, 0, 0, 25);
            monitorTimer.Tick += monitorTimer_Tick;
            monitorTimer.Start();

            bitmapbuffer = new Byte[monitor.ToByteArray().Length];

            CentralMonitor.IsEnabled = false;

            runningTask = RunningTask.Effect;
            filterBitmap = BitmapFactory.New(68, 42);

            //Init Objects and Options Windows
            expandingObjects = new ExpandingObjects(monitor);
            expandingObjectsWindow = new ExpandingObjectsOptionsWindow(expandingObjects);
            movingText = new MovingText(monitor);
            movingTextOptionWindow = new MovingTextOptionsWindow(movingText);
            plasma = new Plasma(monitor);
            plasmaOptionWindow = new PlasmaOptionsWindow(plasma);
            colorGradient = new ColorGradient(monitor);
            gradientOptionWindow = new GradientColorOptionsWindow(colorGradient);
            StickyWindow.RegisterExternalReferenceForm(this);

            //Bluetooth Event listening
            RgbLibrary.Bluetooth.Instance.CommandControlChange += new Bluetooth.PropertyChangeHandler(Bluetooth_Command_Listener);
        }
コード例 #30
0
        /// <summary>
        /// <list type="bullet">
        /// <item>
        /// <description>AuroraWindow size is suitet to the user display</description>
        /// </item>
        /// <item>
        /// <description>The rgb mask and brigthness is set to 256 default</description>
        /// </item>
        /// <item>
        /// <description>The monitorImg <see cref=""/> gets initialised in proportion to the AuroraWindow </description>
        /// </item>
        /// <item>
        /// <description>The portWindow <seealso cref=""/> is initialised and the eventhandler data changed add, which is interrupted if the connection
        /// is cancelated or startet</description>
        /// </item>
        /// <item>
        /// <description>A very important point in InitMainWindow is to set the monitorImg.Source to monitor, otherwise nothing appears on the surface</description>
        /// </item>
        /// <item>
        /// <description>The RenderOptions.SetEdgeMode(monitorImg, EdgeMode.Aliased) EdgeMode property squares the pixel and guarantes clear edges on the 68 x 42 resolution</description>
        /// </item>
        /// <item>
        /// <description>The monitorTimer.Tick event has a frequence of 40 Hz</description>
        /// </item>
        /// </list>
        /// </summary>
        public void InitMainWindow()
        {
            Point screenSize = new Point(System.Windows.SystemParameters.FullPrimaryScreenWidth, System.Windows.SystemParameters.FullPrimaryScreenHeight);

            AuroraWindow.Width  = screenSize.X * 0.4;
            AuroraWindow.Height = screenSize.Y * 0.9;


            redMask   = 255;
            greenMask = 255;
            blueMask  = 255;
            bright    = 255;


            monitorImg.Width  = AuroraWindow.Width * 0.85;
            monitorImg.Height = monitorImg.Width / 1.618;

            //Das SerialportWindow initialisiern
            portWindow = new PortWindow();
            portWindow.data.Changed += new ChangedEventhandler(StatusChanged);


            //Das Rechteck für die Blit funktion festlegen
            r = new Rect(0, 0, 68, 42);

            //Writeable Bitmaps initialisiern
            monitor   = BitmapFactory.New(68, 42);
            drawlayer = BitmapFactory.New(68, 42);


            monitorImg.Source = monitor;

            RenderOptions.SetBitmapScalingMode(monitorImg, BitmapScalingMode.NearestNeighbor);
            RenderOptions.SetEdgeMode(monitorImg, EdgeMode.Aliased);

            monitorTimer          = new DispatcherTimer(DispatcherPriority.Render);
            monitorTimer.Interval = new TimeSpan(0, 0, 0, 0, 25);
            monitorTimer.Tick    += monitorTimer_Tick;
            monitorTimer.Start();

            bitmapbuffer = new Byte[monitor.ToByteArray().Length];

            CentralMonitor.IsEnabled = false;

            runningTask  = RunningTask.Effect;
            filterBitmap = BitmapFactory.New(68, 42);

            //Init Objects and Options Windows
            expandingObjects       = new ExpandingObjects(monitor);
            expandingObjectsWindow = new ExpandingObjectsOptionsWindow(expandingObjects);
            movingText             = new MovingText(monitor);
            movingTextOptionWindow = new MovingTextOptionsWindow(movingText);
            plasma               = new Plasma(monitor);
            plasmaOptionWindow   = new PlasmaOptionsWindow(plasma);
            colorGradient        = new ColorGradient(monitor);
            gradientOptionWindow = new GradientColorOptionsWindow(colorGradient);
            StickyWindow.RegisterExternalReferenceForm(this);

            //Bluetooth Event listening
            RgbLibrary.Bluetooth.Instance.CommandControlChange += new Bluetooth.PropertyChangeHandler(Bluetooth_Command_Listener);
        }
コード例 #31
0
ファイル: Run.cs プロジェクト: alexfordc/Au
    /// <summary>
    /// Executes the compiled assembly in new process.
    /// Returns: process id if started now, 0 if failed, (int)ATask.ERunResult.deferred if scheduled to run later.
    /// </summary>
    /// <param name="f"></param>
    /// <param name="r"></param>
    /// <param name="args"></param>
    /// <param name="noDefer">Don't schedule to run later. If cannot run now, just return 0.</param>
    /// <param name="wrPipeName">Pipe name for ATask.WriteResult.</param>
    /// <param name="ignoreLimits">Don't check whether the task can run now.</param>
    /// <param name="runFromEditor">Starting from the Run button or menu Run command.</param>
    public unsafe int RunCompiled(FileNode f, Compiler.CompResults r, string[] args,
                                  bool noDefer = false, string wrPipeName = null, bool ignoreLimits = false, bool runFromEditor = false)
    {
g1:
        if (!ignoreLimits && !_CanRunNow(f, r, out var running, runFromEditor))
        {
            var  ifRunning = r.ifRunning;
            bool same      = running.f == f;
            if (!same)
            {
                ifRunning = r.ifRunning2 switch
                {
                    EIfRunning2.cancel => EIfRunning.cancel,
                    EIfRunning2.wait => EIfRunning.wait,
                    EIfRunning2.warn => EIfRunning.warn,
                    _ => (ifRunning & ~EIfRunning._restartFlag) switch { EIfRunning.cancel => EIfRunning.cancel, EIfRunning.wait => EIfRunning.wait, _ => EIfRunning.warn }
                };
            }
            else if (ifRunning.Has(EIfRunning._restartFlag))
            {
                if (runFromEditor)
                {
                    ifRunning = EIfRunning.restart;
                }
                else
                {
                    ifRunning &= ~EIfRunning._restartFlag;
                }
            }
            //AOutput.Write(same, ifRunning);
            switch (ifRunning)
            {
            case EIfRunning.cancel:
                break;

            case EIfRunning.wait when !noDefer:
                _q.Insert(0, new _WaitingTask(f, r, args));
                return((int)ATask.ERunResult.deferred);                //-1

            case EIfRunning.restart when _EndTask(running):
                goto g1;

            default:             //warn
                string s1 = same ? "it" : $"{running.f.SciLink}";
                AOutput.Write($"<>Cannot start {f.SciLink} because {s1} is running. You may want to <+properties \"{f.IdStringWithWorkspace}\">change<> <c green>ifRunning<>, <c green>ifRunning2<>, <c green>runMode<>.");
                break;
            }
            return(0);
        }

        _SpUac uac = _SpUac.normal; int preIndex = 0;

        if (!AUac.IsUacDisabled)
        {
            //info: to completely disable UAC on Win7: gpedit.msc/Computer configuration/Windows settings/Security settings/Local policies/Security options/User Account Control:Run all administrators in Admin Approval Mode/Disabled. Reboot.
            //note: when UAC disabled, if our uac is System, IsUacDisabled returns false (we probably run as SYSTEM user). It's OK.
            var IL = AUac.OfThisProcess.IntegrityLevel;
            if (r.uac == EUac.inherit)
            {
                switch (IL)
                {
                case UacIL.High: preIndex = 1; break;

                case UacIL.UIAccess: uac = _SpUac.uiAccess; preIndex = 2; break;
                }
            }
            else
            {
                switch (IL)
                {
                case UacIL.Medium:
                case UacIL.UIAccess:
                    if (r.uac == EUac.admin)
                    {
                        uac = _SpUac.admin;
                    }
                    break;

                case UacIL.High:
                    if (r.uac == EUac.user)
                    {
                        uac = _SpUac.userFromAdmin;
                    }
                    break;

                case UacIL.Low:
                case UacIL.Untrusted:
                case UacIL.Unknown:
                //break;
                case UacIL.System:
                case UacIL.Protected:
                    AOutput.Write($"<>Cannot run {f.SciLink}. Meta comment option <c green>uac {r.uac}<> cannot be used when the UAC integrity level of this process is {IL}. Supported levels are Medium, High and uiAccess.");
                    return(0);
                    //info: cannot start Medium IL process from System process. Would need another function. Never mind.
                }
                if (r.uac == EUac.admin)
                {
                    preIndex = 1;
                }
            }
        }

        string     exeFile, argsString;
        _Preloaded pre = null; byte[] taskParams = null;
        bool       bit32 = r.prefer32bit || AVersion.Is32BitOS;

        if (r.notInCache)          //meta role exeProgram
        {
            exeFile    = Compiler.DllNameToAppHostExeName(r.file, bit32);
            argsString = args == null ? null : Au.Util.AStringUtil.CommandLineFromArray(args);
        }
        else
        {
            exeFile = AFolders.ThisAppBS + (bit32 ? "Au.Task32.exe" : "Au.Task.exe");

            //int iFlags = r.hasConfig ? 1 : 0;
            int iFlags = 0;
            if (r.mtaThread)
            {
                iFlags |= 2;
            }
            if (r.console)
            {
                iFlags |= 4;
            }
            taskParams = Au.Util.Serializer_.SerializeWithSize(r.name, r.file, r.pdbOffset, iFlags, args, r.fullPathRefs, wrPipeName, (string)AFolders.Workspace);
            wrPipeName = null;

            if (bit32 && !AVersion.Is32BitOS)
            {
                preIndex += 3;
            }
            pre        = s_preloaded[preIndex] ??= new _Preloaded(preIndex);
            argsString = pre.pipeName;
        }

        int pid; WaitHandle hProcess = null; bool disconnectPipe = false;

        try {
            //APerf.First();
            var pp = pre?.hProcess;
            if (pp != null && 0 != Api.WaitForSingleObject(pp.SafeWaitHandle.DangerousGetHandle(), 0))              //preloaded process exists
            {
                hProcess     = pp; pid = pre.pid;
                pre.hProcess = null; pre.pid = 0;
            }
            else
            {
                if (pp != null)
                {
                    pp.Dispose(); pre.hProcess = null; pre.pid = 0;
                }                                                                                  //preloaded process existed but somehow ended
                (pid, hProcess) = _StartProcess(uac, exeFile, argsString, wrPipeName);
            }
            Api.AllowSetForegroundWindow(pid);

            if (pre != null)
            {
                //APerf.First();
                var o = new Api.OVERLAPPED {
                    hEvent = pre.overlappedEvent
                };
                if (!Api.ConnectNamedPipe(pre.hPipe, &o))
                {
                    int e = ALastError.Code;
                    if (e != Api.ERROR_PIPE_CONNECTED)
                    {
                        if (e != Api.ERROR_IO_PENDING)
                        {
                            throw new AuException(e);
                        }
                        var ha = stackalloc IntPtr[2] {
                            pre.overlappedEvent, hProcess.SafeWaitHandle.DangerousGetHandle()
                        };
                        int wr = Api.WaitForMultipleObjectsEx(2, ha, false, -1, false);
                        if (wr != 0)
                        {
                            Api.CancelIo(pre.hPipe); throw new AuException("*start task. Preloaded task process ended");
                        }                                                                                                                                    //note: if fails when 32-bit process, rebuild solution with platform x86
                        disconnectPipe = true;
                        if (!Api.GetOverlappedResult(pre.hPipe, ref o, out _, false))
                        {
                            throw new AuException(0);
                        }
                    }
                }
                //APerf.Next();
                if (!Api.WriteFileArr(pre.hPipe, taskParams, out _))
                {
                    throw new AuException(0);
                }
                //APerf.Next();
                Api.DisconnectNamedPipe(pre.hPipe); disconnectPipe = false;
                //APerf.NW('e');

                //start preloaded process for next task. Let it wait for pipe connection.
                if (uac != _SpUac.admin)                  //we don't want second UAC consent
                {
                    try { (pre.pid, pre.hProcess) = _StartProcess(uac, exeFile, argsString, null); }
                    catch (Exception ex) { ADebug.Print(ex); }
                }
            }
        }
        catch (Exception ex) {
            AOutput.Write(ex);
            if (disconnectPipe)
            {
                Api.DisconnectNamedPipe(pre.hPipe);
            }
            hProcess?.Dispose();
            return(0);
        }

        var rt = new RunningTask(f, hProcess, r.runMode != ERunMode.green);

        _Add(rt);
        return(pid);
    }
コード例 #32
0
ファイル: Model.cs プロジェクト: azyobuzin/Azyotter
        public Task Post(string text, ulong? inReplyToStatusId, bool useFooter)
        {
            if (useFooter && !string.IsNullOrEmpty(Settings.Instance.Footer))
                text += " " + Settings.Instance.Footer;

            var cancellation = new CancellationTokenSource();
            RunningTask runningTask = null;

            var token = new Token()
            {
                ConsumerKey = Settings.Instance.ConsumerKey,
                ConsumerSecret = Settings.Instance.ConsumerSecret,
                OAuthToken = Settings.Instance.GetUsingAccount().OAuthToken,
                OAuthTokenSecret = Settings.Instance.GetUsingAccount().OAuthTokenSecret
            };

            var reTask = TwitterApi.Tweets.UpdateApi
                .Create(text, inReplyToStatusId)
                .CallApi(token, cancellation.Token)
                .ContinueWith(t =>
                {
                    RunningTasks.Instance.Remove(runningTask);

                    if (t.Exception == null)
                    {
                        TimelineItemCache.Instance.AddOrMergeTweet(t.Result, true);
                    }
                    else
                    {
                        //TODO:再試行できるようにする
                    }
                });

            runningTask = new RunningTask("投稿中:" + text, reTask, cancellation);
            RunningTasks.Instance.Add(runningTask);

            return reTask;
        }
コード例 #33
0
 public void Dispose()
 {
     RunningTask?.Dispose();
     CancellationTokenSource?.Dispose();
 }
コード例 #34
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Menu_Mouse_Down(object sender, RoutedEventArgs e)
        {
            FrameworkElement feSource = e.Source as FrameworkElement;

            switch (feSource.Name)
            {
            case "Connect":
                if (!init)
                {
                    Init_Connect_Window();
                }
                else
                {
                    portWindow.Visibility = Visibility.Visible;
                }
                break;

            case "Bluetooth":
                BluetoothWindow b_w = new BluetoothWindow(this);
                b_w.Show();
                break;

            case "Draw":
                if (tetris != null)
                {
                    tetris.Stop_Tetris();
                }
                if (video != null)
                {
                    video.RunVideo = false;
                }
                if (webcam != null)
                {
                    webcam.closeWebcam();
                }

                runningTask = RunningTask.Draw;
                drawAccept  = true;

                draw   = new Draw(drawlayer, monitorImg, monitor);
                ex_eff = draw.Draw_execute;


                draw.setColor    = Color.FromArgb(255, 0, 0, 255);
                draw.setDrawtype = Drawtype.rectangle;

                Binding ColorBinding = new Binding("setColor");
                ColorBinding.Source = draw;
                ColorBinding.Mode   = BindingMode.TwoWay;
                DrawingColorPicker.SetBinding(Xceed.Wpf.Toolkit.ColorCanvas.SelectedColorProperty, ColorBinding);

                break;

            case "Effects":
                if (tetris != null)
                {
                    tetris.Stop_Tetris();
                }
                if (video != null)
                {
                    video.RunVideo = false;
                }
                if (webcam != null)
                {
                    webcam.closeWebcam();
                }


                runningTask = RunningTask.Effect;
                drawAccept  = false;
                ex_eff      = plasma.Plasma_execute;

                monitorTimer.IsEnabled = true;

                break;

            case "Images":
                if (tetris != null)
                {
                    tetris.Stop_Tetris();
                    monitor           = BitmapFactory.New(68, 42);
                    monitorImg.Source = monitor;
                }
                if (webcam != null)
                {
                    webcam.closeWebcam();
                }
                if (video != null)
                {
                    video.RunVideo = false;
                }


                drawAccept        = false;
                monitorImg.Source = monitor;
                runningTask       = RunningTask.Image;

                ip     = new ImagePixelate(monitor);
                ex_eff = ip.execute;



                break;

            case "Video":
                if (tetris != null)
                {
                    tetris.Stop_Tetris();

                    monitorImg.Source = monitor;
                }
                if (webcam != null)
                {
                    webcam.closeWebcam();
                }
                runningTask = RunningTask.Video;

                CentralMonitor.IsEnabled = false;
                drawAccept = false;

                video  = new Video(monitor);
                ex_eff = video.video_execute;


                video.RunVideo = true;

                break;

            case "Tetris":

                if (webcam != null)
                {
                    webcam.closeWebcam();
                }
                if (video != null)
                {
                    video.RunVideo = false;
                }
                runningTask = RunningTask.Tetris;
                drawAccept  = false;


                if (tetris == null)
                {
                    tetris = new TetrisExecute(monitor, monitorTimer, AuroraWindow);
                    ex_eff = tetris.tetris_exe;
                }
                else
                {
                    tetris.Stop_Tetris();
                    tetris = new TetrisExecute(monitor, monitorTimer, AuroraWindow);
                    ex_eff = tetris.tetris_exe;
                }
                break;

            case "Webcam":
                runningTask = RunningTask.Webcam;
                CentralMonitor.IsEnabled = false;
                drawAccept = false;

                if (tetris != null)
                {
                    tetris.Stop_Tetris();
                }
                if (webcam == null)
                {
                    webcam = new Webcam(monitor);
                }
                if (video != null)
                {
                    video.RunVideo = false;
                }
                webcam.resumeWebcam(monitor);
                ex_eff = webcam.Webcam_execute;

                break;
            }
            SetUserControls();
        }
コード例 #35
0
        private void Bluetooth_Command_Listener(object sender, PropertyChangeArgs command)
        {
            try
            {
                int    Mode = -1;
                string comm = command.mesg;
                System.Diagnostics.Debug.WriteLine("Command wurde übergeben: " + comm);
                switch (comm)
                {
                case "Paint":             //Paint
                {
                    Mode = 0;
                    Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart) delegate
                        {
                            if (tetris != null)
                            {
                                tetris.Stop_Tetris();
                                monitor           = BitmapFactory.New(68, 42);
                                monitorImg.Source = monitor;
                            }

                            runningTask = RunningTask.Draw;
                            drawAccept  = true;
                            if (video != null)
                            {
                                video.RunVideo = false;
                            }
                            if (webcam != null)
                            {
                                webcam.closeWebcam();
                            }

                            try
                            {
                                draw = new Draw(drawlayer, monitorImg, monitor);
                            }
                            catch (Exception exc)
                            {
                            }
                            ex_eff = draw.Draw_execute;

                            draw.setColor    = Color.FromArgb(0, 200, 0, 255);
                            draw.setDrawtype = Drawtype.point;

                            Binding ColorBinding = new Binding("setColor");
                            ColorBinding.Source  = draw;
                            ColorBinding.Mode    = BindingMode.TwoWay;
                            DrawingColorPicker.SetBinding(Xceed.Wpf.Toolkit.ColorCanvas.SelectedColorProperty, ColorBinding);

                            SetUserControls();

                            //object GlassOfSugar = new  Object();
                            //Slider slider = new Slider();
                            //Binding AmountBinding = new Binding("Amount");
                            ////AmountBinding.Source = GlassOfSugar;
                            ////AmountBinding.Mode = BindingMode.TwoWay;
                            //slider.SetBinding(Slider.ValueProperty, AmountBinding);
                        });


                    break;
                }

                case "Fotobearbeitung":           //Pixelated Picture
                {
                    Mode = 1;

                    Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart) delegate
                        {
                            if (tetris != null)
                            {
                                tetris.Stop_Tetris();
                                monitor           = BitmapFactory.New(68, 42);
                                monitorImg.Source = monitor;
                            }

                            runningTask = RunningTask.Draw;
                            drawAccept  = true;
                            if (video != null)
                            {
                                video.RunVideo = false;
                            }
                            if (webcam != null)
                            {
                                webcam.closeWebcam();
                            }

                            try
                            {
                                draw = new Draw(drawlayer, monitorImg, monitor);
                            }
                            catch (Exception exc)
                            {
                            }
                            ex_eff = draw.Draw_execute;

                            draw.setColor    = Color.FromArgb(0, 200, 0, 255);
                            draw.setDrawtype = Drawtype.point;

                            Binding ColorBinding = new Binding("setColor");
                            ColorBinding.Source  = draw;
                            ColorBinding.Mode    = BindingMode.TwoWay;
                            DrawingColorPicker.SetBinding(Xceed.Wpf.Toolkit.ColorCanvas.SelectedColorProperty, ColorBinding);

                            SetUserControls();

                            //object GlassOfSugar = new Object();
                            //Slider slider = new Slider();
                            //Binding AmountBinding = new Binding("Amount");
                            //AmountBinding.Source = GlassOfSugar;
                            //AmountBinding.Mode = BindingMode.TwoWay;
                            //slider.SetBinding(Slider.ValueProperty, AmountBinding);
                        });

                    break;
                }

                case "Tetris":           //Tetris
                {
                    Mode = 2;

                    Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart) delegate
                        {
                            if (webcam != null)
                            {
                                webcam.closeWebcam();
                            }

                            runningTask = RunningTask.Tetris;
                            drawAccept  = false;
                            //Versuchsweise eingebaut -> dt_m.Tick ist fehlerquelle -.-  -> sollte eigentlich nicht sein
                            //dt_m.IsEnabled = false;

                            if (tetris == null)
                            {
                                monitor           = BitmapFactory.New(68, 42);
                                monitorImg.Source = monitor;
                                tetris            = new TetrisExecute(monitor, monitorTimer, AuroraWindow);
                                ex_eff            = tetris.tetris_exe;


                                Binding ScoreBinding = new Binding("Score");
                                ScoreBinding.Mode    = BindingMode.OneWay;
                                ScoreBinding.Source  = tetris.t;
                                Points.SetBinding(Label.ContentProperty, ScoreBinding);

                                Binding LevelBinding = new Binding("Level");
                                LevelBinding.Mode    = BindingMode.OneWay;
                                LevelBinding.Source  = tetris.t;
                                Level.SetBinding(Label.ContentProperty, LevelBinding);
                            }
                            else
                            {
                                tetris.Stop_Tetris();
                                tetris = new TetrisExecute(monitor, monitorTimer, AuroraWindow);
                                ex_eff = tetris.tetris_exe;

                                Binding ScoreBinding = new Binding("Score");
                                ScoreBinding.Mode    = BindingMode.TwoWay;
                                ScoreBinding.Source  = tetris.t;
                                Points.SetBinding(Label.ContentProperty, ScoreBinding);
                            }
                            SetUserControls();
                        });


                    break;
                }

                default:
                {
                    //hier wäre normalerweise ein switch(mode) -> unnötig?

                    break;
                }
                }
            }
            catch (Exception exc)
            {
            }
        }
コード例 #36
0
ファイル: Run.cs プロジェクト: alexfordc/Au
 /// <summary>
 /// Adds a started task to the 'running' list.
 /// Must be called in the main thread.
 /// </summary>
 /// <param name="rt"></param>
 void _Add(RunningTask rt)
 {
     Debug.Assert(!_disposed);
     _a.Insert(0, rt);
     _updateUI = true;
 }