public void TestMessageShowOnValidationPass()
        {
            // reset...
            MockViewModelHost.Current.Reset();

            // get the view model, passing in our mock host...
            ILogonPageViewModel model = ViewModelFactory.Current.GetHandler<ILogonPageViewModel>(MockViewModelHost.Current);

            // set the data...
            model.Username = "******";
            model.Password = "******";

            // create a task wrapper that can handle the success delegate from the model and patch it
            // into a local variable for testing... (this anonymous method simulates the success callback
            // from the event...)
            TaskWrapper wrapper = new TaskWrapper();

            // this call should work...
            model.LogonCommand.Execute(wrapper);

            // wait until it's finished executing...
            wrapper.WaitIfTaskAvailable();

            // check that we showed no error messages...
            Assert.AreEqual(0, MockViewModelHost.Current.NumErrorBucketMessages);
            Assert.IsNull(MockViewModelHost.Current.Fatal);
        }
Exemple #2
0
    public static ChainedTask DownloadMap2D(MapData map, bool showMap, bool showControls, ChainedTask chain = null)
    {
        TaskWrapper task = map.GetDownloadOverviewTask();

        if (chain == null)
        {
            chain = new ChainedTask(task);
        }
        else
        {
            chain.AddTask(task);
        }

        InvokeMapReady2D(map, showMap, showControls, chain);

        QueueTask(chain);

        return(chain);
    }
Exemple #3
0
    public static ChainedTask GenerateMatchInfo(MatchInfo match, bool load2DMap, bool load3DMap, bool showMap, bool showControls, ChainedTask chain = null)
    {
        TaskWrapper task = match.GetMakeMatchInfoTask();

        if (chain == null)
        {
            chain = new ChainedTask(task);
        }
        else
        {
            chain.AddTask(task);
        }

        GetMapLoadTask(match, load2DMap, load3DMap, showMap, showControls, chain);

        QueueTask(chain);

        return(chain);
    }
Exemple #4
0
        public async Task <DynValue> CallAsync(DynValue function, DynValue[] args)
        {
            List <Processor> coroutinesStack = m_Parent != null ? m_Parent.m_CoroutinesStack : this.m_CoroutinesStack;

            if (coroutinesStack.Count > 0 && coroutinesStack[coroutinesStack.Count - 1] != this)
            {
                return(coroutinesStack[coroutinesStack.Count - 1].Call(function, args));
            }

            EnterProcessor();

            try
            {
                var stopwatch = this.m_Script.PerformanceStats.StartStopwatch(Diagnostics.PerformanceCounter.Execution);

                m_CanYield = false;

                try
                {
                    m_SavedInstructionPtr = PushClrToScriptStackFrame(CallStackItemFlags.CallEntryPoint, function, args);
                    DynValue retval;
                    while ((retval = Processing_Loop(m_SavedInstructionPtr, true)).Type == DataType.AwaitRequest)
                    {
                        await retval.Task;
                        m_ValueStack.Push(TaskWrapper.TaskResultToDynValue(m_Script, retval.Task));
                    }
                    return(retval);
                }
                finally
                {
                    m_CanYield = true;

                    if (stopwatch != null)
                    {
                        stopwatch.Dispose();
                    }
                }
            }
            finally
            {
                LeaveProcessor();
            }
        }
Exemple #5
0
        public void CreateDailyTest()
        {
            Task task = TaskWrapper.CreateDaily("testDailyTask", "notepad.exe", null, null, DateTime.Now.TimeOfDay, 1);

            Assert.IsNotNull(task);
            Task found = TaskWrapper.Find("testDailyTask");

            Assert.IsNotNull(found);
            found.Run();
            if (found.State == TaskState.Running)
            {
                found.Stop();
            }
            TaskWrapper.Delete("testDailyTask");
            found = TaskWrapper.Find("testDailyTask");
            Assert.IsNull(found);

            task = TaskWrapper.CreateDaily("test", "clear_Ids_FALCON_TH.cmd", null, Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + @"\Black & Veatch\ScheduledTasks_FALCON_TH", DateTime.Now.TimeOfDay, 1);
        }
Exemple #6
0
    public static ChainedTask LoadMap(MapData map, bool showMap, bool showControls, ChainedTask chain = null)
    {
        TaskWrapper task = map.GetStartLoadMapTask();

        if (chain == null)
        {
            chain = new ChainedTask(task);
        }
        else
        {
            chain.AddTask(task);
        }

        InvokeMapReady3D(map, showMap, showControls, chain);

        QueueTask(chain);

        return(chain);
    }
        public TaskWrapper <OperationStatus <T> > TryPop( )
        {
            Func <OperationStatus <T> > deque = () =>
            {
                T returnedItem;

                bool isReturned = _Queue.TryDequeue(out returnedItem);

                if (isReturned)
                {
                    return(OperationStatusFactory.CreateSuccess <T>(returnedItem));
                }

                return(OperationStatusFactory.CreateError <T>(ErrorCode.NoDataReceived));
            };

            var sf = new SafeFunc <OperationStatus <T> >(deque, null);

            return(TaskWrapper <OperationStatus <T> > .Run(() => sf.SafeInvoke()));
        }
        public async Task <OperationResult> AddTaskAsync(TaskWrapper task, CancellationToken cancellationToken = default)
        {
            if (task == default)
            {
                return(OperationResult.Failure($"Входной параметр {nameof(task)} не может быть null"));
            }

            try
            {
                await _context.Tasks.AddAsync(_mapper.Map <Tasks>(task), cancellationToken);

                await _context.SaveChangesAsync(cancellationToken);

                return(OperationResult.Success());
            }
            catch (Exception ex)
            {
                return(OperationResult.Failure("При добавлении нового таска в БД, произошла ошибка", ex));
            }
        }
Exemple #9
0
        protected override void Init(Vector3 position, bool screenPosTrue)
        {
            base.Init(position, screenPosTrue);

            InitPreparation();

            if (screenPosTrue)
            {
                PlaceAtScreenPosition(position);
            }
            else
            {
                PlaceAtWorldPosition(position);
            }

            _associatedTaskWrapper = new TaskWrapper <MoveTask>(Task.CreateTask <MoveTask>());

            GetTask().SetTaskMarker(this);
            GetTask().SubscribeOnDestruction("taskmarkerclear", DestroyThis);
        }
Exemple #10
0
        public void CreateWeeklyTest()
        {
            Task task = TaskWrapper.CreateWeekly("testWeeklyTask", "notepad.exe", null, null, DateTime.Now,
                                                 (int)(DaysOfTheWeek.Monday | DaysOfTheWeek.Tuesday),
                                                 DateTime.Now.TimeOfDay,
                                                 1);

            Assert.IsNotNull(task);
            Task found = TaskWrapper.Find("testWeeklyTask");

            Assert.IsNotNull(found);
            found.Run();
            if (found.State == TaskState.Running)
            {
                found.Stop();
            }
            TaskWrapper.Delete("testWeeklyTask");
            found = TaskWrapper.Find("testWeeklyTask");
            Assert.IsNull(found);
        }
        public TaskWrapper SendSerialized(string deviceId, string jsonData)
        {
            TaskWrapper result = null;

            try
            {
                if (String.IsNullOrEmpty(jsonData))
                {
                    return(default(TaskWrapper));
                }

                result = PrepareAndSend(deviceId, jsonData);
            }
            catch (Exception ex)
            {
                Logger.LogError(_logMesagePrefix + ex.Message);
            }

            return(result);
        }
Exemple #12
0
        /// <summary>Publish several messages on this channel.</summary>
        public async Task <Result> PublishAsync(IEnumerable <Message> messages)
        {
            var tw = new TaskWrapper();

            try
            {
                PublishImpl(messages, tw.Callback);
            }
            catch (Exception ex)
            {
                tw.SetException(ex);
            }
            var result = await Task.WhenAny(Task.Delay(RealtimeClient.Options.RealtimeRequestTimeout), tw.Task);

            if (result == tw.Task)
            {
                return(tw.Task.Result);
            }
            return(Result.Fail(new ErrorInfo("PublishAsync timeout expired. Message was not confirmed by the server")));
        }
Exemple #13
0
    /// <summary>
    /// Remove the task from the list of entries.
    /// </summary>
    public void Remove()
    {
        this.Pause();

        TaskWrapper.Log(
            this,
            "Removing.",
            TaskWrapper.TaskWrapperLogType.Info);

        var entry = TaskWrapper.Entries.SingleOrDefault(n => n.Name == this.Name);

        if (entry == null)
        {
            return;
        }

        TaskWrapper.Entries.Remove(entry);

        this.Interval  = null;
        this.DateTimes = null;
    }
Exemple #14
0
        protected virtual void EventBatchProcessed(List <TaskWrapper> messages)
        {
            // test behaviours such as waiting for messages to be delivered or re-transmission

            if (messages == null || messages.Count == 0)
            {
                return;
            }

            foreach (TaskWrapper t in messages)
            {
                _logger.LogInfo(String.Format("task {0} status is '{1}'", t.Id, t.Status.ToString()));
            }

            TaskWrapper.BatchWaitAll(((List <TaskWrapper>)messages).ToArray());

            foreach (TaskWrapper t in messages)
            {
                _logger.LogInfo(String.Format("task {0} status is '{1}'", t.Id, t.Status.ToString()));
            }
        }
Exemple #15
0
        //--//

        public TaskWrapper SendMessage(T data)
        {
            Action <T> send = (d) =>
            {
                lock ( _sentMessages )
                {
                    if (_sentMessages.ContainsKey(d))
                    {
                        _sentMessages[d]++;
                    }
                    else
                    {
                        _sentMessages.Add(d, 1);
                    }
                }
            };

            var sh = new SafeAction <T>((d) => send(d), null);

            return(TaskWrapper.Run(() => sh.SafeInvoke(data)));
        }
        //private async Task AddDeviceAsync(AzureDevices.RegistryManager registryManager)
        //{
        //    AzureDevices.Device device;
        //    try
        //    {
        //        device = await registryManager.AddDeviceAsync(new AzureDevices.Device(DeviceName));
        //    }
        //    catch (Exception ex)
        //    {
        //        if (ex is Microsoft.Azure.Devices.Client.Exceptions.DeviceAlreadyExistsException
        //            || ex is Microsoft.Azure.Devices.Common.Exceptions.DeviceAlreadyExistsException)
        //        {
        //            device = await registryManager.GetDeviceAsync(DeviceName);

        //        }
        //        else
        //            throw;
        //    }

        //    deviceKey = device.Authentication.SymmetricKey.PrimaryKey;
        //}

        public TaskWrapper SendMessage(string deviceId, T data)
        {
            TaskWrapper result = null;

            try
            {
                if (data == null)
                {
                    return(default(TaskWrapper));
                }

                string jsonData = JsonConvert.SerializeObject(data);

                result = PrepareAndSend(deviceId, jsonData);
            }
            catch (Exception ex)
            {
                Logger.LogError(_logMesagePrefix + ex.Message);
            }

            return(result);
        }
Exemple #17
0
    public static ChainedTask DownloadMap3D(MapData map, bool readDependencies = false, bool downloadDependencies = false, bool loadMap = false, bool showMap = false, bool showControls = false, ChainedTask chain = null)
    {
        TaskWrapper task = null;

        task = map.GetDownloadMap3DTask(() =>
        {
            if (task != null && !task.cancelled && !chain.cancelled)
            {
                mapDownloaded3D?.Invoke(map);
            }
        });

        if (chain == null)
        {
            chain = new ChainedTask(task);
        }
        else
        {
            chain.AddTask(task);
        }

        if (readDependencies)
        {
            ReadMapDependencies(map, downloadDependencies, loadMap, showMap, showControls, chain);
        }
        else if (downloadDependencies)
        {
            DownloadMapDependencies(map, loadMap, showMap, showControls, chain);
        }
        else
        {
            LoadMap(map, showMap, showControls, chain);
        }

        QueueTask(chain);

        return(chain);
    }
        private void LogMessageReceived( )
        {
            int sent = Interlocked.Increment(ref _receivedMessages);

            if (sent == 1)
            {
                _start = DateTime.Now;
            }

            if (Interlocked.CompareExchange(ref _receivedMessages, 0, Constants.MessagesLoggingThreshold) == Constants.MessagesLoggingThreshold)
            {
                DateTime now = DateTime.Now;

                TimeSpan elapsed = (now - _start);

                _start = now;

                var sh = new SafeAction <String>(s => Logger.LogInfo(s), Logger);

                TaskWrapper.Run(() => sh.SafeInvoke(
                                    String.Format("GatewayService received {0} events succesfully in {1} ms ", Constants.MessagesLoggingThreshold, elapsed.TotalMilliseconds.ToString( ))));
            }
        }
Exemple #19
0
        public async Task <User> CheckPassword(SecureString password)
        {
            var passwordInfo = await GetPasswordInfo().ConfigureAwait(false);

            if (!passwordInfo.HasPassword)
            {
                throw new ArgumentException("the account does not have a password", nameof(passwordInfo));
            }

            var currentAlgo = passwordInfo.CurrentAlgo
                              ?? throw new ArgumentException("there is no CurrentAlgo", nameof(passwordInfo));
            var algo = currentAlgo
                       .Sha256Sha256Pbkdf2Hmacsha512Iter100000Sha256ModPow
                       ?? throw new ArgumentException("unknown CurrentAlgo", nameof(passwordInfo));

            var request = await TaskWrapper.Wrap(() =>
                                                 PasswordCheckHelper.GenRequest(passwordInfo, algo, password)
                                                 ).ConfigureAwait(false);

            var res = await _tg.Call(request).ConfigureAwait(false);

            return(SetAuthorized(res.Default !.User));
        }
Exemple #20
0
        public void ExecuteTask(
            Func <TaskResult> checker,
            Action completeHandler,
            Action successHandler,
            Action <int, string> failHandler,
            Action timeoutHandler,
            float timeout = 10)
        {
            var task = new TaskWrapper();

            task.StartTime       = Time.time;
            task.CheckTaskState  = new TaskResultChecker(checker);
            task.CompleteHandler = completeHandler;
            task.SuccessHandler  = successHandler;
            task.FailHandler     = failHandler;
            task.TimeoutHandler  = timeoutHandler;
            task.Timeout         = timeout;

            lock (_taskList)
            {
                _taskList.Add(task);
            }
        }
Exemple #21
0
    public static ChainedTask DownloadMatch(MatchInfo match, bool load2DMap, bool load3DMap, bool showMap, bool showControls, ChainedTask chain = null)
    {
        if (chain == null)
        {
            chain = new ChainedTask();
        }

        TaskWrapper task = match.GetDownloadTask((success) =>
        {
            if (!success)
            {
                chain.Cancel();
            }
        });

        chain.AddTask(task);

        GenerateMatchInfo(match, load2DMap, load3DMap, showMap, showControls, chain);

        QueueTask(chain);

        return(chain);
    }
        private TaskWrapper ToTaskWrapper(Task task)
        {
            var result = new TaskWrapper(task);

            if (task.CategoryID > 0)
            {
                result.Category = GetTaskCategoryByID(task.CategoryID);
            }

            if (task.ContactID > 0)
            {
                result.Contact = ToContactBaseWithEmailWrapper(DaoFactory.ContactDao.GetByID(task.ContactID));
            }

            if (task.EntityID > 0)
            {
                result.Entity = ToEntityWrapper(task.EntityType, task.EntityID);
            }

            result.CanEdit = CRMSecurity.CanEdit(task);

            return(result);
        }
Exemple #23
0
    public static ChainedTask InvokeMapReady3D(MapData map, bool showMap, bool showControls, ChainedTask chain = null)
    {
        TaskWrapper task = TaskManagerController.CreateTask((cts) =>
        {
            if (!chain.cancelled)
            {
                mapReady3D?.Invoke(map, showMap, showControls);
            }
        });

        if (chain == null)
        {
            chain = new ChainedTask(task);
        }
        else
        {
            chain.AddTask(task);
        }

        QueueTask(chain);

        return(chain);
    }
Exemple #24
0
        internal Task UpdatePresenceAsync(PresenceMessage msg)
        {
            if ((_channel.State == ChannelState.Initialized) || (_channel.State == ChannelState.Attaching))
            {
                if (_channel.State == ChannelState.Initialized)
                {
                    _channel.Attach();
                }

                var tw = new TaskWrapper();
                _pendingPresence.Add(new QueuedPresenceMessage(msg, tw.Callback));
                return(tw.Task);
            }
            if (_channel.State == ChannelState.Attached)
            {
                var message = new ProtocolMessage(ProtocolMessage.MessageAction.Presence, _channel.Name);
                message.Presence = new[] { msg };
                _connection.Send(message, null);
                //TODO: Fix this;
                return(TaskConstants.BooleanTrue);
            }
            throw new AblyException("Unable to enter presence channel in detached or failed state", 91001,
                                    HttpStatusCode.BadRequest);
        }
Exemple #25
0
        public virtual bool Run(Action <ScheduledTask, DateTimeOffset> actionToRun, bool autoRun = true)
        {
            try
            {
                string message = $"{Name} is started.";
                WorkerLogger.Info(message);
                Store(message);

                ScheduledTask = _schtick.AddAsyncTask(Name, WorkerSettings.SchedulePattern,
                                                      TaskWrapper.WrapAsync(async(task, timeIntendedToRun) =>
                                                                            await Task.Run(() =>
                {
                    Store($"{Name} - execution has started at {DateTime.Now}");
                    OnTaskEnter?.Invoke(this, new WorkerEventArgs());

                    actionToRun?.Invoke(task, timeIntendedToRun);

                    OnTaskExit?.Invoke(this, new WorkerEventArgs());
                    Store($"{Name} - execution has completed at {DateTime.Now}");
                }).ConfigureAwait(false))
                                                      , autoRun);

                ScheduledTask.OnException += ScheduledTask_OnException;

                OnStarted?.Invoke(this, new WorkerStartedEventArgs());

                return(true);
            }
            catch (Exception exception)
            {
                string details = $"An error occurrred while executing {Name}";
                WorkerLogger.Error(details, exception);
                Store($"{details}, Exception = {exception.Message}");
                return(false);
            }
        }
Exemple #26
0
        private void AddToProcessed(List <TaskWrapper> tasks, TaskWrapper <OperationStatus <TQueueItem> > t)
        {
            try
            {
                tasks.Add(t);
            }
            catch (StackOverflowException)// do not hide stack overflow exceptions
            {
                throw;
            }
            catch (OutOfMemoryException) // do not hide memory exceptions
            {
                throw;
            }
            catch (Exception ex) // catch all other exceptions
            {
                Logger.LogError("Exception on adding task: " + ex.Message);

                // TODO
                // If we are here, the task that has been popped could not be added to the list
                // of tasks that the client will be notifed about
                // This does not mean that the task has not been processed though
            }
        }
Exemple #27
0
 public Task <T> Call <T>(ITgFunc <T> func) =>
 TaskWrapper.Wrap(() => CallWithMigration(func));
        public void TestNavigateToLogonOnSuccess()
        {
            // reset...
            MockViewModelHost.Current.Reset();

            // get the view model, passing in our mock host...
            ILogonPageViewModel model = ViewModelFactory.Current.GetHandler<ILogonPageViewModel>(MockViewModelHost.Current);

            // set the data...
            model.Username = "******";
            model.Password = "******";

            // this call should work...
            TaskWrapper wrapper = new TaskWrapper();
            model.LogonCommand.Execute(wrapper);

            // wait until it's finished executing...
            wrapper.WaitIfTaskAvailable();

            // check that we did navigate to the logon page...
            Assert.AreEqual(1, MockViewModelHost.Current.NumPageChanges);
            Assert.AreEqual(typeof(ILogonPageViewModel), MockViewModelHost.Current.LastPageChange);
        }
        public void TestRegistrationPageNavigation()
        {
            // reset...
            MockViewModelHost.Current.Reset();

            // get the view model, passing in our mock host...
            ILogonPageViewModel model = ViewModelFactory.Current.GetHandler<ILogonPageViewModel>(MockViewModelHost.Current);

            // this call should work...
            TaskWrapper wrapper = new TaskWrapper();
            model.RegisterCommand.Execute(wrapper);

            // wait until it's finished executing...
            wrapper.WaitIfTaskAvailable();

            // check that we did navigate to the logon page...
            Assert.AreEqual(1, MockViewModelHost.Current.NumPageChanges);
            Assert.AreEqual(typeof(IRegisterPageViewModel), MockViewModelHost.Current.LastPageChange);
        }
		/// <summary>
		/// Returns a full C# syntax tree resolver which is shared between semantic highlighting, source analysis and refactoring.
		/// For code analysis tasks this should be used instead of generating an own resolver. Only exception is if a local resolving is done using a 
		/// resolve navigator.
		/// Note: The shared resolver is fully resolved.
		/// </summary>
		public static TaskWrapper GetSharedResolver (this Document document)
		{
			var parsedDocument = document.ParsedDocument;
			if (parsedDocument == null || document.IsProjectContextInUpdate)
				return null;

			var unit       = parsedDocument.GetAst<SyntaxTree> ();
			var parsedFile = parsedDocument.ParsedFile as CSharpUnresolvedFile;
			if (unit == null || parsedFile == null)
				return null;
			var compilation = document.Compilation;

			var resolverAnnotation = document.Annotation<ResolverAnnotation> ();

			if (resolverAnnotation != null) {
				if (resolverAnnotation.ParsedFile == parsedFile)
					return resolverAnnotation.Task;
				if (resolverAnnotation.SharedTokenSource != null)
					resolverAnnotation.SharedTokenSource.Cancel ();
				document.RemoveAnnotations<ResolverAnnotation> ();
			}

			var tokenSource = new CancellationTokenSource ();
			var token = tokenSource.Token;
			var resolveTask = Task.Factory.StartNew (delegate {
				try {
					using (var timer = ResolveCounter.BeginTiming ()) {
						var result = new CSharpAstResolver (compilation, unit, parsedFile);
						result.ApplyNavigator (new ConstantModeResolveVisitorNavigator (ResolveVisitorNavigationMode.Resolve, null), token);
						return result;
					}
				} catch (OperationCanceledException) {
					return null;
				} catch (Exception e) {
					LoggingService.LogError ("Error while creating the resolver.", e);
					return null;
				}
			}, token);
			var wrapper = new TaskWrapper (resolveTask);
			document.AddAnnotation (new ResolverAnnotation {
				Task = wrapper,
				ParsedFile = parsedFile,
				SharedTokenSource = tokenSource
			});
			return wrapper;
		}
Exemple #31
0
        private void ThreadJob()
        {
            // signal that the worker thread has actually started processing the events
            _operational.Set();

            try
            {
                const int WAIT_TIMEOUT = 50; // milliseconds

                // run until Stop() is called
                while (_running == true)
                {
                    try
                    {
                        // If there are no tasks to be served, wait for some events to process
                        // Use a timeout to prevent race conditions on the outstanding tasks count
                        // and the actual queue count
                        _doWork.WaitOne(WAIT_TIMEOUT);

                        _logger.Flush();

                        // Fish from the queue and accumulate, keep track of outstanding tasks to
                        // avoid accumulating too many competing tasks. Note that we are going to schedule
                        // one more tasks than strictly needed, so that we prevent tasks to sit in the queue
                        // because of the race condition on the outstanding task count (_outstandingTasks)
                        // and the tasks actually sitting in the queue.  (*)
                        // To prevent this race condition, we will wait with a timeout
                        int count = _dataSource.Count - _outstandingTasks;

                        if (count == 0)
                        {
                            continue;
                        }

                        // check if we have been woken up to actually stop processing
                        EventBatchProcessedEventHandler eventBatchProcessed = null;

                        lock (_syncRoot)
                        {
                            if (_running == false)
                            {
                                return;
                            }

                            // take a snapshot of event handlers to invoke
                            eventBatchProcessed = OnEventsBatchProcessed;
                        }

                        // allocate a container to keep track of tasks for events in the queue
                        var tasks = new List <TaskWrapper>();

                        // process all messages that have not been processed yet
                        while (--count >= 0)
                        {
                            TaskWrapper <OperationStatus <TQueueItem> > t = null;

                            try
                            {
                                t = _dataSource.TryPop();
                            }
                            catch
                            {
                                Interlocked.Decrement(ref _outstandingTasks);

                                continue;
                            }

                            // increment outstanding task count
                            Interlocked.Increment(ref _outstandingTasks);

                            t.ContinueWith <TaskWrapper>(popped =>
                            {
                                // Decrement the numbers of outstanding tasks.
                                // (*) Note that there is a race  condition because at this point in time the tasks
                                // is already out of the queue but we did not decrement the outstanding task count
                                // yet. This race condition may cause tasks to be left sitting in the queue.
                                // To deal with this race condition, we will wait with a timeout
                                Interlocked.Decrement(ref _outstandingTasks);

                                // because the outstanding task counter is incremented before
                                // adding, we should never incur a negative count
                                Debug.Assert(_outstandingTasks >= 0);

                                if (popped?.Result != null && popped.Result.IsSuccess)
                                {
                                    return(_dataTarget.SendMessage(popped.Result.Result.GetDeviceId(), popped.Result.Result));
                                }

                                return(null);
                            });

                            AddToProcessed(tasks, t);
                        }

                        // alert any client about outstanding message tasks
                        if (eventBatchProcessed != null)
                        {
                            var sh = new SafeAction <List <TaskWrapper> >(allScheduledTasks => eventBatchProcessed(allScheduledTasks), Logger);

                            TaskWrapper.Run(() => sh.SafeInvoke(tasks));
                        }
                    }
                    catch (StackOverflowException ex) // do not hide stack overflow exceptions
                    {
                        Logger.LogError(_logMessagePrefix + ex.Message);
                        throw;
                    }
                    catch (OutOfMemoryException ex) // do not hide memory exceptions
                    {
                        Logger.LogError(_logMessagePrefix + ex.Message);
                        throw;
                    }
                    catch (Exception ex) // catch all other exceptions
                    {
                        Logger.LogError(_logMessagePrefix + ex.Message);
                    }
                }
            }
            finally
            {
                _operational.Set();
            }
        }
Exemple #32
0
 public bool Contains(TaskWrapper task)
 {
     return(allTasks.Contains(task));
 }
 public HttpDownloader()
 {
     _tw = new TaskWrapper("HttpDownloader", Runner, TaskCreationOptions.LongRunning);
 }
Exemple #34
0
        /// <summary>
        /// Instance constructor.  This is called only once by one of the calls from my static constructor.
        /// </summary>
        private NeuralPool()
        {
            _lockInstance = new object();

            // Take a rough guess at how many to create
            int numTasks = Convert.ToInt32(Math.Floor(Environment.ProcessorCount * .5d));
            if (numTasks < 1)
            {
                numTasks = 1;
            }

            _itemsByToken = new SortedList<long, Tuple<NeuralBucket, TaskWrapper>>();

            // Create the tasks
            _tasks = new TaskWrapper[numTasks];
            for (int cntr = 0; cntr < numTasks; cntr++)
            {
                _tasks[cntr] = new TaskWrapper();
            }
        }
            private static void Run(TaskWrapper parent, CancellationToken cancel, Color background)
            {
                //NOTE: This method is running on an arbitrary thread
                try
                {
                    //  Create viewport
                    ViewportOffline viewport = new ViewportOffline(background);

                    List<ICameraPoolCamera> cameras = new List<ICameraPoolCamera>();

                    while (!cancel.IsCancellationRequested)
                    {
                        // Add/Remove items
                        AddRemoveItems(parent, viewport, cameras);

                        if (cameras.Count == 0)
                        {
                            // Hang out for a bit, then try again.  No need to burn up the processor
                            //TODO: UseAutoResetEvent (triggered by another thread in CameraPool.Add())
                            //http://stackoverflow.com/questions/382173/what-are-alternative-ways-to-suspend-and-resume-a-thread
                            Thread.Sleep(450 + StaticRandom.Next(100));
                            continue;
                        }

                        MoveVisuals(viewport);

                        #region Take pictures

                        //TODO: If it takes a long time to get through these cameras, then maybe the visuals should be moved after every couple cameras
                        foreach (ICameraPoolCamera camera in cameras)
                        {
                            if (cancel.IsCancellationRequested)
                            {
                                return;
                            }

                            if (camera.IsOn)
                            {
                                var location = camera.GetWorldLocation_Camera();

                                IBitmapCustom bitmap = viewport.GetSnapshot(location.Item1, location.Item2.Standard, location.Item2.Orth, camera.PixelWidthHeight);

                                camera.StoreSnapshot(bitmap);
                            }
                        }

                        #endregion

                        Thread.Sleep(0);		// not sure if this is useful or not
                        //Thread.Yield();
                    }
                }
                catch (Exception)
                {
                    // Don't leak errors, just go away
                }
            }
            //private static void AddRemoveVisuals(TaskWrapper parent, ViewportOffline viewport)
            //{
            //    #region Removes

            //    CameraPoolVisual visual;
            //    while (parent.RemoveVisuals.TryDequeue(out visual))
            //    {
            //        viewport.Viewport.Children.Remove(viewport.Visuals[visual.Token].Item2);
            //        viewport.Visuals.Remove(visual.Token);
            //    }

            //    #endregion
            //    #region Adds

            //    while (parent.AddVisuals.TryDequeue(out visual))
            //    {
            //        //  Deserialize into an instance that is specific to this thread
            //        Model3D model;
            //        using (MemoryStream stream = new MemoryStream(visual.Model3D))
            //        {
            //            model = XamlServices.Load(stream) as Model3D;
            //        }

            //        //  Create a visual to hold it (no need to set the transform here, that will be done each frame)
            //        ModelVisual3D modelVisual = new ModelVisual3D();
            //        modelVisual.Content = model;

            //        //  Store it
            //        viewport.Viewport.Children.Add(modelVisual);
            //        viewport.Visuals.Add(visual.Token, Tuple.Create(visual, (Visual3D)modelVisual));
            //    }

            //    #endregion
            //}
            //private static void AddRemoveCameras(TaskWrapper parent, List<ICameraPoolCamera> cameras)
            //{
            //    bool hadChange = false;

            //    //  Removes
            //    ICameraPoolCamera camera;
            //    while (parent.RemoveCameras.TryDequeue(out camera))
            //    {
            //        cameras.Remove(camera);
            //        hadChange = true;
            //    }

            //    //  Adds
            //    while (parent.AddCameras.TryDequeue(out camera))
            //    {
            //        cameras.Add(camera);
            //        hadChange = true;
            //    }

            //    // Store the new count
            //    if (hadChange)
            //    {
            //        parent._count = cameras.Count;
            //    }
            //}

            private static void AddRemoveItems(TaskWrapper parent, ViewportOffline viewport, List<ICameraPoolCamera> cameras)
            {
                bool numCamerasChanged = false;

                Tuple<object, bool> item;
                while (parent.AddRemoves.TryDequeue(out item))
                {
                    if (item.Item1 is CameraPoolVisual)
                    {
                        CameraPoolVisual visual = (CameraPoolVisual)item.Item1;

                        if (item.Item2)
                        {
                            #region Add Visual

                            //  Deserialize into an instance that is specific to this thread
                            Model3D model;
                            using (MemoryStream stream = new MemoryStream(visual.Model3D))
                            {
                                model = XamlServices.Load(stream) as Model3D;
                            }

                            //  Create a visual to hold it (no need to set the transform here, that will be done each frame)
                            ModelVisual3D modelVisual = new ModelVisual3D();
                            modelVisual.Content = model;

                            //  Store it
                            viewport.Viewport.Children.Add(modelVisual);
                            viewport.Visuals.Add(visual.Token, Tuple.Create(visual, (Visual3D)modelVisual));

                            #endregion
                        }
                        else
                        {
                            #region Remove Visual

                            viewport.Viewport.Children.Remove(viewport.Visuals[visual.Token].Item2);
                            viewport.Visuals.Remove(visual.Token);

                            #endregion
                        }
                    }
                    else if (item.Item1 is ICameraPoolCamera)
                    {
                        ICameraPoolCamera camera = (ICameraPoolCamera)item.Item1;
                        numCamerasChanged = true;

                        if (item.Item2)
                        {
                            #region Add Camera

                            cameras.Add(camera);

                            #endregion
                        }
                        else
                        {
                            #region Remove Camera

                            cameras.Remove(camera);

                            #endregion
                        }
                    }
                    else
                    {
                        throw new ApplicationException("Unknown type of item: " + item.Item1.GetType().ToString());
                    }
                }

                // Store the new count
                if (numCamerasChanged)
                {
                    parent._count = cameras.Count;
                }
            }
        private void HandleFaultTask(TaskWrapper taskWrapper)
        {
            lock (_inProcessList)
            {
                _inProcessList.Remove(taskWrapper.LinkedListNode);
            }

            taskWrapper.Task.Exception?.Flatten().Handle(ex =>
            {
                Console.WriteLine("Action {0} throws an exception: {1}", taskWrapper.Name, ex.Message);
                return true;
            });

            PlaceNextToInProcess();
        }
        public Task Queue(Action action, string name = null)
        {
            TaskWrapper taskWrapper;
            lock (_queue)
            {
                if (_queue.Count >= QueueMaxLenght)
                {
                    Console.WriteLine("Queue is full, can't add.");
                    return null;
                }

                taskWrapper = new TaskWrapper()
                {
                    Action = action,
                    Name = name,
                    Task = new Task(action)
                };

                taskWrapper.Task.ContinueWith(taskWrapper.OnCompleted, TaskContinuationOptions.OnlyOnRanToCompletion);
                taskWrapper.Task.ContinueWith(taskWrapper.OnFault, TaskContinuationOptions.OnlyOnFaulted);

                //TaskAwaiter awaiter = taskWrapper.Task.GetAwaiter();
                //awaiter.OnCompleted(taskWrapper.OnCompleted);

                long counter = Interlocked.Increment(ref _counterQueued);
                taskWrapper.Name = counter.ToString();
                _queue.Enqueue(taskWrapper);

                Console.WriteLine("Action {0} was added. \tIn Queue: {1}\tIn Process: {2}",
                    taskWrapper.Name, _queue.Count, _inProcessList.Count);
            }

            PlaceNextToInProcess();

            return taskWrapper.Task;
        }
        private void RemoveEndedTask(TaskWrapper taskWrapper)
        {
            lock (_inProcessList)
            {
                _timesFromStartProcessing.Add(taskWrapper.Stopwatch.Elapsed);
                _inProcessList.Remove(taskWrapper.LinkedListNode);

                Interlocked.Increment(ref _counterExecuted);

                Console.WriteLine("Action {0} was ended. \tIn Queue: {1}\tIn Process: {2}", taskWrapper.Name, _queue.Count, _inProcessList.Count);
            }

            PlaceNextToInProcess();
        }
        private IEnumerable <TaskWrapper> ToTaskListWrapper(IEnumerable <Task> itemList)
        {
            var result = new List <TaskWrapper>();

            var contactIDs        = new List <int>();
            var taskIDs           = new List <int>();
            var categoryIDs       = new List <int>();
            var entityWrappersIDs = new Dictionary <EntityType, List <int> >();

            foreach (var item in itemList)
            {
                taskIDs.Add(item.ID);

                if (!categoryIDs.Contains(item.CategoryID))
                {
                    categoryIDs.Add(item.CategoryID);
                }

                if (item.ContactID > 0 && !contactIDs.Contains(item.ContactID))
                {
                    contactIDs.Add(item.ContactID);
                }

                if (item.EntityID > 0)
                {
                    if (item.EntityType != EntityType.Opportunity && item.EntityType != EntityType.Case)
                    {
                        continue;
                    }

                    if (!entityWrappersIDs.ContainsKey(item.EntityType))
                    {
                        entityWrappersIDs.Add(item.EntityType, new List <int>
                        {
                            item.EntityID
                        });
                    }
                    else if (!entityWrappersIDs[item.EntityType].Contains(item.EntityID))
                    {
                        entityWrappersIDs[item.EntityType].Add(item.EntityID);
                    }
                }
            }

            var entityWrappers = new Dictionary <string, EntityWrapper>();

            foreach (var entityType in entityWrappersIDs.Keys)
            {
                switch (entityType)
                {
                case EntityType.Opportunity:
                    DaoFactory.DealDao.GetDeals(entityWrappersIDs[entityType].Distinct().ToArray())
                    .ForEach(item =>
                    {
                        if (item == null)
                        {
                            return;
                        }

                        entityWrappers.Add(
                            string.Format("{0}_{1}", (int)entityType, item.ID),
                            new EntityWrapper
                        {
                            EntityId    = item.ID,
                            EntityTitle = item.Title,
                            EntityType  = "opportunity"
                        });
                    });
                    break;

                case EntityType.Case:
                    DaoFactory.CasesDao.GetByID(entityWrappersIDs[entityType].ToArray())
                    .ForEach(item =>
                    {
                        if (item == null)
                        {
                            return;
                        }

                        entityWrappers.Add(
                            string.Format("{0}_{1}", (int)entityType, item.ID),
                            new EntityWrapper
                        {
                            EntityId    = item.ID,
                            EntityTitle = item.Title,
                            EntityType  = "case"
                        });
                    });
                    break;
                }
            }

            var categories         = DaoFactory.ListItemDao.GetItems(categoryIDs.ToArray()).ToDictionary(x => x.ID, x => new TaskCategoryBaseWrapper(x));
            var contacts           = DaoFactory.ContactDao.GetContacts(contactIDs.ToArray()).ToDictionary(item => item.ID, ToContactBaseWithEmailWrapper);
            var restrictedContacts = DaoFactory.ContactDao.GetRestrictedContacts(contactIDs.ToArray()).ToDictionary(item => item.ID, ToContactBaseWithEmailWrapper);



            foreach (var item in itemList)
            {
                var taskWrapper = new TaskWrapper(item)
                {
                    CanEdit = CRMSecurity.CanEdit(item)
                };

                if (contacts.ContainsKey(item.ContactID))
                {
                    taskWrapper.Contact = contacts[item.ContactID];
                }
                if (restrictedContacts.ContainsKey(item.ContactID))
                {
                    taskWrapper.Contact = restrictedContacts[item.ContactID];
                    /*Hide some fields. Should be refactored! */
                    taskWrapper.Contact.Currency   = null;
                    taskWrapper.Contact.Email      = null;
                    taskWrapper.Contact.AccessList = null;
                }

                if (item.EntityID > 0)
                {
                    var entityStrKey = string.Format("{0}_{1}", (int)item.EntityType, item.EntityID);

                    if (entityWrappers.ContainsKey(entityStrKey))
                    {
                        taskWrapper.Entity = entityWrappers[entityStrKey];
                    }
                }

                if (categories.ContainsKey(item.CategoryID))
                {
                    taskWrapper.Category = categories[item.CategoryID];
                }

                result.Add(taskWrapper);
            }

            return(result);
        }
        public void TestCallbackRaisedOnSuccess()
        {
            // reset...
            MockViewModelHost.Current.Reset();

            // get the view model, passing in our mock host...
            ILogonPageViewModel model = ViewModelFactory.Current.GetHandler<ILogonPageViewModel>(MockViewModelHost.Current);

            // set the data...
            model.Username = "******";
            model.Password = "******";

            // create a task wrapper that can handle the success delegate from the model and patch it
            // into a local variable for testing... (this anonymous method simulates the success callback
            // from the event...)
            LogonResult result = null;
            TaskWrapper wrapper = new TaskWrapper((theResult) => result = (LogonResult)theResult);

            // this call should work...
            model.LogonCommand.Execute(wrapper);

            // wait until it's finished executing...
            wrapper.WaitIfTaskAvailable();

            // check that we called the callback...
            Assert.IsTrue(wrapper.SuccessCalled);

            // check that we got a token in the result...
            Assert.IsFalse(string.IsNullOrEmpty(result.Token));
        }
Exemple #42
0
            private static void Run(TaskWrapper parent, CancellationToken cancel)
            {
                //NOTE: This method is running on an arbitrary thread
                try
                {
                    List<NeuralBucket> buckets = new List<NeuralBucket>();

                    while (!cancel.IsCancellationRequested)
                    {
                        #region Add/Remove buckets

                        bool wasListChanged = false;

                        Tuple<NeuralBucket, bool> bucket;
                        while (parent.AddRemoves.TryDequeue(out bucket))
                        {
                            if (bucket.Item2)
                            {
                                buckets.Add(bucket.Item1);
                            }
                            else
                            {
                                buckets.Remove(bucket.Item1);
                            }

                            wasListChanged = true;
                        }

                        // Store the new count
                        if (wasListChanged)
                        {
                            parent._count = buckets.Sum(o => o.Count);
                        }

                        #endregion

                        if (buckets.Count == 0)
                        {
                            // Hang out for a bit, then try again.  No need to burn up the processor
                            Thread.Sleep(450 + StaticRandom.Next(100));
                            continue;
                        }

                        #region Process buckets

                        foreach (NeuralBucket bucket2 in buckets)
                        {
                            bucket2.Tick();
                        }

                        #endregion

                        Thread.Sleep(0);		// not sure if this is useful or not
                        //Thread.Yield();
                    }
                }
                catch (Exception)
                {
                    // Don't leak errors, just go away
                }
            }
        public CameraPool(int numThreads, Color background)
        {
            _staScheduler = new StaTaskScheduler(numThreads);

            _tasks = new TaskWrapper[numThreads];
            for (int cntr = 0; cntr < numThreads; cntr++)
            {
                _tasks[cntr] = new TaskWrapper(_staScheduler, background);
            }
        }