Inheritance: Item
        /// <summary>
        /// Initializes a new instance of the <see cref="AsynchronousTraceListenerWrapper" /> class.
        /// </summary>
        /// <param name="wrappedTraceListener">The wrapped trace listener.</param>
        /// <param name="ownsWrappedTraceListener">Indicates whether the wrapper should dispose the wrapped trace listener.</param>
        /// <param name="bufferSize">Size of the buffer for asynchronous requests.</param>
        /// <param name="maxDegreeOfParallelism">The max degree of parallelism for thread safe listeners. Specify <see langword="null"/> to use the current core count.</param>
        /// <param name="disposeTimeout">The timeout for waiting to complete buffered requests when disposing. When <see langword="null" /> the default of <see cref="Timeout.InfiniteTimeSpan" /> is used.</param>
        public AsynchronousTraceListenerWrapper(
            TraceListener wrappedTraceListener,
            bool ownsWrappedTraceListener = true,
            int? bufferSize = DefaultBufferSize,
            int? maxDegreeOfParallelism = null,
            TimeSpan? disposeTimeout = null)
        {
            Guard.ArgumentNotNull(wrappedTraceListener, "wrappedTraceListener");
            CheckBufferSize(bufferSize);
            CheckMaxDegreeOfParallelism(maxDegreeOfParallelism);
            CheckDisposeTimeout(disposeTimeout);

            this.wrappedTraceListener = wrappedTraceListener;
            this.ownsWrappedTraceListener = ownsWrappedTraceListener;
            this.disposeTimeout = disposeTimeout ?? Timeout.InfiniteTimeSpan;

            this.closeSource = new CancellationTokenSource();
            this.requests = bufferSize != null ? new BlockingCollection<Action<TraceListener>>(bufferSize.Value) : new BlockingCollection<Action<TraceListener>>();

            if (this.wrappedTraceListener.IsThreadSafe)
            {
                this.maxDegreeOfParallelism = maxDegreeOfParallelism.HasValue ? maxDegreeOfParallelism.Value : Environment.ProcessorCount;
                this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequestsInParallel, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
            else
            {
                this.asyncProcessingTask = Task.Factory.StartNew(this.ProcessRequests, CancellationToken.None, TaskCreationOptions.HideScheduler | TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
        }
Exemplo n.º 2
1
        public CommandProcessor(ICommandProcessingStrategy processingStrategy,
                                ICommandQueue commandQueue)
        {
            _processingStrategy = processingStrategy;
            _commandQueue = commandQueue;

            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;
            var task = new Task(
                () =>
                    {
                        while (!token.IsCancellationRequested)
                        {
                            var cmd = _commandQueue.Dequeue();
                            while (cmd != null)
                            {
                                _processingStrategy.ProcessCommand(cmd.Execute);
                                cmd = commandQueue.Dequeue();
                            }
                            Thread.Sleep(100);
                        }
                    },
                token,
                TaskCreationOptions.LongRunning);
            task.Start();
        }
Exemplo n.º 3
1
        public static IYubicoResponse Validate(IEnumerable<string> urls, string userAgent)
        {
            var tasks = new List<Task<IYubicoResponse>>();
            var cancellation = new CancellationTokenSource();

            foreach (var url in urls)
            {
                var thisUrl = url;
                var task = new Task<IYubicoResponse>(() => DoVerify(thisUrl, userAgent), cancellation.Token);
                task.ContinueWith(t => { }, TaskContinuationOptions.OnlyOnFaulted);
                tasks.Add(task);
                task.Start();
            }

            while (tasks.Count != 0)
            {
                // TODO: handle exceptions from the verify task. Better to be able to propagate cause for error.
                var completed = Task.WaitAny(tasks.Cast<Task>().ToArray());
                var task = tasks[completed];
                tasks.Remove(task);
                if (task.Result != null)
                {
                    cancellation.Cancel();
                    return task.Result;
                }
            }

            return null;
        }
        public void Start()
        {
            _source = new CancellationTokenSource();
            var token = _source.Token;
            _listenerTask = new Task(() =>
            {
                BusListener.MessageReceivedEvent += (s, e) => Console.WriteLine("Received message at " + e.Endpoint + " of type " + e.MessageType);
                BusListener.MessageSentEvent += (s, e) => Console.WriteLine("Sent message " + e.MessageType);
                BusListener.BusStartedEvent += (s, e) => Console.WriteLine("Bus started " + e.Endpoint);
                BusListener.MessageExceptionEvent += (s, e) => Console.WriteLine("Exception with message " + e.Endpoint + " for type " + e.MessageType + " with value " + e.Exception);
                using (var host = new ServiceHost(_listener, new[] { new Uri("net.tcp://localhost:5050") }))
                {

                    host.AddServiceEndpoint(typeof(IBusListener), new NetTcpBinding(), "NServiceBus.Diagnostics");

                    host.Opened += (s, e) => Console.WriteLine("Listening for events...");
                    host.Closed += (s, e) => Console.WriteLine("Closed listening for events...");

                    host.Open();

                    while (!token.IsCancellationRequested) { }

                    host.Close();
                }
            }, token);

            _listenerTask.Start();
            _listenerTask.Wait(10000);

        }
        private async Task Polling()
        {
            while (true)
            {
                try
                {
                    if (cancellationToken.IsCancellationRequested)
                        break;

                    var list = sources;
                    var tasks = new Task<IDictionary<string,object>>[list.Count];
                    for (int i = 0; i < list.Count; i++)
                    {
                        tasks[i] = list[i].LoadProperties(cancellationToken.Token);
                    }

                    if(!Task.WaitAll(tasks, sourceTimeoutInMs, cancellationToken.Token))
                    {
                        // log : one task is timeout
                    }

                    LoadPropertiesFromSources(tasks);

                    await Task.Delay(PollingIntervalInSeconds*1000, cancellationToken.Token);
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                catch (Exception)
                {
                    // log
                }
            }
        }
Exemplo n.º 6
0
 public Promise(Arguments args)
 {
     m_promiseTask = new Task<JSObject>(() =>
     {
         return Undefined;
     });
 }
        /// <summary>
        /// Blocks the calling thread to pump messages until a task has completed.
        /// </summary>
        /// <param name="untilCompleted">The task that must complete to break out of the message loop.</param>
        public void PumpMessages(Task untilCompleted)
        {
            this.VerifyState();

            this.pumping = true;
            try
            {
                // Arrange to wake up immediately when the task completes.
                untilCompleted.ContinueWith(
                    _ =>
                    {
                        lock (this.messageQueue)
                        {
                            Monitor.Pulse(this.messageQueue);
                        }
                    },
                    TaskScheduler.Default);

                // Now run the message loop until the task completes.
                while (!untilCompleted.IsCompleted)
                {
                    this.TryOneWorkItem();
                }
            }
            finally
            {
                this.pumping = false;
            }
        }
Exemplo n.º 8
0
        public void NUnitTestShouldDependOnDlls()
        {
            var paths = new Task<string> [] {"one", "two"};
            var tests = new NUnitTests {DllPaths = paths};

            Assert.That(tests.Dependencies.Select(d => d.Task), Has.Member(paths[0]).And.Member(paths[1]));
        }
            public void Enable()
            {
                lock (_gate)
                {
                    if (_instanceTask != null)
                    {
                        // already enabled
                        return;
                    }

                    if (!_workspace.Options.GetOption(RemoteHostOptions.RemoteHost))
                    {
                        // not turned on
                        return;
                    }

                    var remoteHostClientFactory = _workspace.Services.GetService<IRemoteHostClientFactory>();
                    if (remoteHostClientFactory == null)
                    {
                        // dev14 doesn't have remote host client factory
                        return;
                    }

                    // make sure we run it on background thread
                    _shutdownCancellationTokenSource = new CancellationTokenSource();

                    var token = _shutdownCancellationTokenSource.Token;
                    _instanceTask = Task.Run(() => EnableAsync(token), token);
                }
            }
            public void Disable()
            {
                lock (_gate)
                {
                    if (_instanceTask == null)
                    {
                        // already disabled
                        return;
                    }

                    var instance = _instanceTask;
                    _instanceTask = null;

                    RemoveGlobalAssets();

                    _shutdownCancellationTokenSource.Cancel();

                    try
                    {
                        instance.Wait(_shutdownCancellationTokenSource.Token);

                        instance.Result.Shutdown();
                    }
                    catch (OperationCanceledException)
                    {
                        // _instance wasn't finished running yet.
                    }
                }
            }
Exemplo n.º 11
0
		public AssemblyLoader (AssemblyBrowserWidget widget, string fileName)
		{
			if (widget == null)
				throw new ArgumentNullException ("widget");
			if (fileName == null)
				throw new ArgumentNullException ("fileName");
			this.widget = widget;
			this.FileName = fileName;
			if (!File.Exists (fileName))
				throw new ArgumentException ("File doesn't exist.", "fileName");
			this.assemblyLoaderTask = Task.Factory.StartNew<AssemblyDefinition> (() => {
				try {
					return AssemblyDefinition.ReadAssembly (FileName, new ReaderParameters {
						AssemblyResolver = this
					});
				} catch (Exception e) {
					LoggingService.LogError ("Error while reading assembly " + FileName, e);
					return null;
				}
			}, src.Token);
			
			this.unresolvedAssembly = new Lazy<IUnresolvedAssembly> (delegate {
				try {
					return widget.CecilLoader.LoadAssembly (Assembly);
				} catch (Exception e) {
					LoggingService.LogError ("Error while loading assembly", e);
					return new ICSharpCode.NRefactory.TypeSystem.Implementation.DefaultUnresolvedAssembly (FileName);
				}
			});
		}
Exemplo n.º 12
0
		public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
		{
			_metrics = metrics;

			OpenFiles();

			var saveTasks = new Task[4];

			saveTasks[0] = SaveItems();
			saveTasks[1] = SaveMobiles();
			saveTasks[2] = SaveGuilds();
			saveTasks[3] = SaveData();

			SaveTypeDatabases();

			if (permitBackgroundWrite)
			{
				//This option makes it finish the writing to disk in the background, continuing even after Save() returns.
				Task.Factory.ContinueWhenAll(
					saveTasks,
					_ =>
					{
						CloseFiles();

						World.NotifyDiskWriteComplete();
					});
			}
			else
			{
				Task.WaitAll(saveTasks); //Waits for the completion of all of the tasks(committing to disk)
				CloseFiles();
			}
		}
        private static async Task CancelAllWhenAnyCompletes(Task leaderTask, Task renewLeaseTask, CancellationTokenSource cts)
        {
            await Task.WhenAny(leaderTask, renewLeaseTask);

            // Cancel the user's leader task or the renewLease Task, as it is no longer the leader.
            cts.Cancel();

            var allTasks = Task.WhenAll(leaderTask, renewLeaseTask);
            try
            {
                await Task.WhenAll(allTasks);
            }
            catch (Exception)
            {
                if (allTasks.Exception != null)
                {
                    allTasks.Exception.Handle(ex =>
                    {
                        if (!(ex is OperationCanceledException))
                        {
                            Trace.TraceError(ex.Message);
                        }

                        return true;
                    });
                }
            }
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            var maxPlayers = 6;
            var rand = new Random();

            while (true)
            {

                var numOfPlayers = rand.Next(maxPlayers / 2, maxPlayers);
                Task[] tasks = new Task[numOfPlayers];
                for (int j = 0; j < numOfPlayers; j++)
                {
                    int j1 = j;

                    tasks[j] = Task.Factory.StartNew(() => Target(new ThreadParams()
                                                                      {
                                                                          MaxUsers=numOfPlayers,
                                                                          Seed = j1 * 6,
                                                                          State = (j1 == 0 ? (ThreadState.CreateGame) : ThreadState.JoinGame),
                                                                          UserName = names[j1]
                                                                      }));
                }
                while (tasks.Any(t => !t.IsCompleted)) { } //spin wait

            }
        }
Exemplo n.º 15
0
        public Promise(Task<JSObject> task)
        {
            if (task == null)
                throw new ArgumentNullException("task");

            m_promiseTask = task;
        }
Exemplo n.º 16
0
		public void AddOnChangeSetSuccessTask(Task onSuccessTask)
		{
			lock (this)
			{
				_onSuccessTasks.Add(onSuccessTask);
			}
		}
 public void Start()
 {
     if (_running)
         return;
     _running = true;
     _httpTask = Task.Run(() => RunTask(), _cts.Token);
 }
Exemplo n.º 18
0
		public void AddOnChangeSetFailureTask(Task onFailureTask)
		{
			lock (this)
			{
				_onFailureTasks.Add(onFailureTask);
			}
		}
Exemplo n.º 19
0
 /// <summary>
 /// 创建对象
 /// </summary>
 /// <param name="name">测试名称</param>
 /// <param name="threads">线程数</param>
 /// <param name="iteration">循环数</param>
 /// <param name="action">测试方法</param>
 public static void Time(string name, int threads, int iteration, Action action)
 {
     Console.ForegroundColor = ConsoleColor.Green;
     Console.WriteLine("{0} {1}", name, DateTime.Now.ToString("yyyy-M-d hh:mm:ss"));
     Console.ForegroundColor = ConsoleColor.White;
     action();
     Thread.Sleep(1);
     Display("GO");
     //
     WorkerStat[] statArray = new WorkerStat[threads];
     Task[] taskArray = new Task[threads];
     WorkerStat mainStat = new WorkerStat { RunCount = threads * iteration };
     DateTime before = DateTime.Now;
     //Stopwatch watch = Stopwatch.StartNew();
     for (int i = 0; i < threads; i++)
     {
         statArray[i] = new WorkerStat()
         {
             RunCount = iteration
         };
         taskArray[i] = Task.Factory.StartNew(new TaskExt(statArray[i], action).Run);
     }
     Task.WaitAll(taskArray);
     TimeSpan timeTaken = DateTime.Now - before;
     //watch.Stop();
     mainStat.Timespan = (long)timeTaken.TotalMilliseconds;
     WorkerStat totalStat = new WorkerStat();
     for (int i = 0; i < threads; i++)
     {
         totalStat.RunCount = totalStat.RunCount + statArray[i].RunCount;
         totalStat.Timespan = totalStat.Timespan + statArray[i].Timespan;
     }
     //---
     DisplayTestResult(name, threads, iteration, mainStat, totalStat);
 }
Exemplo n.º 20
0
 public void FinishAccept(byte[] buffer, int offset, int length, IPEndPoint remoteEndPoint, IPEndPoint localEndPoint)
 {
     _remoteEndPoint = remoteEndPoint;
     _localEndPoint = localEndPoint;
     Debug.Assert(length == 0);
     try
     {
         _ssl = new SslStream(_inputStream, true);
         _authenticateTask = _ssl.AuthenticateAsServerAsync(_serverCertificate, false, _protocols, false).ContinueWith((t, selfObject) =>
         {
             var self = (SslTransportHandler)selfObject;
             if (t.IsFaulted || t.IsCanceled)
                 self._next.FinishAccept(null, 0, 0, null, null);
             else
                 self._ssl.ReadAsync(self._recvBuffer, self._recvOffset, self._recvLength).ContinueWith((t2, selfObject2) =>
                 {
                     var self2 = (SslTransportHandler)selfObject2;
                     if (t2.IsFaulted || t2.IsCanceled)
                         self2._next.FinishAccept(null, 0, 0, null, null);
                     else
                         self2._next.FinishAccept(self2._recvBuffer, self2._recvOffset, t2.Result, self2._remoteEndPoint, self2._localEndPoint);
                 }, self);
         }, this);
     }
     catch (Exception)
     {
         Callback.StartDisconnect();
     }
 }
Exemplo n.º 21
0
 public static void Add(RecursiveAsyncLock mutex, Task<IDisposable> key)
 {
     Tuple<int, Task<IDisposable>> value;
     if (!OwnedLocks.TryGetValue(mutex, out value))
         value = Tuple.Create(0, key);
     OwnedLocks = OwnedLocks.SetItem(mutex, Tuple.Create(value.Item1 + 1, value.Item2));
 }
 static void Main()
 {
     Task t = new Task(DownloadPageAsync);
     t.Start();
     Console.WriteLine("Downloading page...");
     Console.ReadLine();
 }
Exemplo n.º 23
0
			protected override bool TryExecuteTaskInline (Task task, bool taskWasPreviouslyQueued)
			{
				if (TryExecuteTaskInlineHandler != null)
					TryExecuteTaskInlineHandler (task, taskWasPreviouslyQueued);

				return base.TryExecuteTask (task);
			}
Exemplo n.º 24
0
			protected override void QueueTask (Task task)
			{
				Interlocked.Increment (ref qc);
				ThreadPool.QueueUserWorkItem (o => {
					TryExecuteTask (task);
				});
			}
        /// <summary>
        /// Implementación para la demostración del flujo de control de invocaciones 
        /// a través de elementos de programa de TPL.
        /// </summary>
        /// <returns>Resultado de la operación asincrónica.</returns>
        private Task AsincronismoConTpl()
        {
            var tareaCompuesta = new Task(() =>
            {
                Task<string> tarea1 = ObtenerInfoThreadAsync("TPL No. 1");
                tarea1.ContinueWith(tarea =>
                {
                    Console.WriteLine(tarea1.Result);

                    Task<string> tarea2 = ObtenerInfoThreadAsync("TPL No. 2");
                    tarea2.ContinueWith(tareaAnidada =>
                        Console.WriteLine(tareaAnidada.Result),
                        TaskContinuationOptions.NotOnFaulted |
                            TaskContinuationOptions.AttachedToParent);

                    tarea2.ContinueWith(tareaAnidada =>
                        Console.WriteLine(tareaAnidada.Exception.InnerException),
                        TaskContinuationOptions.OnlyOnFaulted |
                            TaskContinuationOptions.AttachedToParent);
                },
                    TaskContinuationOptions.NotOnFaulted |
                        TaskContinuationOptions.AttachedToParent);

                tarea1.ContinueWith(tarea =>
                    Console.WriteLine(tarea1.Exception.InnerException),
                    TaskContinuationOptions.OnlyOnFaulted |
                        TaskContinuationOptions.AttachedToParent);
            });

            tareaCompuesta.Start();

            return tareaCompuesta;
        }
Exemplo n.º 26
0
        /// <summary>
        /// Starts the listening for updates and fires a <see cref="OnMessageReceived"/> event when a message is received.
        /// </summary>
        /// <param name="pollingInterval">The interval of polling in seconds (default set)</param>
        public void Start(int pollingInterval = 1)
        {
            if (_getUpdatesTask != null) return;

            try
            {
                Action poll = async () =>
                {
                    while (!_cancellationTokenSource.IsCancellationRequested)
                    {
                        Update[] updates = await GetUpdatesAsync(_lastUpdateId, timeout: pollingInterval);
                        foreach (Update update in updates.Where(u => u.UpdateId > _lastUpdateId))
                        {
                            FireMessageReceived(update.Message);
                            _lastUpdateId = update.UpdateId;
                        }
                        //await Task.Delay(pollingInterval * 1000);
                    }
                };
                _getUpdatesTask = Task.Run(poll, _cancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemplo n.º 27
0
    protected void DropDownListMark_SelectedIndexChanged(object sender, EventArgs e)
    {
        bool status = false;
        foreach (GridViewRow row in GridViewTask.Rows)
        {
            CheckBox checkBox = (CheckBox)row.Cells[0].FindControl("CheckBoxTask");
            if (checkBox.Checked)
            {
                HiddenField hiddenField = (HiddenField)row.Cells[0].FindControl("HiddenFieldTask");
                string taskUserOID = hiddenField.Value;
                Task task = new Task();
                if ((DropDownListMark.SelectedItem.Text == "Mark") || (DropDownListMark.SelectedItem.Text == "Star"))
                {
                    if (task.UpdateTaskUserUMark(Convert.ToInt32(taskUserOID), 1)) status = true;
                }
                else
                {
                    if (task.UpdateTaskUserUStatus(Convert.ToInt32(taskUserOID), DropDownListMark.SelectedItem.Text)) status = true;
                }

            }
        }
        if (status)
        {
            PopulateGridview();
        }
    }
Exemplo n.º 28
0
		//called when data for any output pin is requested
		public void Evaluate(int SpreadMax)
		{
			if(FInput.IsChanged)
			{
				FOutput.SliceCount = FInput.SliceCount;
	
				for (int i = 0; i < FInput.SliceCount; i++) {
					
					var r = new TRes();
					r.host = FInput[i];
					r.idx = i;
					r.Resolved = false;
					var t = new Task<TRes>(() => _GetHostByName(r));
					var c = t.ContinueWith((res) =>
					{
					   if(res.Result.ips != null)
					   {
							FOutput[res.Result.idx].SliceCount = res.Result.ips.Length;
							for(int j = 0; j<res.Result.ips.Length;j++)
							{
								FOutput[res.Result.idx][j] = res.Result.ips[j];
							}
						} else FOutput[res.Result.idx].SliceCount = 0;
					},TaskContinuationOptions.OnlyOnRanToCompletion);
					t.Start();
					
					
				}
				
			}
			
			
			//FLogger.Log(LogType.Debug, "Logging to Renderer (TTY)");
		}
Exemplo n.º 29
0
		public static void Start(string name)
		{
			DBC.Pre(!string.IsNullOrEmpty(name), "name is null or empty");
			
			if (ms_current == null)
			{
				DBC.Assert(ms_root == null, "Start was called after the root task was stopped");
				
				ms_root = new Task(null, name);
				ms_current = ms_root;
			}
			else
			{
				Task task;
				if (!ms_current.SubTasks.TryGetValue(name, out task))
				{
					task = new Task(ms_current, name);
					ms_current.SubTasks.Add(name, task);
				}
				else
				{
					DBC.Assert(task.StartTime == DateTime.MinValue, "can't nest the same task");
					task.StartTime = DateTime.Now;
					task.Count += 1;
				}
				ms_current = task;
			}			
		}
        public async Task Stop()
        {
            await _startStopSemaphore.WaitAsync();

            try
            {
                if (!_running) return;
                _running = false;

                _cancellationTokenSource.Cancel();
                _cancellationTokenSource = null;

                var workerTask = _workerTask;
                _workerTask = null;
                if (workerTask != null) await workerTask;

                // wait for all our existing tasks to complete
                //FIXME a bit ick..
                while (_throttle.CurrentCount < ConcurrentHandlerLimit)
                {
                    await Task.Delay(TimeSpan.FromMilliseconds(100));
                }
            }
            finally
            {
                _startStopSemaphore.Release();
            }
        }
 /// <summary>
 /// This method is called during suspected data loss. 
 /// You can override this method to restore the service in case of data loss.
 /// </summary>
 /// <param name="restoreCtx">
 /// A <see cref="RestoreContext"/> to be used to restore the service.
 /// </param>
 /// <param name="cancellationToken">
 /// <see cref="CancellationToken"/> to monitor for cancellation requests.
 /// </param>
 /// <returns>
 /// A Task that represents the asynchronous restore operation.
 /// True indicates that the state has been restored.
 /// False indicates that the replica's state has not been modified.
 /// </returns>
 protected virtual Task<bool> OnDataLossAsync(RestoreContext restoreCtx, CancellationToken cancellationToken)
 {
     return Task.FromResult(false);
 }
 public Task SendAsync(IdentityMessage message)
 {
     // Plug in your SMS service here to send a text message.
     return Task.FromResult(0);
 }
 protected RedirectToRouteResult RedirectToActionPermanent(Task <ActionResult> taskResult)
 {
     return(RedirectToActionPermanent(taskResult.Result));
 }
 public Task<byte[]> Decompress(byte[] compressedArray, int bufferSize)
 {
     return Task.FromResult(compressedArray);
 }
Exemplo n.º 35
0
 /// <inheritdoc/>
 public Task<IEnumerable<string>> GetAvailableDifficultyLevelsAsync()
 {
     return Task.FromResult(levelsProvider.GetLevels());
 }
Exemplo n.º 36
0
        public async Task<TestingSystemResponse> CheckSolution(SolutionTestingRequest solutionRequest)
        {
            try
            {
                var solution = _db.Solutions.Find(solutionRequest.SolutionId);

                if (solution != null && solution.File != null)
                {
                    var taskTests = _db.TaskTests.Where(t => t.TaskId == solution.TaskId).ToArray();

                    if (taskTests != null && taskTests.Length > 0)
                    {
                        var isAlive = await CheckIfAlive(_config.CompilerServicesOrchestrator);

                        if (isAlive)
                        {
                            //var dataBytes = await file.GetBytes();                        
                            var codeStyleTask = taskTests.FirstOrDefault(t => t.TestType == "codeStyleTest");

                            var req = new TestRequest
                            {
                                SolutionId = solutionRequest.SolutionId,
                                TestId = codeStyleTask is null ? -1 : codeStyleTask.Id,
                                ReCheck = solutionRequest.ReCheck,
                            };

                            string url = _config.CompilerServicesOrchestrator.GetFullTestLinkFrom(_config.TestingSystemWorker);
                            using var httpClient = new HttpClient();
                            using var form = JsonContent.Create(req);
                            HttpResponseMessage response = await httpClient.PostAsync(url, form);
                            string apiResponse = await response.Content.ReadAsStringAsync();
                            if (response.IsSuccessStatusCode)
                            {
                                TestResponse compResponse = JsonConvert.DeserializeObject<TestResponse>(apiResponse);

                                if (compResponse.OK && compResponse.Result == ResultCode.OK)
                                {
                                    var compResult = _db.CompilationResults.Find(solutionRequest.SolutionId);

                                    if (compResult != null)
                                    {
                                        if (compResult.ResultCode != ResultCode.CE && compResult.File != null)
                                        {
                                            var testTasks = new List<Task<TestResponse>>();
                                            foreach (var test in taskTests)
                                            {
                                                if (_config.Tests.ContainsKey(test.TestType))
                                                {
                                                    testTasks.Add(StartTest(test.TestType, solutionRequest.SolutionId, test.Id, solutionRequest.ReCheck));
                                                }
                                                else
                                                {
                                                    testTasks.Add(Task.Run(() => NoTestFound(test.TestType, solutionRequest.SolutionId, test.Id)));
                                                }
                                            }
                                            await Task.WhenAll(testTasks);

                                            var responses = testTasks.Select(t => t.Result).ToArray();
                                            var results = responses.Join(taskTests, i => i.TestId, o => o.Id, (i, o) => new { Result = i, Definition = o }).ToArray();

                                            double totalScore = 0;
                                            ResultCode totalResult = results.Select(r => r.Result.Result).Max();

                                            foreach (var res in results)
                                            {
                                                if (res.Definition.Block && res.Result.Score == 0)
                                                {
                                                    totalScore = 0;

                                                    break;
                                                }
                                                else
                                                {
                                                    totalScore += res.Result.Score * res.Definition.Weight;
                                                }
                                            }

                                            return WriteToDb(solution, totalResult, totalScore, "success", true, responses);
                                        }
                                        else
                                        {
                                            return WriteToDb(solution, compResult.ResultCode, 0, "compilation error!", true);
                                        }
                                    }
                                    else
                                    {
                                        return WriteToDb(solution, compResponse.Result, 0, "can't find compilation! Inner message: " + compResponse.Message, false);
                                    }
                                }
                                else
                                {
                                    return WriteToDb(solution, compResponse.Result, 0, "something went wrong during compilation! Inner message: " + compResponse.Message, false);
                                }
                            }
                            else
                            {
                                return WriteToDb(solution, ResultCode.IE, 0, "bad response from compilation container: " + response.StatusCode, false);
                            }
                        }
                        else
                        {
                            return WriteToDb(solution, ResultCode.IE, 0, "Compiler Service Is Dead!", false);
                        }
                    }
                    else
                    {
                        return WriteToDb(null, ResultCode.IE, 0, "Can't find task tests!", false);
                    }
                }
                else
                {
                    return WriteToDb(null, ResultCode.IE, 0, "Can't find solution!", false);
                }
            }
            catch
            {
                return new TestingSystemResponse();
            }
        }
Exemplo n.º 37
0
            public async Task Slot(ShmartNumber amount)
            {
                if (!_runningUsers.Add(Context.User.Id))
                {
                    return;
                }
                try
                {
                    if (!await CheckBetMandatory(amount).ConfigureAwait(false))
                    {
                        return;
                    }
                    const int maxAmount = 9999;
                    if (amount > maxAmount)
                    {
                        await ReplyErrorLocalizedAsync("max_bet_limit", maxAmount + Bc.BotConfig.CurrencySign).ConfigureAwait(false);

                        return;
                    }

                    if (!await _cs.RemoveAsync(Context.User, "Slot Machine", amount, false, gamble: true).ConfigureAwait(false))
                    {
                        await ReplyErrorLocalizedAsync("not_enough", Bc.BotConfig.CurrencySign).ConfigureAwait(false);

                        return;
                    }
                    Interlocked.Add(ref _totalBet, amount.Value);
                    using (var bgImage = Image.Load(_images.SlotBackground))
                    {
                        var   result  = SlotMachine.Pull();
                        int[] numbers = result.Numbers;

                        for (int i = 0; i < 3; i++)
                        {
                            using (var randomImage = Image.Load(_images.SlotEmojis[numbers[i]]))
                            {
                                bgImage.Mutate(x => x.DrawImage(GraphicsOptions.Default, randomImage, new Point(95 + 142 * i, 330)));
                            }
                        }

                        var won      = amount * result.Multiplier;
                        var printWon = won;
                        var n        = 0;
                        do
                        {
                            var digit = (int)(printWon % 10);
                            using (var img = Image.Load(_images.SlotNumbers[digit]))
                            {
                                bgImage.Mutate(x => x.DrawImage(GraphicsOptions.Default, img, new Point(230 - n * 16, 462)));
                            }
                            n++;
                        } while ((printWon /= 10) != 0);

                        var printAmount = amount;
                        n = 0;
                        do
                        {
                            var digit = (int)(printAmount % 10);
                            using (var img = Image.Load(_images.SlotNumbers[digit]))
                            {
                                bgImage.Mutate(x => x.DrawImage(GraphicsOptions.Default, img, new Point(395 - n * 16, 462)));
                            }
                            n++;
                        } while ((printAmount /= 10) != 0);

                        var msg = GetText("better_luck");
                        if (result.Multiplier != 0)
                        {
                            await _cs.AddAsync(Context.User, $"Slot Machine x{result.Multiplier}", amount *result.Multiplier, false, gamble : true).ConfigureAwait(false);

                            Interlocked.Add(ref _totalPaidOut, amount * result.Multiplier);
                            if (result.Multiplier == 1)
                            {
                                msg = GetText("slot_single", Bc.BotConfig.CurrencySign, 1);
                            }
                            else if (result.Multiplier == 4)
                            {
                                msg = GetText("slot_two", Bc.BotConfig.CurrencySign, 4);
                            }
                            else if (result.Multiplier == 10)
                            {
                                msg = GetText("slot_three", 10);
                            }
                            else if (result.Multiplier == 30)
                            {
                                msg = GetText("slot_jackpot", 30);
                            }
                        }

                        using (var imgStream = bgImage.ToStream())
                        {
                            await Context.Channel.SendFileAsync(imgStream, "result.png", Context.User.Mention + " " + msg + $"\n`{GetText("slot_bet")}:`{amount} `{GetText("won")}:` {amount * result.Multiplier}{Bc.BotConfig.CurrencySign}").ConfigureAwait(false);
                        }
                    }
                }
                finally
                {
                    var _ = Task.Run(async() =>
                    {
                        await Task.Delay(1500).ConfigureAwait(false);
                        _runningUsers.Remove(Context.User.Id);
                    });
                }
            }
Exemplo n.º 38
0
		public void Send(ref System.Diagnostics.Stopwatch sw)
		{
			sw.Start();
			Task.WaitAll(mSend());
		}
        public Task<PackageVerificationCode> VerifyPackageAsync()
        {
            return Task.Run(() => 
            {
                ModuleTypesList type; float MinimalVersion;
                using (ZipArchive zip_content = ZipFile.OpenRead(Package.Path))
                {

                    //Verify "infos.json" and if the file exist, get the content for the others verification !
                    try
                    {
                        ZipArchiveEntry InfosJson = zip_content.GetEntry("infos.json");

                        if (InfosJson == null)
                        {
                            return PackageVerificationCode.InfosJsonNotFound;
                        }
                        else
                        {

                            using (var reader = new StreamReader(InfosJson.Open()))
                            using (JsonReader JsonReader = new JsonTextReader(reader))
                            {
                                InfosModule module = new JsonSerializer().Deserialize<InfosModule>(JsonReader);
                                if (module != null)
                                {
                                    type = module.ModuleType;
                                    MinimalVersion = module.SceMinimalVersionRequired;
                                }
                                else
                                {
                                    return PackageVerificationCode.InfosJsonNotFound;
                                }
                            }

                        }
                    }
                    catch
                    {
                        return PackageVerificationCode.InfosJsonNotFound;
                    }


                    //Verify if the logo exist or not
                    try
                    {
                        if (zip_content.GetEntry("logo.png") == null)
                        {
                            return PackageVerificationCode.LogoNotFound;
                        }
                    }
                    catch
                    {
                        return PackageVerificationCode.LogoNotFound;
                    }

                    //Verify if the icon exist or not
                    try
                    {
                        if (zip_content.GetEntry("icon.png") == null)
                        {
                            return PackageVerificationCode.LogoNotFound;
                        }
                    }
                    catch
                    {
                        return PackageVerificationCode.LogoNotFound;
                    }

                    switch (type)
                    {
                        case ModuleTypesList.Templates:
                        case ModuleTypesList.Addon:

                            //Verify if the "main.js" exist or not
                            try
                            {
                                if (zip_content.GetEntry("main.js") == null)
                                {
                                    return PackageVerificationCode.MainJsNotFound;
                                }
                            }
                            catch { return PackageVerificationCode.MainJsNotFound; }

                            break;

                        case ModuleTypesList.Theme:

                            //Verify if the "theme.js" or "theme_ace.js" exist or not
                            bool themejs = true, themeacejs = true;

                            try
                            {
                                if (zip_content.GetEntry("theme.json") == null)
                                {
                                    themejs = false;
                                }
                            }
                            catch
                            {
                                themejs = false;
                            }

                            /*try
                            {
                                if (zip_content.GetEntry("theme_ace.js") == null)
                                {
                                    themeacejs = false;
                                }
                            }
                            catch
                            {
                                themeacejs = false;
                            }*/

                            if (!themejs /*&& !themeacejs*/)
                            {
                                return PackageVerificationCode.NoThemeFiles;
                            }

                            break;

                        case ModuleTypesList.ProgrammingLanguage:

                            try
                            {
                                if (zip_content.GetEntry("language.js") == null)
                                {
                                    return PackageVerificationCode.NoProgLanguagesFiles;
                                }
                            }
                            catch
                            {
                                return PackageVerificationCode.NoProgLanguagesFiles;
                            }
                            break;
                    }


                }

                return PackageVerificationCode.Passed;
            });
        }
 public Task SendAsync(IdentityMessage message)
 {
     // Plug in your email service here to send an email.
     return Task.FromResult(0);
 }
Exemplo n.º 41
0
        private void buttonApprox_Click(object sender, EventArgs e)
        {
            //Слово для поиска
            string word = this.textBoxFind.Text.Trim();

            //Если слово для поиска не пусто
            if (!string.IsNullOrWhiteSpace(word) && list.Count > 0)
            {
                int maxDist;
                if (!int.TryParse(this.textBoxMaxDist.Text.Trim(), out maxDist))
                {
                    MessageBox.Show("Необходимо указать максимальное расстояние");
                    return;
                }

                if (maxDist < 1 || maxDist > 5)
                {
                    MessageBox.Show("Максимальное расстояние должно быть в диапазоне от 1 до 5");
                    return;
                }

                int ThreadCount;
                if (!int.TryParse(this.textBoxThreadCount.Text.Trim(), out ThreadCount))
                {
                    MessageBox.Show("Необходимо указать количество потоков");
                    return;
                }

                Stopwatch timer = new Stopwatch();
                timer.Start();

                //-------------------------------------------------
                // Начало параллельного поиска
                //-------------------------------------------------

                //Результирующий список
                List <ParallelSearchResult> Result = new List <ParallelSearchResult>();

                //Деление списка на фрагменты для параллельного запуска в потоках
                List <MinMax> arrayDivList = SubArrays.DivideSubArrays(0, list.Count, ThreadCount);
                int           count        = arrayDivList.Count;

                //Количество потоков соответствует количеству фрагментов массива
                Task <List <ParallelSearchResult> >[] tasks = new Task <List <ParallelSearchResult> > [count];

                //Запуск потоков
                for (int i = 0; i < count; i++)
                {
                    //Создание временного списка, чтобы потоки не работали параллельно с одной коллекцией
                    List <string> tempTaskList = list.GetRange(arrayDivList[i].Min, arrayDivList[i].Max - arrayDivList[i].Min);

                    tasks[i] = new Task <List <ParallelSearchResult> >(
                        //Метод, который будет выполняться в потоке
                        ArrayThreadTask,
                        //Параметры потока
                        new ParallelSearchThreadParam()
                    {
                        tempList    = tempTaskList,
                        maxDist     = maxDist,
                        ThreadNum   = i,
                        wordPattern = word
                    });

                    //Запуск потока
                    tasks[i].Start();
                }

                Task.WaitAll(tasks);

                timer.Stop();

                //Объединение результатов
                for (int i = 0; i < count; i++)
                {
                    Result.AddRange(tasks[i].Result);
                }

                //-------------------------------------------------
                // Завершение параллельного поиска
                //-------------------------------------------------

                timer.Stop();

                //Вывод результатов

                //Время поиска
                this.textBoxApproxTime.Text = timer.Elapsed.ToString();

                //Вычисленное количество потоков
                this.textBoxThreadCountAll.Text = count.ToString();

                //Начало обновления списка результатов
                this.listBoxResult.BeginUpdate();

                //Очистка списка
                this.listBoxResult.Items.Clear();

                //Вывод результатов поиска
                foreach (var x in Result)
                {
                    string temp = x.word + "(расстояние=" + x.dist.ToString() + " поток=" + x.ThreadNum.ToString() + ")";
                    this.listBoxResult.Items.Add(temp);
                }

                //Окончание обновления списка результатов
                this.listBoxResult.EndUpdate();
            }
            else
            {
                MessageBox.Show("Необходимо выбрать файл и ввести слово для поиска");
            }
        }
Exemplo n.º 42
0
                        public async Task CreatesPackageOwnerRequestSendsEmailAndReturnsPendingState(Func <Fakes, User> getCurrentUser, Func <Fakes, User> getUserToAdd)
                        {
                            var fakes = Get <Fakes>();

                            var currentUser = getCurrentUser(fakes);
                            var userToAdd   = getUserToAdd(fakes);

                            var controller = GetController <JsonApiController>();

                            controller.SetCurrentUser(currentUser);

                            var packageOwnershipManagementServiceMock = GetMock <IPackageOwnershipManagementService>();
                            var messageServiceMock = GetMock <IMessageService>();

                            var pending = !(ActionsRequiringPermissions.HandlePackageOwnershipRequest.CheckPermissions(currentUser, userToAdd) == PermissionsCheckResult.Allowed);

                            if (pending)
                            {
                                packageOwnershipManagementServiceMock
                                .Setup(p => p.AddPackageOwnershipRequestAsync(fakes.Package, currentUser, userToAdd))
                                .Returns(Task.FromResult(new PackageOwnerRequest {
                                    ConfirmationCode = "confirmation-code"
                                }))
                                .Verifiable();

                                messageServiceMock
                                .Setup(m => m.SendPackageOwnerRequestAsync(
                                           currentUser,
                                           userToAdd,
                                           fakes.Package,
                                           TestUtility.GallerySiteRootHttps + "packages/FakePackage/",
                                           TestUtility.GallerySiteRootHttps + $"packages/FakePackage/owners/{userToAdd.Username}/confirm/confirmation-code",
                                           TestUtility.GallerySiteRootHttps + $"packages/FakePackage/owners/{userToAdd.Username}/reject/confirmation-code",
                                           "Hello World! Html Encoded &lt;3",
                                           ""))
                                .Returns(Task.CompletedTask)
                                .Verifiable();

                                foreach (var owner in fakes.Package.Owners)
                                {
                                    messageServiceMock
                                    .Setup(m => m.SendPackageOwnerRequestInitiatedNoticeAsync(
                                               currentUser,
                                               owner,
                                               userToAdd,
                                               fakes.Package,
                                               It.IsAny <string>()))
                                    .Returns(Task.CompletedTask)
                                    .Verifiable();
                                }
                            }
                            else
                            {
                                packageOwnershipManagementServiceMock
                                .Setup(p => p.AddPackageOwnerAsync(fakes.Package, userToAdd, true))
                                .Returns(Task.CompletedTask)
                                .Verifiable();

                                foreach (var owner in fakes.Package.Owners)
                                {
                                    messageServiceMock
                                    .Setup(m => m.SendPackageOwnerAddedNoticeAsync(
                                               owner,
                                               userToAdd,
                                               fakes.Package,
                                               It.IsAny <string>()))
                                    .Returns(Task.CompletedTask)
                                    .Verifiable();
                                }
                            }

                            JsonResult result = await controller.AddPackageOwner(fakes.Package.Id, userToAdd.Username, "Hello World! Html Encoded <3");

                            dynamic data = result.Data;
                            PackageOwnersResultViewModel model = data.model;

                            Assert.True(data.success);
                            Assert.Equal(userToAdd.Username, model.Name);
                            Assert.Equal(pending, model.Pending);

                            packageOwnershipManagementServiceMock.Verify();
                            messageServiceMock.Verify();
                        }
Exemplo n.º 43
0
        public Task BufferSong(CancellationToken cancelToken) =>
           Task.Run(async () =>
           {
               Process p = null;
               FileStream outStream = null;
               try
               {
                   p = Process.Start(new ProcessStartInfo
                   {
                       FileName = "ffmpeg",
                       Arguments = $"-ss {CurrentTrack.SkipTo} -i {CurrentTrack.SourceVideo.GetUri()} -f s16le -ar 48000 -vn -ac 2 pipe:1 -loglevel quiet",
                       UseShellExecute = false,
                       RedirectStandardOutput = true,
                       RedirectStandardError = false,
                       CreateNoWindow = true,
                   });

                   byte[] buffer = new byte[81920];
                   int currentFileSize = 0;
                   ulong prebufferSize = 100ul.MiB();

                   outStream = new FileStream(Basename + "-" + ++FileNumber, FileMode.Append, FileAccess.Write, FileShare.Read);
                   while (!p.HasExited) //Also fix low bandwidth
                   {
                       int bytesRead = await p.StandardOutput.BaseStream.ReadAsync(buffer, 0, buffer.Length, cancelToken).ConfigureAwait(false);
                       if (currentFileSize >= MaxFileSize)
                       {
                           try
                           {
                               outStream.Dispose();
                           }
                           catch { }
                           outStream = new FileStream(Basename + "-" + ++FileNumber, FileMode.Append, FileAccess.Write, FileShare.Read);
                           currentFileSize = bytesRead;
                       }
                       else
                       {
                           currentFileSize += bytesRead;
                       }
                       CurrentBufferSize += Convert.ToUInt64(bytesRead);
                       await outStream.WriteAsync(buffer, 0, bytesRead, cancelToken).ConfigureAwait(false);
                       while (CurrentBufferSize > prebufferSize)
                           await Task.Delay(100, cancelToken);
                   }
                   BufferingCompleted = true;
               }
               catch (Win32Exception ex)
               {
                   Log.Message(LogSeverity.Error, ex.Message);
                   Log.Message(LogSeverity.Error, ex.StackTrace);
               }
               catch (Exception ex)
               {
                   Log.Message(LogSeverity.Error, $"Buffering stopped: {ex.Message}");
               }
               finally
               {
                   if (outStream != null)
                       outStream.Dispose();
                   Log.Message(LogSeverity.Debug, $"Buffering done.");
                   if (p != null)
                   {
                       try
                       {
                           p.Kill();
                       }
                       catch { }
                       p.Dispose();
                   }
               }
           });
Exemplo n.º 44
0
        static void Main()
        {
            Console.WriteLine("SIPSorcery Getting Started Video Call Demo");
            Console.WriteLine("Press ctrl-c to exit.");

            Log = AddConsoleLogger();

            _sipTransport = new SIPTransport();

            EnableTraceLogs(_sipTransport);

            // Open a window to display the video feed from the remote SIP party.
            _form          = new Form();
            _form.AutoSize = true;
            _form.BackgroundImageLayout = ImageLayout.Center;
            _picBox = new PictureBox
            {
                Size     = new Size(640, 480),
                Location = new Point(0, 0),
                Visible  = true
            };
            _form.Controls.Add(_picBox);

            Application.EnableVisualStyles();
            ThreadPool.QueueUserWorkItem(delegate { Application.Run(_form); });

            ManualResetEvent formMre = new ManualResetEvent(false);

            _form.Activated += (object sender, EventArgs e) => formMre.Set();

            Console.WriteLine("Waiting for form activation.");
            formMre.WaitOne();

            _sipTransport.SIPTransportRequestReceived += OnSIPTransportRequestReceived;

            string executableDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            var userAgent            = new SIPUserAgent(_sipTransport, null);
            var windowsAudioEndPoint = new WindowsAudioEndPoint(new AudioEncoder());

            windowsAudioEndPoint.RestrictCodecs(new List <AudioCodecsEnum> {
                AudioCodecsEnum.PCMU
            });
            var windowsVideoEndPoint = new WindowsVideoEndPoint();

            MediaEndPoints mediaEndPoints = new MediaEndPoints
            {
                AudioSink   = windowsAudioEndPoint,
                AudioSource = windowsAudioEndPoint,
                VideoSink   = windowsVideoEndPoint,
                VideoSource = windowsVideoEndPoint,
            };

            var voipMediaSession = new VoIPMediaSession(mediaEndPoints);

            voipMediaSession.AcceptRtpFromAny = true;

            // Place the call and wait for the result.
            Task <bool> callTask = userAgent.Call(DESTINATION, null, null, voipMediaSession);

            callTask.Wait(CALL_TIMEOUT_SECONDS * 1000);

            ManualResetEvent exitMRE = new ManualResetEvent(false);

            if (callTask.Result)
            {
                Log.LogInformation("Call attempt successful.");
                windowsVideoEndPoint.OnVideoSinkDecodedSample += (byte[] bmp, uint width, uint height, int stride, VideoPixelFormatsEnum pixelFormat) =>
                {
                    _picBox.BeginInvoke(new Action(() =>
                    {
                        unsafe
                        {
                            fixed(byte *s = bmp)
                            {
                                System.Drawing.Bitmap bmpImage = new System.Drawing.Bitmap((int)width, (int)height, stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, (IntPtr)s);
                                _picBox.Image = bmpImage;
                            }
                        }
                    }));
                };

                windowsAudioEndPoint.PauseAudio().Wait();
                voipMediaSession.AudioExtrasSource.SetSource(AudioSourcesEnum.Music);
            }
            else
            {
                Log.LogWarning("Call attempt failed.");
                Console.WriteLine("Press ctrl-c to exit.");
            }

            Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
            {
                e.Cancel = true;
                Log.LogInformation("Exiting...");
                exitMRE.Set();
            };
            exitMRE.WaitOne();

            if (userAgent.IsCallActive)
            {
                Log.LogInformation("Hanging up.");
                userAgent.Hangup();

                Task.Delay(1000).Wait();
            }

            // Clean up.
            _form.BeginInvoke(new Action(() => _form.Close()));
            _sipTransport.Shutdown();
        }
Exemplo n.º 45
0
 protected RedirectToRouteResult RedirectToAction(Task<IActionResult> taskResult)
 {
     return RedirectToAction(taskResult.Result);
 }
 /// <summary>
 /// This method is called when replica's state has been restored successfully via the Backup Restore service
 /// </summary>
 /// <param name="cancellationToken">
 /// <see cref="CancellationToken"/> to monitor for cancellation requests.
 /// </param>
 /// <returns>
 /// A Task that represents the asynchronous operation.
 /// </returns>
 protected virtual Task OnRestoreCompletedAsync(CancellationToken cancellationToken)
 {
     return Task.FromResult(0);
 }
Exemplo n.º 47
0
        public async Task ShouldLogError_WhenSaveChangesThrows()
        {
            // Arrange
            var context = Fixture.Freeze <Mock <IDbContext> >();

            var token = new CancellationToken();

            var exception = Fixture.Create <Exception>();

            context.Setup(x => x.SaveChangesAsync(token)).Callback(() => throw exception);

            var logger = Fixture.Freeze <Mock <ILogger <CustomCommand <int> > > >();

            var sut = Fixture.Create <SaveChangesBehaviour <CustomCommand <int>, int> >();

            // Act
            Func <Task <int> > act = () => sut.Handle(new CustomCommand <int>(), token, () => Task.FromResult(0));

            // Assert
            await act.Should().ThrowExactlyAsync <Exception>();

            logger.Verify(x => x.LogError("Error while saving changes", exception), Times.Once);
        }
 /// <summary>
 /// This method is called when role of the replica is changing and it is the final step before completing <see cref="IStatefulServiceReplica.ChangeRoleAsync"/>.
 /// Override this method to be notified that ChangeRole has completed for this replica's internal components.
 /// <para>
 /// For information about Reliable Services life cycle please see
 /// https://docs.microsoft.com/azure/service-fabric/service-fabric-reliable-services-lifecycle
 /// </para>
 /// </summary>
 /// <param name="newRole">New <see cref="ReplicaRole"/> for this service replica.</param>
 /// <param name="cancellationToken">Cancellation token to monitor for cancellation requests.</param>
 /// <returns>
 /// A <see cref="Task"/> that represents outstanding operation.
 /// </returns>
 protected virtual Task OnChangeRoleAsync(ReplicaRole newRole, CancellationToken cancellationToken)
 {
     return Task.FromResult(true);
 }
Exemplo n.º 49
0
        public async Task<List<ActionResult>> Validate(DeploymentTaskExecutionParams execParams)
        {
            var results = new List<ActionResult> { };

            return await Task.FromResult(results);
        }
 /// <summary>
 /// This method is called as the final step of closing the service gracefully.
 /// Override this method to be notified that Close has completed for this replica's internal components.
 /// <para>
 /// For information about Reliable Services life cycle please see
 /// https://docs.microsoft.com/azure/service-fabric/service-fabric-reliable-services-lifecycle
 /// </para>
 /// </summary>
 /// <param name="cancellationToken">Cancellation token to monitor for cancellation requests.</param>
 /// <returns>
 /// A <see cref="System.Threading.Tasks.Task">Task</see> that represents outstanding operation.
 /// </returns>
 protected virtual Task OnCloseAsync(CancellationToken cancellationToken)
 {
     return Task.FromResult(true);
 }
        protected override Task SaveLocalToken(string token)
        {
            SetLocalValue(SettingsUserNameKey, token);

            return(Task.FromResult(true));
        }
 /// <summary>
 /// This method is called when the replica is being opened and it is the final step of opening the service.
 /// Override this method to be notified that Open has completed for this replica's internal components.
 /// <para>
 /// For information about Reliable Services life cycle please see
 /// https://docs.microsoft.com/azure/service-fabric/service-fabric-reliable-services-lifecycle
 /// </para>
 /// </summary>
 /// <param name="openMode"><see cref="ReplicaOpenMode"/> for this service replica.</param>
 /// <param name="cancellationToken">Cancellation token to monitor for cancellation requests.</param>
 /// <returns>
 /// A <see cref="Task">Task</see> that represents outstanding operation.
 /// </returns>
 protected virtual Task OnOpenAsync(ReplicaOpenMode openMode, CancellationToken cancellationToken)
 {
     return Task.FromResult(true);
 }
Exemplo n.º 53
0
        public void ConfigureAuth(IAppBuilder app)
        {
            string ClientId = ConfigurationManager.AppSettings["ida:ClientID"];
            string Password = ConfigurationManager.AppSettings["ida:Password"];
            string Authority = string.Format(ConfigurationManager.AppSettings["ida:Authority"], "common");
            string GraphAPIIdentifier = ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"];
            string AzureResourceManagerIdentifier = ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"];
                        
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions { });
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
                {
                    ClientId = ClientId,
                    Authority = Authority,
                    TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                    {
                        // we inject our own multitenant validation logic
                        ValidateIssuer = false,
                    },
                    Notifications = new OpenIdConnectAuthenticationNotifications()
                    {
                        RedirectToIdentityProvider = (context) =>
                        {
                            // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                            // this allows you to deploy your app (to Azure Web Sites, for example) without having to change settings
                            // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                            //string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                            context.ProtocolMessage.RedirectUri = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path);
                            context.ProtocolMessage.PostLogoutRedirectUri = new UrlHelper(HttpContext.Current.Request.RequestContext).Action
                                ("Index", "Home", null, HttpContext.Current.Request.Url.Scheme);
                            context.ProtocolMessage.Resource = GraphAPIIdentifier;
                            return Task.FromResult(0);
                        },
                        AuthorizationCodeReceived = (context) =>
                        {
                            ClientCredential credential = new ClientCredential(ClientId, Password);
                            string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                            string signedInUserUniqueName = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#')[context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

                            AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID),
                                new ADALTokenCache(signedInUserUniqueName));

                            //var items = authContext.TokenCache.ReadItems().ToList();

                            AuthenticationResult result1 = authContext.AcquireTokenByAuthorizationCode(
                                context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential);

                             //items = authContext.TokenCache.ReadItems().ToList();

                             AuthenticationResult result2 = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                                 new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                             //items = authContext.TokenCache.ReadItems().ToList();

                            return Task.FromResult(0);
                        },
                        // we use this notification for injecting our custom logic
                        SecurityTokenValidated = (context) =>
                        {
                            // retriever caller data from the incoming principal
                            string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                            if (!issuer.StartsWith("https://sts.windows.net/"))
                                // the caller is not from a trusted issuer - throw to block the authentication flow
                                throw new System.IdentityModel.Tokens.SecurityTokenValidationException();

                            return Task.FromResult(0);
                        },
                        //AuthenticationFailed = (context) =>
                        //{
                        //    context.OwinContext.Response.Redirect(new UrlHelper(HttpContext.Current.Request.RequestContext).
                        //        Action("Index", "Home", null, HttpContext.Current.Request.Url.Scheme));
                        //    context.HandleResponse(); // Suppress the exception
                        //    return Task.FromResult(0);
                        //}
                    }
                });
        }
 public override Task <string> GetLastTokenAsync()
 {
     return(Task.FromResult(GetLocalValue(SettingsUserNameKey)));
 }
Exemplo n.º 55
0
    public Task Handle(TrackZipCodeReply message, IMessageHandlerContext context)
    {
        Logger.Log($"##### CandidateVote saga for {Data.Candidate} got reply for zip code '{message.ZipCode}' tracking with current count of {message.CurrentCount}");

        return Task.FromResult(0);
    }
Exemplo n.º 56
0
 public AsyncLock()
 {
     this.semaphore = new SemaphoreSlim(1);
     this.releaser  = Task.FromResult(new Releaser(this));
 }
 private Task<string> serializeRequest<Rq>(Rq request) where Rq : class => Task.FromResult(request != null ? JsonSerializer.Serialize(request, options) : null);
 private Task<Rs> deserializeResponse<Rs>(string responseMessage) where Rs : class
 {
     return Task.FromResult(responseMessage != null ? JsonSerializer.Deserialize<Rs>(responseMessage, options) : null);
 }
Exemplo n.º 59
0
        private async Task Invoke(HubMethodDescriptor descriptor, HubConnectionContext connection,
                                  HubMethodInvocationMessage hubMethodInvocationMessage, bool isStreamResponse, bool isStreamCall)
        {
            var methodExecutor = descriptor.MethodExecutor;

            var disposeScope = true;
            var scope        = _serviceScopeFactory.CreateScope();
            IHubActivator <THub> hubActivator = null;
            THub hub = null;

            try
            {
                if (!await IsHubMethodAuthorized(scope.ServiceProvider, connection.User, descriptor.Policies))
                {
                    Log.HubMethodNotAuthorized(_logger, hubMethodInvocationMessage.Target);
                    await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                                              $"Failed to invoke '{hubMethodInvocationMessage.Target}' because user is unauthorized");

                    return;
                }

                if (!await ValidateInvocationMode(descriptor, isStreamResponse, hubMethodInvocationMessage, connection))
                {
                    return;
                }

                hubActivator = scope.ServiceProvider.GetRequiredService <IHubActivator <THub> >();
                hub          = hubActivator.Create();

                if (isStreamCall)
                {
                    // swap out placeholders for channels
                    var args = hubMethodInvocationMessage.Arguments;
                    for (int i = 0; i < args.Length; i++)
                    {
                        var placeholder = args[i] as StreamPlaceholder;
                        if (placeholder == null)
                        {
                            continue;
                        }

                        Log.StartingParameterStream(_logger, placeholder.StreamId);
                        var itemType = methodExecutor.MethodParameters[i].ParameterType.GetGenericArguments()[0];
                        args[i] = connection.StreamTracker.AddStream(placeholder.StreamId, itemType);
                    }
                }

                try
                {
                    InitializeHub(hub, connection);
                    Task invocation = null;

                    CancellationTokenSource cts = null;
                    var arguments = hubMethodInvocationMessage.Arguments;
                    if (descriptor.HasSyntheticArguments)
                    {
                        // In order to add the synthetic arguments we need a new array because the invocation array is too small (it doesn't know about synthetic arguments)
                        arguments = new object[descriptor.OriginalParameterTypes.Count];

                        var hubInvocationArgumentPointer = 0;
                        for (var parameterPointer = 0; parameterPointer < arguments.Length; parameterPointer++)
                        {
                            if (hubMethodInvocationMessage.Arguments.Length > hubInvocationArgumentPointer &&
                                hubMethodInvocationMessage.Arguments[hubInvocationArgumentPointer].GetType() == descriptor.OriginalParameterTypes[parameterPointer])
                            {
                                // The types match so it isn't a synthetic argument, just copy it into the arguments array
                                arguments[parameterPointer] = hubMethodInvocationMessage.Arguments[hubInvocationArgumentPointer];
                                hubInvocationArgumentPointer++;
                            }
                            else
                            {
                                // This is the only synthetic argument type we currently support
                                if (descriptor.OriginalParameterTypes[parameterPointer] == typeof(CancellationToken))
                                {
                                    cts = CancellationTokenSource.CreateLinkedTokenSource(connection.ConnectionAborted);
                                    arguments[parameterPointer] = cts.Token;
                                }
                                else
                                {
                                    // This should never happen
                                    Debug.Assert(false, $"Failed to bind argument of type '{descriptor.OriginalParameterTypes[parameterPointer].Name}' for hub method '{methodExecutor.MethodInfo.Name}'.");
                                }
                            }
                        }
                    }

                    if (isStreamResponse)
                    {
                        var result = await ExecuteHubMethod(methodExecutor, hub, arguments);

                        if (!TryGetStreamingEnumerator(connection, hubMethodInvocationMessage.InvocationId, descriptor, result, out var enumerator, ref cts))
                        {
                            Log.InvalidReturnValueFromStreamingMethod(_logger, methodExecutor.MethodInfo.Name);
                            await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                                                      $"The value returned by the streaming method '{methodExecutor.MethodInfo.Name}' is not a ChannelReader<>.");

                            return;
                        }

                        Log.StreamingResult(_logger, hubMethodInvocationMessage.InvocationId, methodExecutor);
                        _ = StreamResultsAsync(hubMethodInvocationMessage.InvocationId, connection, enumerator, scope, hubActivator, hub, cts);
                    }

                    else if (string.IsNullOrEmpty(hubMethodInvocationMessage.InvocationId))
                    {
                        // Send Async, no response expected
                        invocation = ExecuteHubMethod(methodExecutor, hub, arguments);
                    }

                    else
                    {
                        // Invoke Async, one reponse expected
                        async Task ExecuteInvocation()
                        {
                            var result = await ExecuteHubMethod(methodExecutor, hub, arguments);

                            Log.SendingResult(_logger, hubMethodInvocationMessage.InvocationId, methodExecutor);
                            await connection.WriteAsync(CompletionMessage.WithResult(hubMethodInvocationMessage.InvocationId, result));
                        }
                        invocation = ExecuteInvocation();
                    }

                    if (isStreamCall || isStreamResponse)
                    {
                        // don't await streaming invocations
                        // leave them running in the background, allowing dispatcher to process other messages between streaming items
                        disposeScope = false;
                    }
                    else
                    {
                        // complete the non-streaming calls now
                        await invocation;
                    }
                }
                catch (TargetInvocationException ex)
                {
                    Log.FailedInvokingHubMethod(_logger, hubMethodInvocationMessage.Target, ex);
                    await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                                              ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex.InnerException, _enableDetailedErrors));
                }
                catch (Exception ex)
                {
                    Log.FailedInvokingHubMethod(_logger, hubMethodInvocationMessage.Target, ex);
                    await SendInvocationError(hubMethodInvocationMessage.InvocationId, connection,
                                              ErrorMessageHelper.BuildErrorMessage($"An unexpected error occurred invoking '{hubMethodInvocationMessage.Target}' on the server.", ex, _enableDetailedErrors));
                }
            }
            finally
            {
                if (disposeScope)
                {
                    hubActivator?.Release(hub);
                    scope.Dispose();
                }
            }
        }
Exemplo n.º 60
0
        public async Task <ActionResult> SparkSvgAll <T>(Func <Node, Task <List <T> > > getPoints, Func <Node, List <T>, long> getMax, Func <T, double> getVal) where T : IGraphPoint
        {
            const int width = SparkPoints;

            var nodes         = Dashboard.AllNodes;
            var overallHeight = nodes.Count * SparkHeight;

            long nowEpoch   = DateTime.UtcNow.ToEpochTime(),
                 startEpoch = SparkStart.ToEpochTime();
            var range       = (nowEpoch - startEpoch) / (float)width;

            var sb = StringBuilderCache.Get()
                     .AppendFormat("<svg version=\"1.1\" baseProfile=\"full\" width=\"{0}\" height=\"{1}\" xmlns=\"http://www.w3.org/2000/svg\" preserveAspectRatio=\"none\">\n", width.ToString(), overallHeight.ToString())
                     .AppendLine("\t<style>")
                     .AppendFormat("\t\tline {{ stroke:{0}; stroke-width:1 }}\n", AxisColor)
                     .AppendFormat("\t\tpath {{ fill:{0}; stroke:none; }}\n", Color)
                     .AppendLine("\t</style>");

            var pointsLookup = new ConcurrentDictionary <string, List <T> >();
            var maxLookup    = new ConcurrentDictionary <string, long>();
            var lookups      = new List <Task>(nodes.Count);

            foreach (var node in nodes)
            {
                lookups.Add(getPoints(node).ContinueWith(t =>
                {
                    if (!t.IsFaulted)
                    {
                        pointsLookup[node.Id] = t.Result;
                        maxLookup[node.Id]    = getMax(node, t.Result);
                    }
                }));
            }
            await Task.WhenAll(lookups);

            int currentYTop = 0;

            foreach (var pl in pointsLookup)
            {
                sb.AppendFormat("\t<view id=\"{0}\" viewBox=\"0 {1} {2} {3}\" />\n", pl.Key, currentYTop, width, SparkHeight)
                .AppendFormat("\t<g transform=\"translate(0, {0})\">\n", currentYTop)
                .AppendFormat("\t\t<line x1=\"0\" y1=\"{0}\" x2=\"{1}\" y2=\"{0}\" />\n", SparkHeight.ToString(), width.ToString())
                .AppendFormat("\t\t<path d=\"M0 {0} L", SparkHeight);

                var  first   = true;
                long divisor = maxLookup[pl.Key] / SparkHeight;
                foreach (var p in pl.Value)
                {
                    var pos = (p.DateEpoch - startEpoch) / range;
                    if (first && pos > 0)
                    {
                        // TODO: Indicate a missing, ungraphed time portion?
                        sb.Append((pos - 1).ToString("f1", CultureInfo.InvariantCulture))
                        .Append(" ")
                        .Append(SparkHeight)
                        .Append(" ");
                        first = false;
                    }
                    sb.Append(pos.ToString("f1", CultureInfo.InvariantCulture)).Append(" ")
                    .Append((SparkHeight - (getVal(p) / divisor)).ToString("f1", CultureInfo.InvariantCulture)).Append(" ");
                }
                sb.Append(width)
                .Append(" ")
                .Append(SparkHeight)
                .Append(@" z""/>\n")
                .Append("\t</g>\n");

                currentYTop += SparkHeight;
            }

            sb.Append("</svg>");
            var bytes = Encoding.UTF8.GetBytes(sb.ToStringRecycle());

            return(new FileContentResult(bytes, "image/svg+xml"));
        }