コード例 #1
1
        public void Load(BulkLoad load)
        {
            var tasks = new Task[load.Collections.Count];

            int i = 0;
            foreach (var pair in load.Collections)
            {
                var bulkCollection = pair.Value;
                var collectionName = pair.Key;
                var keys = bulkCollection.Documents.Keys;

                var bsonIdArray = new BsonArray(keys);

                var collection = _mongoDatabase.GetCollection(bulkCollection.CollectionType, collectionName);

                tasks[i] = Task.Factory.StartNew(() =>
                {
                    MongoCursor cursor = collection.FindAs(bulkCollection.CollectionType, Query.In("_id", bsonIdArray));

                    foreach (var doc in cursor)
                    {
                        var id = _metadata.GetDocumentId(doc);
                        bulkCollection.Documents[id] = doc;
                    }
                });
                i++;
            }
            Task.WaitAll(tasks);
        }
コード例 #2
1
        private void RunTestLoop(int numberOfTasks, TaskScheduler[] schedulers)
        {
            var taskList = new List<Task>(numberOfTasks);

            for (int i = 0; i < numberOfTasks; i++)
            {
                int id = i; // capture
                Task t = new Task(() =>
                {
                    if (Verbose) output.WriteLine("Task: " + id);
                });

                if (schedulers == null || schedulers.Length == 0)
                {
                    t.Start();
                }
                else
                {
                    var scheduler = schedulers[i % schedulers.Length];
                    t.Start(scheduler);
                }

                taskList.Add(t);
            }

            Task.WaitAll(taskList.ToArray());
        }
コード例 #3
1
 protected override void ConfigureBus(IInMemoryBusFactoryConfigurator configurator)
 {
     configurator.ReceiveEndpoint("input_queue_error", x =>
     {
         _errorHandler = Handled<PingMessage>(x);
     });
 }
コード例 #4
1
 void LoginScreen_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
 {
     if (this.IsVisible)
     {
         dbInitializingTask = Task.Factory.StartNew(() => DBResources.Instance.ReInstanceDbContext());
     }
 }
コード例 #5
1
ファイル: TCPIPServer.cs プロジェクト: diogos88/LIB
        public void Start()
        {
            m_Listener.Start();
            m_Listen = true;

            m_AcceptTask = AcceptClients(m_Listener);
        }
コード例 #6
1
ファイル: BatchWorker.cs プロジェクト: MikeHardman/orleans
        // executes at the end of each work cycle
        // on the same task scheduler
        private void CheckForMoreWork()
        {
            Action signalThunk = null;

            lock (this)
            {
                if (moreWork)
                {
                    moreWork = false;

                    // see if someone created a promise for waiting for the next work cycle
                    // if so, take it and remove it
                    var x = this.nextWorkCyclePromise;
                    this.nextWorkCyclePromise = null;

                    // start the next work cycle
                    Start();

                    // if someone is waiting, signal them
                    if (x != null)
                        signalThunk = () => { x.SetResult(currentWorkCycle); };
                }
                else
                {
                    currentWorkCycle = null;
                }
            }

            // to be safe, must do the signalling out here so it is not under the lock
            if (signalThunk != null)
                signalThunk();
        }
コード例 #7
1
ファイル: Scheduler.cs プロジェクト: koush/mono
		protected internal override void QueueTask (Task t)
		{
			// Add to the shared work pool
			workQueue.TryAdd (t);
			// Wake up some worker if they were asleep
			PulseAll ();
		}
コード例 #8
1
        private TodoItemViewModel[] HandleResult(Task<TodoItemViewModel[]> task)
        {
            if (task.Exception != null)
            {
                IsFaulted = true;
                if (IsTrying == false)
                {
                    StartTrying(5);
                    return new TodoItemViewModel[0];
                }
                return new TodoItemViewModel[0];
            }

            IsFaulted = false;
            IsTrying = false;
            var result = task.Result;
            SetupCommands(result);

            if (ItemsList.IsRefreshing)
            {
                try
                {
                    ItemsList.IsRefreshing = false;
                    ItemsList.EndRefresh();
                }
                catch (Exception ex)
                {
                }
            }

            return result;
        }
コード例 #9
1
        /// <summary>
        /// Initializes a new instance of the <see cref="TaskDecoratorCoTask"/> class.
        /// </summary>
        /// <param name="task">The task.</param>
        public TaskDecoratorCoTask(Task task)
        {
            if (task == null)
                throw new ArgumentNullException(nameof(task));

            _innerTask = task;
        }
コード例 #10
1
        private static void OnBeginRequest(object sender, EventArgs e) {
            var context = (HttpApplication)sender;

            // TaskCreationOptions.PreferFairness 를 지정해야, StartNew() 메소드를 바로 시작한다.
            var stopwatchTask
                = new Task<Lazy<double>>(() => {
                                             var sw = new Stopwatch();
                                             sw.Start();

                                             if(IsDebugEnabled) {
                                                 var request = context.Request;
                                                 log.Debug(BeginRequestLogFormat,
                                                           request.UserHostAddress,
                                                           request.RequestType,
                                                           request.CurrentExecutionFilePath);
                                             }

                                             // Lazy 값을 처음 호출할 때, stop watch가 끝나고, 경과 값을 반환한다.
                                             return new Lazy<double>(() => {
                                                                         sw.Stop();
                                                                         return sw.ElapsedMilliseconds;
                                                                     });
                                         });
            stopwatchTask.Start();

            Local.Data[AsyncAccessLogModuleKey] = stopwatchTask;
        }
コード例 #11
1
ファイル: RelayCommad.cs プロジェクト: mgrman/SteamPaver
 public async void Execute(object parameter)
 {
     asyncExecutingTask = this.asyncExecute();
     await asyncExecutingTask;
     asyncExecutingTask = null;
     CommandManager.InvalidateRequerySuggested();
 }
コード例 #12
1
ファイル: MainWindow.xaml.cs プロジェクト: srstrong/DDDSW2010
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            // For best results use 1024 x 768 jpg files at 32bpp.
            string[] files = System.IO.Directory.GetFiles(@"C:\Users\Public\Pictures\Sample Pictures\", "*.jpg");

            _fileCount = files.Length;
            var loadImageTasks = new Task<byte[]>[_fileCount];

            // Spin off a task to load each image
            for (var i = 0; i < _fileCount; i++)
            {
                var x = i;
                loadImageTasks[x] = Task.Factory.StartNew(() => LoadImage(files[x]));
            }

            // When they've all been loaded, tile them into a single byte array.
            var tiledImageTask = Task.Factory.ContinueWhenAll(loadImageTasks, i => TileImages(i));

            // We are currently on the UI thread. Save the sync context and pass it to
            // the next task so that it can access the UI control "image1".
            var uiSyncContext = TaskScheduler.FromCurrentSynchronizationContext();

            // On the UI thread, put the bytes into a bitmap and
            // and display it in the Image control.
            tiledImageTask.ContinueWith(antedecent => LoadTiledImage(antedecent.Result), uiSyncContext);
        }
コード例 #13
0
        public static void Main(string[] args)
        {
            Console.Clear();
            string[] urls = args;
            if(args.Length == 0)
            {
                urls = new string[]  
          {
              "http://www.habitat-spokane.org",
              "http://www.partnersintl.org",
              "http://www.iassist.org ",
              "http://www.fh.org",
              "http://www.worldvision.org"
          };
            }
            Task[] tasks = new Task[urls.Length];
            for(int line = 0; line < urls.Length; line++)
            {
                tasks[line] = DisplayPageSizeAsync(
                    urls[line], line);
            }

            while(!Task.WaitAll(tasks, 50))
            {
                DisplayProgress(tasks);
            }
            Console.SetCursorPosition(0, urls.Length);
        }
コード例 #14
0
 public GeoViewModel(MetroTwitStatusBase Tweet)
 {
     this.ShowAnimation = true;
       this.LinkCommand = new RelayCommand<string>(new Action<string>(CommonCommands.OpenLink));
       Coordinate coordinate = Tweet.Coordinates != null ? Tweet.Coordinates.Coordinate[0] : Tweet.Geo.BoundingBox.Coordinates[0];
       if (coordinate != null)
       {
     Task task = new Task((Action) (() => this.GeoLookup(coordinate)));
     task.ContinueWith((Action<Task>) (t => CommonCommands.CheckTaskExceptions(t)));
     task.Start();
     object resource = Application.Current.FindResource((object) "ModernColorFeature");
     string PinColour = resource == null ? "blue" : "0x" + resource.ToString().Remove(0, 3);
     this.GeoImageURI = CoreServices.Instance.CurrentMapService.StaticMapURL(coordinate.Latitude, coordinate.Longitude, 320, 320, PinColour);
     GeoViewModel geoViewModel = this;
     double num = coordinate.Latitude;
     string str1 = num.ToString((IFormatProvider) CultureInfo.InvariantCulture.NumberFormat);
     string str2 = ", ";
     num = coordinate.Longitude;
     string str3 = num.ToString((IFormatProvider) CultureInfo.InvariantCulture.NumberFormat);
     string str4 = str1 + str2 + str3;
     geoViewModel.GeoPlaceText = str4;
     this.LiveMapURL = CoreServices.Instance.CurrentMapService.LiveMapURL(coordinate.Latitude, coordinate.Longitude);
       }
       this.ShowAnimation = false;
 }
コード例 #15
0
        public override void ImageGrabbedHandler(object sender, EventArgs e)
        {
            if (_transmitTask == null || _transmitTask.IsCompleted)
            {
                using (var matCaptured = new Mat())
                {
                    CameraCapture.Retrieve(matCaptured);
                    var bgrImage = matCaptured.ToImage<Bgr, byte>();
                    WriteText(bgrImage, 30, DateTime.Now.ToString("HH:mm:ss tt"));
                    imageBoxCaptured.Image = bgrImage;

                    IImageTransmitter transmitter = null;
                    if (radBsonImage.Checked)
                    {
                        transmitter = _imageTransmitter;
                    }

                    if (radBsonJpeg.Checked)
                    {
                        transmitter = _jpegTransmitter;
                    }

                    if (transmitter != null)
                    {
                        _transmitTask = transmitter.Transmit(bgrImage);
                    }
                }
            }
        }
コード例 #16
0
        // *** Methods ***

        public static async void InjectAsyncExceptions(Task task)
        {
            // Await the task to allow any exceptions to be thrown

            try
            {
                await task;
            }
            catch (Exception e)
            {
                // If we are currently on the core dispatcher then we can simply rethrow the exception
                // NB: This will occur if awaiting the task returned immediately

                CoreDispatcher dispatcher = CoreApplication.GetCurrentView().CoreWindow.Dispatcher;

                if (dispatcher.HasThreadAccess)
                    throw;

                // Otherwise capture the exception with its original stack trace

                ExceptionDispatchInfo exceptionDispatchInfo = ExceptionDispatchInfo.Capture(e);

                // Re-throw the exception via a DispatcherTimer (this will then be captured by the Application.UnhandledException event)

                DispatcherTimer timer = new DispatcherTimer();
                timer.Tick += (sender, args) =>
                {
                    timer.Stop();
                    exceptionDispatchInfo.Throw();
                };
                timer.Start();
            }
        }
コード例 #17
0
        protected internal override void QueueTask(Task task)
        {
#if !FEATURE_PAL && !FEATURE_CORECLR    // PAL and CoreClr don't support  eventing
            var etwLog = TplEtwProvider.Log;
            if (etwLog.IsEnabled(EventLevel.Verbose, ((EventKeywords)(-1))))
            {
                Task currentTask = Task.InternalCurrent;
                Task creatingTask = task.m_parent;

                etwLog.TaskScheduled(this.Id, currentTask == null ? 0 : currentTask.Id,
                                                 task.Id, creatingTask == null ? 0 : creatingTask.Id,
                                                 (int)task.Options);
            }
#endif

            if ((task.Options & TaskCreationOptions.LongRunning) != 0)
            {
                NativeThreadPool.QueueLongRunningWork(() => task.ExecuteEntry(false));
            }
            else
            {
                // Normal handling for non-LongRunning tasks.
                bool forceToGlobalQueue = ((task.Options & TaskCreationOptions.PreferFairness) != 0);
                ThreadPool.UnsafeQueueCustomWorkItem(task, forceToGlobalQueue);
            }
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: jeremywho/OpenKeyVal.NET
 static void Main()
 {
     try
     {
         var tester = new OpenKeyValTester();
         var t = new Task(async () =>
             {
                 await tester.RunTests();
             });
         t.Start();
         t.Wait();
         
         Console.WriteLine("Done.");
         Console.ReadLine();
     }
     catch (WebException we)
     {
         Console.WriteLine("WebException: Message");
         Console.WriteLine(we.Message);
         Console.ReadLine();
     }
     catch (Exception ex)
     {
         Console.WriteLine("Exception:");
         Console.WriteLine(ex.Message);
         Console.ReadLine();
     }
 }
コード例 #19
0
        public Task CreateRemoteThread(MemoryWriter writer)
        {
            UIntPtr bytesWriten;
            Win32.WriteProcessMemory(processInfo.hProcess, writer.TargetStartAddress, writer.Buffer,
                (uint)writer.Size, out bytesWriten);

            //lastWin32Error = Marshal.GetLastWin32Error();

            Win32.FlushInstructionCache(processInfo.hProcess, writer.TargetStartAddress, new UIntPtr((uint)writer.Size));

            //lastWin32Error = Marshal.GetLastWin32Error();

            IntPtr hThread = Win32.CreateRemoteThread(processInfo.hProcess, IntPtr.Zero, 0, writer.CodeTargetStartAddress,
                IntPtr.Zero, 0, IntPtr.Zero);

            //lastWin32Error = Marshal.GetLastWin32Error();

            Task task = new Task(() =>
                {
                    Win32.WaitForSingleObject(hThread, Win32.INFINITE);

                    // Free the memory in the process that we allocated
                    Win32.VirtualFreeEx(processInfo.hProcess, writer.TargetStartAddress, 0, Win32.FreeType.Release);
                });
            task.Start();

            return task;
        }
コード例 #20
0
		/// <summary>
		///		Añade una tarea a la cola y la ejecuta
		/// </summary>
		public void Process(AbstractProcessor objProcessor)
		{ Task objTask;
				
				// Añade el procesador a la cola
					Queue.Add(objProcessor);
				// Asigna los manejador de eventos
					objProcessor.ActionProcess += (objSender, objEventArgs) =>
																						{ if (ActionProcess != null)
																								ActionProcess(objSender, objEventArgs);
																						};
					objProcessor.Progress += (objSender, objEventArgs) =>
																			{ if (Progress != null)
																					Progress(objSender, objEventArgs);
																			};
					objProcessor.ProgressAction += (objSender, objEventArgs) =>
																						{ if (ProgressAction != null)
																								ProgressAction(objSender, objEventArgs);
																						};
					objProcessor.EndProcess += (objSender, objEventArgs) =>
																			{ TreatEndProcess(objSender as AbstractProcessor, objEventArgs);
																			};
				// Crea la tarea para la compilación en otro hilo
					objTask = new Task(() => objProcessor.Process());
				// Arranca la tarea de generación
					try
						{ objTask.Start();
						}
					catch (Exception objException)
						{ TreatEndProcess(objProcessor, 
															new EventArguments.EndProcessEventArgs("Error al lanzar el proceso" + Environment.NewLine + objException.Message,
																																		 new List<string> {objException.Message } ));
						}
		}
コード例 #21
0
        private async void BillShiftSelectionForm_Load(object sender, EventArgs e)
        {
            ShowWaitPanel();
            SettingsHelper.Instance.RestoreLayout(gvSelectBillShift);
            gvSelectBillShift.ActiveFilterString = string.Empty;

            var listBills = new List<BillShift>();
            var listOpers = new List<TechOperation>();
            var listOrders = new List<Order>();

            var taskOpers = new Task(() => { listOpers = _controller.GetTechOperationsList(); });
            taskOpers.Start();

            var taskOrders = new Task(() => { listOrders = _controller.GetOrdersList(); });
            taskOrders.Start();

            var taskBills = new Task(() =>
            {
                listBills = Filter != null ? _controller.GetBillShiftsList().Where(Filter).ToList() : _controller.GetBillShiftsList();
            });
            taskBills.Start();

            var taskCommon = new Task(() => Task.WaitAll(taskOpers, taskOrders, taskBills));
            taskCommon.Start();
            await taskCommon;

            gcBills.DataSource = listBills;
            repoOrders.DataSource = listOrders;
            repoTechOpers.DataSource = listOpers;

            HideWaitPanel();
        }
コード例 #22
0
        public void AsyncHTTPICmd()
        {
            FileStream stream;
            stream = File.Create(outputFileHTTPAsync);
            results = new StreamWriter(stream);
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();

            ICmd validICmd = new ICmd(TestGlobals.testServer, TestGlobals.validSerial);
            Test validTest = new Test(validICmd);
            validTest.setTestName("ValidSerial");
            validTest.setExpectedResult ("200");
            validTest.setType ("performance");
            List<Test> tests = new List<Test>();
            tests.Add(validTest);

            // Construct started tasks
            Task<double>[] tasks = new Task<double>[TestGlobals.maxReps];
            for (int i = 0; i < TestGlobals.maxReps; i++)
            {
                System.Threading.Thread.Sleep(TestGlobals.delay);
                tasks[i] = new HTTPCalls().runTest(validTest, HTTPOperation.GET);
                Console.WriteLine("Test starting:" + i.ToString());
            }
            Console.WriteLine("------------------------------------------------------");
            Console.WriteLine("All tests initialized, waiting on them to run as async");
            Console.WriteLine("------------------------------------------------------");
            Task.WaitAll(tasks);

            foreach (Task<double> nextResult in tasks)
            {
                results.WriteLine("Test Time," + nextResult.Result);
            }

            results.Close();
        }
コード例 #23
0
 public static void LogHttpResponse(this DiagnosticListener @this, Task<HttpResponseMessage> responseTask, Guid loggingRequestId)
 {
     if (@this.IsEnabled(HttpHandlerLoggingStrings.ResponseWriteName))
     {
         ScheduleLogResponse(@this, responseTask, loggingRequestId);
     }
 }
コード例 #24
0
        protected override void Init(ISettingsPageHost aPageHost)
        {
            base.Init(aPageHost);

            _populateBuildServerTypeTask =
                Task.Factory.StartNew(() =>
                        {
                            var exports = ManagedExtensibility.CompositionContainer.GetExports<IBuildServerAdapter, IBuildServerTypeMetadata>();
                            var buildServerTypes = exports.Select(export =>
                                {
                                    var canBeLoaded = export.Metadata.CanBeLoaded;
                                    return export.Metadata.BuildServerType.Combine(" - ", canBeLoaded);
                                }).ToArray();

                            return buildServerTypes;
                        })
                    .ContinueWith(
                        task =>
                            {
                                checkBoxEnableBuildServerIntegration.Enabled = true;
                                checkBoxShowBuildSummary.Enabled = true;
                                BuildServerType.Enabled = true;

                                BuildServerType.DataSource = new[] { NoneItem }.Concat(task.Result).ToArray();
                                return BuildServerType.DataSource;
                            },
                        TaskScheduler.FromCurrentSynchronizationContext());
        }
コード例 #25
0
        public void run(int seconds)
        {
            var tsks = new HashSet<Task>();
            durationSeconds = seconds;
            var metrics = Metric.Context("shared");
            foreach (var t in tasks)
            {
                t.Duration = durationSeconds;

                if (sharedMetrics > 0)
                {
                    t.metrics = metrics;
                }
                else
                {
                    t.metrics = Metric.Context(t.ToString());
                }
                var task = new Task(() => t.Call(),TaskCreationOptions.LongRunning);
                task.Start();
                tsks.Add(task);
            }
            try
            {

                Task.WaitAll(tsks.ToArray());
            }
            catch (Exception)
            {
            }
            Console.WriteLine("TASKS COMPLETE ");
        }
コード例 #26
0
 public void Execute(Envelope envelope, ContinuationContext context)
 {
     _task = Task.Factory.StartNew(() => {
         var continuation = _inner();
         continuation.Execute(envelope, context);
     });
 }
コード例 #27
0
        private void HandlePromptResponse(
            Task<ShowChoicePromptResponse> responseTask)
        {
            if (responseTask.IsCompleted)
            {
                ShowChoicePromptResponse response = responseTask.Result;

                if (!response.PromptCancelled)
                {
                    this.consoleService.ReceivePromptResponse(
                        response.ChosenItem,
                        false);
                }
                else
                {
                    // Cancel the current prompt
                    this.consoleService.SendControlC();
                }
            }
            else
            {
                if (responseTask.IsFaulted)
                {
                    // Log the error
                    Logger.Write(
                        LogLevel.Error,
                        "ShowChoicePrompt request failed with error:\r\n{0}",
                        responseTask.Exception.ToString());
                }

                // Cancel the current prompt
                this.consoleService.SendControlC();
            }
        }
コード例 #28
0
ファイル: PrintController.cs プロジェクト: ctukc-nt/UPPY_v2
        public async Task PrintPassportWithTechOeprs(int? orderId)
        {
            var order = _dataManagersFactory.GetDataManager<Order>().GetDocument(orderId);

            var task = new Task(() =>
            {
                var topParentId = order.DrawingId;
                var dm = _dataManagersFactory.GetFilteredDrawingsByContainsId(topParentId);
                var header = _dataManagersFactory.GetDataManager<Drawing>().GetDocument(topParentId);
                var hierarchy = CreateHierarchyNumbers(dm.GetListCollection(), header);
                hierarchy = hierarchy.OrderBy(x => x.HierarchyNumber, new HierarchyNumberDrawingComparer()).ToList();
                var tos =
                    _dataManagersFactory.GetDataManager<TechOperation>()
                        .GetListCollection()
                        .OrderBy(x => x.OrderInPrint)
                        .ToList();
                var trs = _dataManagersFactory.GetDataManager<TechRoute>().GetListCollection();

                _dataExport.CreatePassportProjectToFile(order, hierarchy, tos, trs);
            });

            task.Start();

            await task;

            _dataExport.SaveReport(order.Name);
        }
コード例 #29
0
        public List<int> Execute(int minPrime, int maxPrime, int degree)
        {
            var subTasks = new Task[degree];

            int mx = _primes.Max();
            if (mx < maxPrime)
            {
                int current = mx+1;

                for (int i = 0; i < degree; i++, current++)
                {
                    int c1 = current;
                    subTasks[i] = new Task(() => { if (CheckPrime(c1)) AddToPrimesList(c1); });
                    subTasks[i].Start();
                }

                while (current < maxPrime)
                {
                    int t = Task.WaitAny(subTasks);
                    int c = current;

                    subTasks[t].Dispose();
                    subTasks[t] = new Task(() => { if (CheckPrime(c)) AddToPrimesList(c); });
                    subTasks[t].Start();

                    current++;
                }
                Task.WaitAll(subTasks);
            }
            return _primes.ToList();
        }
コード例 #30
0
ファイル: PostOrder.cs プロジェクト: daymonc/Draw_Graph
 public override async void Execute(Vertex start)
 {
     Initialize();
     algTask = Postorder(start);
     await algTask;
     base.Execute();
 }
コード例 #31
0
        /// <summary>
        /// Pings the server to download version compatibility information and stores this in a cached file in the users app data. If the cached file is
        /// less than 24 hours old, it uses that data. Otherwise it downloads from the server. If the download fails it will use the previously cached
        /// file, or if that file doesn't not exist, it uses the data baked into this class
        /// </summary>
        private VersionCompatibilityData GetVersionCompatibilityData()
        {
            // Do we need to update our cached data? Note that since the download could take a long time like tens of seconds we don't really want to
            // start showing messages to the user well after their project is opened and they are interacting with it. Thus we start a task to update the
            // file, so that the next time we come here, we have updated data.
            if (CurrentVersionCompatibilityData != null && _timeCurVersionDataLastUpdatedUtc.AddHours(s_cacheFileValidHours) > DateTime.UtcNow)
            {
                return(CurrentVersionCompatibilityData);
            }

            try
            {
                // Try the cache file
                Dictionary <Version, VersionCompatibilityData>?versionCompatData = GetCompatibilityDataFromCacheFile();

                // See if the cache file needs refreshing and if so, kick off a task to do so
                if (_versionDataCacheFile != null && _versionDataCacheFile.CacheFileIsStale())
                {
                    Task noWait = _versionDataCacheFile.TryToUpdateCacheFileAsync(() =>
                    {
                        // Invalidate the in-memory cached data on success
                        _timeCurVersionDataLastUpdatedUtc = DateTime.MinValue;
                    });
                }

                if (versionCompatData != null && VisualStudioVersion != null)
                {
                    // First try to match exactly on our VS version and if that fails, match on just major, minor
                    if (versionCompatData.TryGetValue(VisualStudioVersion, out VersionCompatibilityData compatData) || versionCompatData.TryGetValue(new Version(VisualStudioVersion.Major, VisualStudioVersion.Minor), out compatData))
                    {
                        // Now fix up missing data
                        if (string.IsNullOrEmpty(compatData.OpenSupportedMessage))
                        {
                            compatData.OpenSupportedMessage = VSResources.PartialSupportedDotNetCoreProject;
                        }

                        if (string.IsNullOrEmpty(compatData.OpenUnsupportedMessage))
                        {
                            compatData.OpenUnsupportedMessage = VSResources.NotSupportedDotNetCoreProject;
                        }

                        CurrentVersionCompatibilityData   = compatData;
                        _timeCurVersionDataLastUpdatedUtc = DateTime.UtcNow;
                    }
                }
            }
            catch
            {
            }

            if (CurrentVersionCompatibilityData == null)
            {
                // Something failed or no remote file,  use the compatibility data we shipped with which does not have any warnings
                CurrentVersionCompatibilityData = new VersionCompatibilityData
                {
                    OpenSupportedMessage   = VSResources.PartialSupportedDotNetCoreProject,
                    OpenUnsupportedMessage = VSResources.NotSupportedDotNetCoreProject
                };
                _timeCurVersionDataLastUpdatedUtc = DateTime.UtcNow;
            }

            return(CurrentVersionCompatibilityData);
        }
コード例 #32
0
        /// <summary>
        /// Returns an object that is passed into the constructor of <see cref="ReferenceWindow"/>.
        /// </summary>
        protected override async Task <object> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken)
        {
            await Task.Delay(4000); // simulate long running initialization

            return(ReferenceWindow.Title);
        }
コード例 #33
0
 public Task <TaskResult> Execute(ConductorTask task)
 {
     Console.WriteLine("Doing some work");
     return(Task.FromResult(task.Completed()));
 }
コード例 #34
0
        public Файл ВыводОтчета(string НазваниеОтчета, string ИсходныйКод, string ИсходныйФорматОтчета, ФорматОтчета ФорматОтчета, ШаблонОтчета.Ориентация Ориентация, DataSet ds, Хранилище Хранилище, string user, string domain)
        {
            var file = null as Файл;

            try
            {
                if (ds == null)
                {
                    new Exception("Не определен DataSet");
                }

                var extension = string.Empty;
                var mime      = MimeType.НеОпределен;
                switch (ИсходныйФорматОтчета)
                {
                case "Xps":
                    extension = "xps";
                    mime      = MimeType.Xps;
                    break;

                case "Excel":
                    extension = "xls";
                    mime      = MimeType.Excel;
                    break;

                case "Word":
                    extension = "doc";
                    mime      = MimeType.Word;
                    break;

                case "Text Plain":
                    extension = "txt";
                    mime      = MimeType.Text;
                    break;

                case "Excel-PDF":
                case "Word-PDF":
                    extension = "pdf";
                    break;

                default:
                    throw new Exception("Не верно указан 'Исходный формат отчета'");
                }
                file = new Файл()
                {
                    Name = string.Format("{0}_{1:yyyymmdd_HHmmss}.{2}", FileNameValid(НазваниеОтчета), DateTime.Now, extension), MimeType = mime
                };
                var task = new System.Threading.Tasks.Task(() =>
                {
                    try
                    {
                        using (var msXml = new MemoryStream())
                        {
                            var processor   = new Saxon.Api.Processor();
                            var compiler    = processor.NewXsltCompiler();
                            var transformer = compiler.Compile(new StringReader(ИсходныйКод)).Load();
                            var dest        = new Saxon.Api.TextWriterDestination(XmlTextWriter.Create(msXml));

                            transformer.InitialContextNode = processor.NewDocumentBuilder().Build(new XmlDataDocument(ds));
                            transformer.Run(dest);

                            switch (ИсходныйФорматОтчета)
                            {
                            case "Xps":
                                {
                                    file.MimeType = MimeType.Xps;
                                    switch (ФорматОтчета)
                                    {
                                        #region Отчет Xaml (по-умолчанию)
                                    case ФорматОтчета.Xaml:
                                    case ФорматОтчета.ПоУмолчанию:
                                        {
                                            file.Stream = msXml.ToArray();
                                        }
                                        break;
                                        #endregion

                                        #region Отчет Xps
                                    case ФорматОтчета.Xps:
                                    default:
                                        {
                                            var documentUri = Path.GetTempFileName();
                                            try
                                            {
                                                msXml.Position = 0;
                                                var sourceDoc  = XamlReader.Load(msXml) as IDocumentPaginatorSource;

                                                var doc = new XpsDocument(documentUri, FileAccess.Write, CompressionOption.Normal);
                                                var xsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false);
                                                var pgn = sourceDoc.DocumentPaginator;
                                                // 1cm = 38px
                                                switch (Ориентация)
                                                {
                                                case ШаблонОтчета.Ориентация.Альбом:
                                                    {
                                                        pgn.PageSize = new System.Windows.Size(29.7 * (96 / 2.54), 21 * (96 / 2.54));
                                                    }
                                                    break;

                                                case ШаблонОтчета.Ориентация.Книга:
                                                default:
                                                    {
                                                        pgn.PageSize = new System.Windows.Size(21 * (96 / 2.54), 29.7 * (96 / 2.54));
                                                    }
                                                    break;
                                                }
                                                //необходимо фиксированно указать размер колонки документа иначе при
                                                //построении часть данных будет срезано
                                                if (sourceDoc is FlowDocument)
                                                {
                                                    ((FlowDocument)sourceDoc).ColumnWidth = pgn.PageSize.Width;
                                                }
                                                xsm.SaveAsXaml(pgn);

                                                doc.Close();
                                                file.Stream = System.IO.File.ReadAllBytes(documentUri);
                                            }
                                            finally
                                            {
                                                if (System.IO.File.Exists(documentUri))
                                                {
                                                    System.IO.File.Delete(documentUri);
                                                }
                                            }
                                        }
                                        break;
                                        #endregion
                                    }
                                }
                                break;

                            case "TextPlain":
                                {
                                    file.MimeType = MimeType.Text;
                                    file.Stream   = msXml.ToArray();
                                }
                                break;

                            case "Word-PDF":
                                {
                                    #region generate
                                    object paramSourceDocPath = Path.GetTempFileName();
                                    object paramMissing       = System.Type.Missing;

                                    System.IO.File.WriteAllBytes((string)paramSourceDocPath, msXml.ToArray());
                                    if (!System.IO.File.Exists((string)paramSourceDocPath))
                                    {
                                        throw new Exception(string.Format("Исходный файл для генерации отчета не найден '{0}'", paramSourceDocPath));
                                    }

                                    var wordApplication     = null as Microsoft.Office.Interop.Word.Application;
                                    var wordDocument        = null as Document;
                                    var paramExportFilePath = GetTempFilePathWithExtension(".pdf");
                                    try
                                    {
                                        wordApplication = new Microsoft.Office.Interop.Word.Application()
                                        {
                                            DisplayAlerts = WdAlertLevel.wdAlertsNone
                                        };

                                        var paramExportFormat       = WdExportFormat.wdExportFormatPDF;
                                        var paramOpenAfterExport    = false;
                                        var paramExportOptimizeFor  = WdExportOptimizeFor.wdExportOptimizeForPrint;
                                        var paramExportRange        = WdExportRange.wdExportAllDocument;
                                        var paramStartPage          = 0;
                                        var paramEndPage            = 0;
                                        var paramExportItem         = WdExportItem.wdExportDocumentContent;
                                        var paramIncludeDocProps    = true;
                                        var paramKeepIRM            = true;
                                        var paramCreateBookmarks    = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                                        var paramDocStructureTags   = true;
                                        var paramBitmapMissingFonts = true;
                                        var paramUseISO19005_1      = false;

                                        // Open the source document.
                                        wordDocument = wordApplication.Documents.Open(
                                            ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing, ref paramMissing, ref paramMissing,
                                            ref paramMissing);

                                        // Export it in the specified format.
                                        if (wordDocument != null)
                                        {
                                            wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                                             paramExportFormat, paramOpenAfterExport,
                                                                             paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                                             paramEndPage, paramExportItem, paramIncludeDocProps,
                                                                             paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                                             paramBitmapMissingFonts, paramUseISO19005_1,
                                                                             ref paramMissing);
                                        }

                                        if (!System.IO.File.Exists(paramExportFilePath))
                                        {
                                            throw new Exception(string.Format("Word-PDF: Файл отчета не найден '{0}'", paramExportFilePath));
                                        }

                                        if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                        {
                                            file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                        }

                                        file.Stream = System.IO.File.ReadAllBytes(paramExportFilePath);
                                    }
                                    finally
                                    {
                                        // Close and release the Document object.
                                        if (wordDocument != null)
                                        {
                                            wordDocument.Close(false, ref paramMissing, ref paramMissing);
                                            wordDocument = null;
                                        }

                                        // Quit Word and release the ApplicationClass object.
                                        if (wordApplication != null)
                                        {
                                            wordApplication.Quit(false, ref paramMissing, ref paramMissing);
                                            wordApplication = null;

                                            GC.Collect();
                                            GC.WaitForPendingFinalizers();
                                            GC.Collect();
                                        }

                                        if (System.IO.File.Exists((string)paramSourceDocPath))
                                        {
                                            System.IO.File.Delete((string)paramSourceDocPath);
                                        }
                                        if (System.IO.File.Exists(paramExportFilePath))
                                        {
                                            System.IO.File.Delete(paramExportFilePath);
                                        }

                                        //var sb = new StringBuilder();
                                        //sb.AppendLine((string)paramSourceDocPath);
                                        //sb.AppendLine(paramExportFilePath);
                                        //ConfigurationClient.WindowsLog(sb.ToString(), "", domain);
                                    }
                                    #endregion
                                }
                                break;

                            case "Excel-PDF":
                                {
                                    #region generate
                                    object paramSourceDocPath = Path.GetTempFileName();
                                    object paramMissing       = System.Type.Missing;

                                    System.IO.File.WriteAllBytes((string)paramSourceDocPath, msXml.ToArray());
                                    if (!System.IO.File.Exists((string)paramSourceDocPath))
                                    {
                                        throw new Exception(string.Format("Исходный файл для генерации отчета не найден '{0}'", paramSourceDocPath));
                                    }

                                    var excelApplication = new Microsoft.Office.Interop.Excel.Application()
                                    {
                                        DisplayAlerts = false
                                    };
                                    var excelDocument = null as Workbook;

                                    var paramExportFilePath   = GetTempFilePathWithExtension(".pdf");
                                    var paramExportFormat     = XlFixedFormatType.xlTypePDF;
                                    var paramExportQuality    = XlFixedFormatQuality.xlQualityStandard;
                                    var paramOpenAfterPublish = false;
                                    var paramIncludeDocProps  = true;
                                    var paramIgnorePrintAreas = true;
                                    var paramFromPage         = System.Type.Missing;
                                    var paramToPage           = System.Type.Missing;

                                    try
                                    {
                                        // Open the source document.
                                        excelDocument = excelApplication.Workbooks.Open(
                                            (string)paramSourceDocPath, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing,
                                            paramMissing, paramMissing, paramMissing);

                                        // Export it in the specified format.
                                        if (excelDocument != null)
                                        {
                                            excelDocument.ExportAsFixedFormat(paramExportFormat,
                                                                              paramExportFilePath, paramExportQuality,
                                                                              paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage,
                                                                              paramToPage, paramOpenAfterPublish,
                                                                              paramMissing);
                                        }

                                        if (!System.IO.File.Exists(paramExportFilePath))
                                        {
                                            throw new Exception(string.Format("Файл отчета не найден '{0}'", paramExportFilePath));
                                        }

                                        if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                        {
                                            file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                        }

                                        file.Stream = System.IO.File.ReadAllBytes(paramExportFilePath);
                                    }
                                    finally
                                    {
                                        // Close and release the Document object.
                                        if (excelDocument != null)
                                        {
                                            excelDocument.Close(false, paramMissing, paramMissing);
                                            excelDocument = null;
                                        }

                                        // Quit Word and release the ApplicationClass object.
                                        if (excelApplication != null)
                                        {
                                            excelApplication.Quit();
                                            excelApplication = null;
                                        }

                                        if (System.IO.File.Exists((string)paramSourceDocPath))
                                        {
                                            System.IO.File.Delete((string)paramSourceDocPath);
                                        }
                                        if (System.IO.File.Exists(paramExportFilePath))
                                        {
                                            System.IO.File.Delete(paramExportFilePath);
                                        }

                                        GC.Collect();
                                        GC.WaitForPendingFinalizers();
                                        GC.Collect();
                                        GC.WaitForPendingFinalizers();
                                    }
                                    #endregion
                                }
                                break;

                            default:
                                {
                                    if (Enum.IsDefined(typeof(MimeType), ИсходныйФорматОтчета))
                                    {
                                        file.MimeType = (MimeType)Enum.Parse(typeof(MimeType), ИсходныйФорматОтчета);
                                    }

                                    file.Stream = msXml.ToArray();
                                }
                                break;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ConfigurationClient.WindowsLog(ex.ToString(), user, domain, "ВыводОтчета");
                    }
                });
                task.Start();
                task.Wait();
            }
            catch (Exception ex)
            {
                ConfigurationClient.WindowsLog(ex.ToString(), user, domain, "ВыводОтчета");
            }
            return(file);
        }
コード例 #35
0
 public async Task <Customer> GetById(int id)
 {
     return(await Task.Run(() => _baseContext.Customers.SingleOrDefault(i => i.Id == id)).ConfigureAwait(false));
 }
コード例 #36
0
        /// <summary>
        /// Initializes the proxy.
        /// </summary>
        /// <param name="projectId">
        /// The project id.
        /// </param>
        private void Init(string projectId)
        {
            Task.Run(() =>
            {
                try
                {
                    var visualStudioProject = IntellisenseProxy.GetVisualStudioProjectByUniqueName(projectId);
                    var projectName         = "Unknown project";
                    var configFile          = (string)null;
                    var assemblies          = new string[0];

                    if (visualStudioProject != null)
                    {
                        projectName = visualStudioProject.Project.Name;

                        try
                        {
                            this.referencesEvents = visualStudioProject.Events.ReferencesEvents;

                            this.referencesEvents.ReferenceAdded   += this.ReferencesUpdated;
                            this.referencesEvents.ReferenceChanged += this.ReferencesUpdated;
                            this.referencesEvents.ReferenceRemoved += this.ReferencesUpdated;
                        }
                        catch (NotImplementedException)
                        {
                            //// CPS does not have reference events.
                        }

                        try
                        {
                            this.importsEvents                = visualStudioProject.Events.ImportsEvents;
                            this.importsEvents.ImportAdded   += this.ImportsUpdated;
                            this.importsEvents.ImportRemoved += this.ImportsUpdated;
                        }
                        catch (NotImplementedException)
                        {
                            //// CPS does not have import events.
                        }

                        configFile = visualStudioProject.Project.ProjectItems.OfType <ProjectItem>().FirstOrDefault(i => i.Name.EndsWith(".config", StringComparison.OrdinalIgnoreCase))?.FileNames[0];

                        assemblies = visualStudioProject.References.Cast <Reference>()
                                     .Where(r =>
                        {
                            try
                            {
                                return(!string.IsNullOrEmpty(r.Path));
                            }
                            catch
                            {
                                return(false);
                            }
                        })
                                     .Select(r => r.Path)
                                     .ToArray();
                    }

                    var setupInfomation = AppDomain.CurrentDomain.SetupInformation;

                    setupInfomation.ApplicationBase    = string.Empty;
                    setupInfomation.ConfigurationFile  = configFile;
                    setupInfomation.LoaderOptimization = LoaderOptimization.SingleDomain;

                    AppDomain.CurrentDomain.AssemblyResolve += IntellisenseProxy.AppDomainFix;

                    this.appDomain = AppDomain.CreateDomain($"Intellisense project {projectName} domain", null, setupInfomation);

                    object[] arguments =
                    {
                        assemblies,
                        typeof(ConnectQlContext).Assembly.Location
                    };

                    this.watchPaths = assemblies
                                      .Concat(new[]
                    {
                        configFile
                    }).ToArray();

                    this.WatchPaths(this.watchPaths);

                    this.handler = new RemoteEventHandler <byte[]>(this.IntellisenseSessionOnDocumentUpdated);

                    this.intellisenseSession = (AppDomainIntellisenseSession)this.appDomain.CreateInstanceFromAndUnwrap(
                        typeof(AppDomainIntellisenseSession).Assembly.Location,
                        typeof(AppDomainIntellisenseSession).FullName ?? string.Empty,
                        false,
                        BindingFlags.CreateInstance,
                        null,
                        arguments,
                        CultureInfo.CurrentCulture,
                        null);

                    this.intellisenseSession.DocumentUpdated += this.handler.Handler;

                    this.Initialized?.Invoke(this, EventArgs.Empty);
                }
                catch (Exception)
                {
                    this.Dispose();

                    Task.Run(async() =>
                    {
                        await Task.Delay(TimeSpan.FromSeconds(1));

                        this.Init(projectId);
                    });
                }
                finally
                {
                    AppDomain.CurrentDomain.AssemblyResolve -= IntellisenseProxy.AppDomainFix;
                }
            });
        }
コード例 #37
0
        public async Task Reader(NetworkStream stream, CancellationToken token)
        {
            Debug.WriteLine("Запуск PLC Reader");
            while (!token.IsCancellationRequested)
            {
                byte[]  messageBytes;
                Message header;
                try {
                    var headerBytes = await ReadFromStreamAsync(PlcClass <Message> ._Size, stream, token);

                    header = PlcClass <Message> .GetMessage(headerBytes);

                    switch (header.Type)
                    {
                    case Messages.CURRENT_DATA: {
                        var bodyBytes = await ReadFromStreamAsync(PlcClass <MessageCyclic> ._Size - PlcClass <Message> ._Size, stream, token);

                        messageBytes = Combine(headerBytes, bodyBytes);
                    }
                    break;

                    case Messages.ERRORS_WARNINGS: {
                        var bodyBytes = await ReadFromStreamAsync(PlcClass <MessageErrors> ._Size - PlcClass <Message> ._Size, stream, token);

                        messageBytes = Combine(headerBytes, bodyBytes);
                    }
                    break;

                    case Messages.SERVICE:
                    {
                        var bodyBytes = await ReadFromStreamAsync(154 - PlcClass <Message> ._Size, stream, token);
                    }
                        continue;

                    case Messages.AXIS_SERVICE:
                    {
                        var bodyBytes = await ReadFromStreamAsync(271 - PlcClass <Message> ._Size, stream, token);
                    }
                        continue;

                    default: continue;
                    }
                }

                catch (OperationCanceledException) {
                    return;
                }
                catch (Exception e) {
                    Debug.WriteLine(
                        $"Reader() Exception{Environment.NewLine}{e.Message}{Environment.NewLine}{e.StackTrace}");
                    Task.Run(Connect);
                    return;
                }

                try
                {
                    switch (header.Type)
                    {
                    case Messages.CURRENT_DATA:
                    {
                        var message = PlcClass <MessageCyclic> .GetMessage(messageBytes);

                        Zones[message.Zone].Update(message);
                    }
                    break;

                    case Messages.ERRORS_WARNINGS:
                    {
                        var message = PlcClass <MessageErrors> .GetMessage(messageBytes);

                        Zones[message.Zone].Update(message);
                    }
                    break;
                    }
                }
                catch (Exception e) {
                    Debug.WriteLine(
                        $"Reader() Exception{Environment.NewLine}{e.Message}{Environment.NewLine}{e.StackTrace}");
                }
            }
        }
コード例 #38
0
 /// <summary>Waits the given time span. Overriding this method is recommended for mocking purposes.</summary>
 /// <param name="ts">TimeSpan to wait (and block the current thread).</param>
 /// <param name="cancellationToken">The cancellation token in case the user wants to cancel the operation in
 /// the middle.</param>
 protected virtual async Task Wait(TimeSpan ts, CancellationToken cancellationToken)
 {
     await TaskEx.Delay(ts, cancellationToken).ConfigureAwait(false);
 }
コード例 #39
0
        public static async Task <string> CreateCsvFromLists
            (IEnumerable <Dictionary <string, string> > dictList,
            List <string> keyList)
        {
            _ = await Task.FromResult(true);

            var sb = new StringBuilder();

            /*
             * currently unused
             * will take a selection of properties
             * and return only the values for those properties
             * will require a bit of different handling
             *
             *
             * var selection = new List<string> {"resource.id", "resource.name[0].family", "resource.name[0].given[0]", "resource.gender", "resource.birthDate"};
             *
             * // this selects the items from the above list.
             *
             * var firstLine = keyList.Where(item => selection.Contains
             *  (item));
             *
             * var newLine = string.Join(";", firstLine);
             *
             */

            sb.Append(string.Join(";", keyList));
            sb.Append("\n");

            var count = 0;

            foreach (var dict in dictList)
            {
                foreach (var key in keyList)
                {
                    foreach (var kvp in dict)
                    {
                        if (!dict.ContainsKey(key))
                        {
                            if (keyList.IndexOf(key) <
                                keyList.Count - 1)
                            {
                                sb.Append(";");
                            }
                            break;
                        }

                        if (!key.Equals(kvp.Key))
                        {
                            continue;
                        }
                        if (string.IsNullOrEmpty(kvp.Value))
                        {
                            sb.Append(";");
                        }
                        else if (keyList.IndexOf(key) ==
                                 keyList.Count - 1)
                        {
                            sb.Append("\"" + kvp
                                      .Value + "\"");
                        }
                        else
                        {
                            sb.Append("\"" + kvp.Value + "\"" + ";");
                        }
                    }
                }
                count++;

                if (count < dictList.Count())
                {
                    sb.Append("\n");
                }
            }

            return(sb.ToString());
        }
コード例 #40
0
 public override Task <ICollection <FilterValue> > GroupValuesAsync(ICollection <Guid> necessaryMIATypeIds, IFilter selectAttributeFilter, IFilter filter)
 {
     return(Task.FromResult((ICollection <FilterValue>)null));
 }
コード例 #41
0
        private void LogError(Task task, INuGetUI uiService)
        {
            var exception = ExceptionUtilities.Unwrap(task.Exception);

            uiService.ProjectContext.Log(MessageLevel.Error, exception.Message);
        }
コード例 #42
0
        private async Task <bool> CheckPackageManagementFormat(INuGetUI uiService, CancellationToken token)
        {
#if VS14
            // don't show this dialog for VS 2015
            return(await Task.FromResult(true));
#else
            var potentialProjects = new List <NuGetProject>();

            // check if project suppports <PackageReference> items.
            // otherwise don't show format selector dialog for this project
            var capableProjects = uiService
                                  .Projects
                                  .Where(project =>
                                         project.ProjectStyle == ProjectModel.ProjectStyle.PackagesConfig &&
                                         project.ProjectServices.Capabilities.SupportsPackageReferences);

            // get all packages.config based projects with no installed packages
            foreach (var project in capableProjects)
            {
                var installedPackages = await project.GetInstalledPackagesAsync(token);

                if (!installedPackages.Any())
                {
                    potentialProjects.Add(project);
                }
            }

            // only show this dialog if there are any new project(s) with no installed packages.
            if (potentialProjects.Count > 0)
            {
                var packageManagementFormat = new PackageManagementFormat(uiService.Settings);
                if (!packageManagementFormat.Enabled)
                {
                    // user disabled this prompt either through Tools->options or previous interaction of this dialog.
                    // now check for default package format, if its set to PackageReference then update the project.
                    if (packageManagementFormat.SelectedPackageManagementFormat == 1)
                    {
                        await uiService.UpdateNuGetProjectToPackageRef(potentialProjects);
                    }

                    return(true);
                }

                packageManagementFormat.ProjectNames = potentialProjects
                                                       .Select(project => project.GetMetadata <string>(NuGetProjectMetadataKeys.Name))
                                                       .OrderBy(name => name, StringComparer.OrdinalIgnoreCase).ToList();

                // show dialog for package format selector
                var result = uiService.PromptForPackageManagementFormat(packageManagementFormat);

                // update nuget projects if user selected PackageReference option
                if (result && packageManagementFormat.SelectedPackageManagementFormat == 1)
                {
                    await uiService.UpdateNuGetProjectToPackageRef(potentialProjects);
                }
                return(result);
            }

            return(true);
#endif
        }
コード例 #43
0
 /// <summary>
 /// Sets whether two factor authentication is enabled for the user
 /// </summary>
 /// <param name="user"/><param name="enabled"/>
 /// <returns/>
 public virtual Task SetTwoFactorEnabledAsync(BackOfficeIdentityUser user, bool enabled)
 {
     user.TwoFactorEnabled = false;
     return(Task.FromResult(0));
 }
コード例 #44
0
        /// <summary>
        /// Generates the original references directory tree.
        /// </summary>
        protected override void Initialize()
        {
#pragma warning disable RS0030 // symbol LoadedProject is banned
            using (UnconfiguredProjectAsynchronousTasksService.LoadedProject())
#pragma warning restore RS0030 // symbol LoadedProject is banned
            {
                base.Initialize();

                // this.IsApplicable may take a project lock, so we can't do it inline with this method
                // which is holding a private lock.  It turns out that doing it asynchronously isn't a problem anyway,
                // so long as we guard against races with the Dispose method.
#pragma warning disable RS0030 // symbol LoadedProjectAsync is banned
                UnconfiguredProjectAsynchronousTasksService.LoadedProjectAsync(
#pragma warning restore RS0030 // symbol LoadedProjectAsync is banned
                    async delegate
                {
                    await TaskScheduler.Default.SwitchTo(alwaysYield: true);
                    UnconfiguredProjectAsynchronousTasksService
                    .UnloadCancellationToken.ThrowIfCancellationRequested();

                    lock (SyncObject)
                    {
                        Verify.NotDisposed(this);

                        // Issue this token before hooking the SnapshotChanged event to prevent a race
                        // where a snapshot tree is replaced by the initial, empty tree created below.
                        // The handler will cancel this token before submitting its update.
                        CancellationToken initialTreeCancellationToken = _treeUpdateCancellationSeries.CreateNext();

                        _ = SubmitTreeUpdateAsync(
                            delegate
                        {
                            IProjectTree dependenciesNode = CreateDependenciesNode();

                            return(Task.FromResult(new TreeUpdateResult(dependenciesNode)));
                        },
                            initialTreeCancellationToken);

                        ITargetBlock <SnapshotChangedEventArgs> actionBlock = DataflowBlockSlim.CreateActionBlock <SnapshotChangedEventArgs>(
                            OnDependenciesSnapshotChangedAsync,
                            "DependenciesProjectTreeProviderSource {1}",
                            skipIntermediateInputData: true);
                        _snapshotEventListener = _dependenciesSnapshotProvider.SnapshotChangedSource.LinkTo(actionBlock, DataflowOption.PropagateCompletion);
                    }
                },
                    registerFaultHandler: true);
            }

            IProjectTree CreateDependenciesNode()
            {
                var values = new ReferencesProjectTreeCustomizablePropertyValues
                {
                    Caption      = Resources.DependenciesNodeName,
                    Icon         = ManagedImageMonikers.ReferenceGroup.ToProjectSystemType(),
                    ExpandedIcon = ManagedImageMonikers.ReferenceGroup.ToProjectSystemType(),
                    Flags        = DependencyTreeFlags.DependenciesRootNodeFlags
                };

                // Allow property providers to perform customization.
                // These are ordered from lowest priority to highest, allowing higher priority
                // providers to override lower priority providers.
                foreach (IProjectTreePropertiesProvider provider in _projectTreePropertiesProviders.ExtensionValues())
                {
                    provider.CalculatePropertyValues(ProjectTreeCustomizablePropertyContext.Instance, values);
                }

                // Note that all the parameters are specified so we can force this call to an
                // overload of NewTree available prior to 15.5 versions of CPS. Once a 15.5 build
                // is publicly available we can move this to an overload with default values for
                // most of the parameters, and we'll only need to pass the interesting ones.
                return(NewTree(
                           caption: values.Caption,
                           filePath: null,
                           browseObjectProperties: null,
                           icon: values.Icon,
                           expandedIcon: values.ExpandedIcon,
                           visible: true,
                           flags: values.Flags));
            }
        }
コード例 #45
0
        public static async void Update(ProjectFile file, Project project, bool force)
        {
            SingleProjectFileCustomTool tool;
            ProjectFile genFile;

            if (!ShouldRunGenerator(file, project, force, out tool, out genFile))
            {
                return;
            }

            TaskService.Errors.ClearByOwner(file);

            TaskInfo runningTask;
            TaskCompletionSource <bool> newTask = new TaskCompletionSource <bool> ();
            var  result                = new SingleFileCustomToolResult();
            Task existingTask          = null;
            CancellationTokenSource cs = new CancellationTokenSource();

            // if this file is already being run, cancel it

            lock (runningTasks) {
                if (runningTasks.TryGetValue(file.FilePath, out runningTask))
                {
                    runningTask.CancellationTokenSource.Cancel();
                    runningTasks.Remove(file.FilePath);
                    existingTask = runningTask.Task;
                }
                runningTask = new TaskInfo {
                    Task = newTask.Task, CancellationTokenSource = cs, Result = result
                };
                runningTasks.Add(file.FilePath, runningTask);
            }

            // If a task was already running, wait for it to finish. Running the same task in parallel may lead
            // to file sharing violation errors

            if (existingTask != null)
            {
                try {
                    await existingTask;
                } catch {
                    // Ignore exceptions, they are handled elsewhere
                }
            }

            // Maybe I was cancelled while I was waiting. In that case, the task has already been removed from
            // the runningTasks collection

            if (cs.IsCancellationRequested)
            {
                newTask.TrySetResult(true);
                return;
            }

            // Execute the generator

            Exception error   = null;
            var       monitor = IdeApp.Workbench.ProgressMonitors.GetToolOutputProgressMonitor(false).WithCancellationSource(cs);

            try {
                monitor.BeginTask(GettextCatalog.GetString("Running generator '{0}' on file '{1}'...", file.Generator, file.Name), 1);

                try {
                    await tool.Generate(monitor, project, file, result);
                } catch (Exception ex) {
                    error = ex;
                    result.UnhandledException = ex;
                }

                // Generation has finished. Remove the task from the runningTasks collection

                lock (runningTasks) {
                    TaskInfo registeredTask;
                    if (runningTasks.TryGetValue(file.FilePath, out registeredTask) && registeredTask == runningTask)
                    {
                        runningTasks.Remove(file.FilePath);
                        UpdateCompleted(monitor, file, genFile, result, false);
                    }
                    else
                    {
                        // it was cancelled because another was run for the same file, so just clean up
                        monitor.EndTask();
                        monitor.ReportWarning(GettextCatalog.GetString("Cancelled because generator ran again for the same file"));
                        monitor.Dispose();
                    }
                }
            } catch (Exception ex) {
                result.UnhandledException = ex;
                UpdateCompleted(monitor, file, genFile, result, false);
            } finally {
                if (error == null)
                {
                    newTask.SetResult(true);
                }
                else
                {
                    newTask.SetException(error);
                }
            }
        }
コード例 #46
0
 /// <summary>
 /// Returns whether two factor authentication is enabled for the user
 /// </summary>
 /// <param name="user"/>
 /// <returns/>
 public virtual Task <bool> GetTwoFactorEnabledAsync(BackOfficeIdentityUser user)
 {
     return(Task.FromResult(false));
 }
コード例 #47
0
 public Task <bool> ExecuteFileAsync(string filename, string extraArgs)
 {
     return((_evaluator as IPythonInteractiveEvaluator)?.ExecuteFileAsync(filename, extraArgs)
            ?? Task.FromResult(false));
 }
コード例 #48
0
 /// <summary>
 /// Sets whether the user email is confirmed
 /// </summary>
 /// <param name="user"/><param name="confirmed"/>
 /// <returns/>
 public Task SetEmailConfirmedAsync(BackOfficeIdentityUser user, bool confirmed)
 {
     ThrowIfDisposed();
     user.EmailConfirmed = confirmed;
     return(Task.FromResult(0));
 }
コード例 #49
0
 public async Task <int?> GetProvisionedDataStoreCapacityAsync(CancellationToken cancellationToken = default)
 {
     return(await Task.FromResult((int?)null));
 }
コード例 #50
0
ファイル: TaskAwaiter.cs プロジェクト: salmanmkc/coyote
 internal TaskAwaiter(TaskController taskController, SystemTasks.Task awaitedTask)
 {
     this.TaskController = taskController;
     this.AwaitedTask    = awaitedTask;
     this.Awaiter        = awaitedTask.GetAwaiter();
 }
コード例 #51
0
        public void Update(MessageCyclic message)
        {
            lock (_locker)
            {
                switch (message.Type)
                {
                case Messages.CURRENT_DATA:
                {
                    if (Message.Progress != message.Progress)
                    {
                        Task.Run(() => { Core.Notify($"{{\"id\":\"devices\",\"update\":[\"{id}\",\"progress\"]}}"); });
                    }
                    if (Message.Mode != message.Mode)
                    {
                        Task.Run(() => { Core.Notify($"{{\"id\":\"devices\",\"update\":[\"{id}\",\"mode\"]}}"); });
                    }

                    if (Message.Status != message.Status || Message.Id != message.Id || Message.RequestType != message.RequestType)
                    {
                        if (Message.RequestType != message.RequestType)
                        {
                            switch (message.RequestType)
                            {
                            case RequestTypes.WRITING_WEIGHT_TO_DB:
                                _answersQueue.Add(new RequestWeight(message.Status, message.Id, message.RequestType, message.Weight));
                                break;

                            case RequestTypes.WRITING_TO_DB_OPERATION:
                                _answersQueue.Add(new RequestOperation(message.Status, message.Id, message.RequestType, message.OperationId));
                                break;

                            case RequestTypes.READY_ACCEPT_OPERATION:
                                _answersQueue.Add(new RequestStatus(message.Status, message.Id, message.RequestType));
                                break;

                            case RequestTypes.BLOCK_ADDRESS:
                                _answersQueue.Add(new RequestLock(message.Status, message.Id, message.RequestType, message.OperationId, message.Address));
                                break;

                            case RequestTypes.UNBLOCK_ADDRESS:
                                _answersQueue.Add(new RequestUnlock(message.Status, message.Id, message.RequestType, message.OperationId, message.Address));
                                break;

                            default:
                                _answersQueue.Add(new RequestStatus(message.Status, message.Id, message.RequestType));
                                break;
                            }
                        }
                        else
                        {
                            _answersQueue.Add(new RequestStatus(message.Status, message.Id, message.RequestType));
                        }
                    }

                    Message = message;
                }
                break;

                default:
                    break;
                }
            }
        }
コード例 #52
0
 public async Task <ICollection <Customer> > Get()
 {
     return(await Task.Run(() => _baseContext.Customers.ToListAsync()).ConfigureAwait(false));
 }
コード例 #53
0
 public override Task <HttpWebResponseWrapper> SendAsync()
 {
     return(TaskEx.Run(this.OnSend));
 }
コード例 #54
0
 public Task SaveAsync(Stream stream)
 {
     return(TaskEx.Run(() => this.OnSave(stream)));
 }
コード例 #55
0
ファイル: WordEditor.cs プロジェクト: PayaSoft/PendarEditor
        public async Task PrintAsync(bool withPreview, CancellationTokenSource cancellationTokenSource = null)
        {
            string fileName = Path.GetFileName(this._FileName);

            if (_Logger.IsTraceEnabled)
            {
                _Logger.Trace("Launching {0}", fileName);
            }

            this._CurrentApp      = null;
            this._CurrentDocument = null;

            using (var app = new Application {
                Visible = true, DisplayAlerts = WdAlertLevel.wdAlertsNone, DisplayRecentFiles = false, Caption = Resources.PendarEditorTitle
            })
            {
                try
                {
                    app.Console.Mode = DebugConsoleMode.Trace;
                    app.Console.AppendTimeInfoEnabled = true;

                    app.DisplayAlerts = WdAlertLevel.wdAlertsNone;

                    app.DocumentBeforeCloseEvent += this.App_DocumentBeforeCloseEvent;
                    app.DocumentBeforeSaveEvent  += this.App_DocumentBeforeSaveEvent;
                    app.DocumentBeforePrintEvent += this.App_DocumentBeforePrintEvent;
                    app.DocumentChangeEvent      += this.App_DocumentChangeEvent;
                    app.DocumentOpenEvent        += this.App_DocumentOpenEvent;
                    app.NewDocumentEvent         += this.App_NewDocumentEvent;
                    app.QuitEvent    += this.App_QuitEvent;
                    app.StartupEvent += this.App_StartupEvent;

                    app.Options.AllowReadingMode = true;

                    this._CurrentApp        = app;
                    this._isQuit            = false;
                    this._isFinished        = false;
                    this.IsSaved            = false;
                    this.IsWaitingForFinish = false;

                    try
                    {
                        app.Options.ArabicNumeral         = WdArabicNumeral.wdNumeralContext;
                        app.Options.BackgroundSave        = false;
                        app.Options.CreateBackup          = false;
                        app.Options.DocumentViewDirection = WdDocumentViewDirection.wdDocumentViewRtl;
                        app.Options.MeasurementUnit       = WdMeasurementUnits.wdMillimeters;
                        app.Options.MonthNames            = WdMonthNames.wdMonthNamesFrench;
                        app.Options.DefaultTextEncoding   = NetOffice.OfficeApi.Enums.MsoEncoding.msoEncodingUTF8;
                        app.Options.ShowDevTools          = false;
                    }
                    catch (COMException exp)
                    {
                        if (_Logger.IsWarnEnabled)
                        {
                            _Logger.Warn(exp, "Error while setting the Word options");
                        }
                    }

                    using (var doc = app.Documents.Open(this._FileName, true, false, false))
                    {
                        doc.Settings.EnableAutomaticQuit      = true;
                        doc.Settings.EnableMoreDebugOutput    = Internal.IsDebug;
                        doc.Settings.EnableEventDebugOutput   = Internal.IsDebug;
                        doc.Settings.EnableEvents             = true;
                        doc.Settings.ExceptionMessageBehavior = ExceptionMessageHandling.CopyInnerExceptionMessageToTopLevelException;
                        doc.Settings.EnableSafeMode           = Internal.IsDebug;

                        try
                        {
                            doc.Protect(WdProtectionType.wdAllowOnlyFormFields, true, password: Guid.NewGuid().ToString("N"));
                        }
                        catch (COMException exp)
                        {
                            if (_Logger.IsWarnEnabled)
                            {
                                _Logger.Warn(exp, "Error while protecting the document");
                            }
                        }

                        try
                        {
                            doc.ReadOnlyRecommended = true;
                        }
                        catch (COMException exp)
                        {
                            if (_Logger.IsWarnEnabled)
                            {
                                _Logger.Warn(exp, "Error in the ReadOnlyRecommended");
                            }
                        }

                        try
                        {
                            doc.Saved = true;
                        }
                        catch (COMException exp)
                        {
                            if (_Logger.IsWarnEnabled)
                            {
                                _Logger.Warn(exp, "Error while setting document as saved");
                            }
                        }

                        try
                        {
                            if (withPreview)
                            {
                                doc.PrintPreview();

                                app.Activate();

                                await this.WaitForExitAsync(cancellationTokenSource : cancellationTokenSource);
                            }
                            else
                            {
                                doc.PrintOut();
                            }

                            await TaskEx.Delay(90);
                        }
                        finally
                        {
                            try
                            {
                                doc.ClosePrintPreview();
                            }
                            catch (Exception exp)
                            {
                                if (_Logger.IsWarnEnabled)
                                {
                                    _Logger.Warn(exp, "Error while closing the print preview");
                                }
                            }

                            try
                            {
                                doc.Close(false);
                            }
                            catch (Exception exp)
                            {
                                if (_Logger.IsWarnEnabled)
                                {
                                    _Logger.Warn(exp, "Error while closing the word document");
                                }
                            }
                        }
                    }
                }
                finally
                {
                    try
                    {
                        if (_Logger.IsDebugEnabled)
                        {
                            _Logger.Debug("Quiting the word application");
                        }

                        if (!this._isQuit)
                        {
                            app.Quit(false, true);
                        }

                        if (_Logger.IsDebugEnabled)
                        {
                            _Logger.Debug("Quited the word application");
                        }
                    }
                    catch (COMException exp)
                    {
                        if (_Logger.IsWarnEnabled)
                        {
                            _Logger.Warn(exp, "Error while quiting the word Application");
                        }
                    }
                }
            }
        }
コード例 #56
0
        public async Task GivenReindexJobRunning_WhenReindexJobCancelRequest_ThenReindexJobStopsAndMarkedCanceled()
        {
            var             randomName      = Guid.NewGuid().ToString().ComputeHash().Substring(0, 14).ToLower();
            string          searchParamName = randomName;
            string          searchParamCode = randomName + "Code";
            SearchParameter searchParam     = await CreateSearchParam(searchParamName, SearchParamType.String, ResourceType.Patient, "Patient.name", searchParamCode);

            const string sampleName1 = "searchIndicesPatient1";
            const string sampleName2 = "searchIndicesPatient2";
            const string sampleName3 = "searchIndicesPatient3";
            const string sampleName4 = "searchIndicesPatient4";

            string sampleId1 = Guid.NewGuid().ToString();
            string sampleId2 = Guid.NewGuid().ToString();
            string sampleId3 = Guid.NewGuid().ToString();
            string sampleId4 = Guid.NewGuid().ToString();

            // Set up the values that the search index extraction should return during reindexing
            var searchValues = new List <(string, ISearchValue)>
            {
                (sampleId1, new StringSearchValue(sampleName1)),
                (sampleId2, new StringSearchValue(sampleName2)),
                (sampleId3, new StringSearchValue(sampleName3)),
                (sampleId4, new StringSearchValue(sampleName4)),
            };

            MockSearchIndexExtraction(searchValues, searchParam);

            UpsertOutcome sample1 = await CreatePatientResource(sampleName1, sampleId1);

            UpsertOutcome sample2 = await CreatePatientResource(sampleName2, sampleId2);

            UpsertOutcome sample3 = await CreatePatientResource(sampleName3, sampleId3);

            UpsertOutcome sample4 = await CreatePatientResource(sampleName4, sampleId4);

            // Create the query <fhirserver>/Patient?foo=searchIndicesPatient1
            var queryParams = new List <Tuple <string, string> > {
                new(searchParamCode, sampleName1)
            };
            SearchResult searchResults = await _searchService.Value.SearchAsync("Patient", queryParams, CancellationToken.None);

            // Confirm that the search parameter "foo" is marked as unsupported
            Assert.Equal(searchParamCode, searchResults.UnsupportedSearchParameters.FirstOrDefault()?.Item1);

            // When search parameters aren't recognized, they are ignored
            // Confirm that "foo" is dropped from the query string and all patients are returned
            Assert.Equal(4, searchResults.Results.Count());

            var createReindexRequest       = new CreateReindexRequest(new List <string>(), 1, 1, 500);
            CreateReindexResponse response = await SetUpForReindexing(createReindexRequest);

            var cancellationTokenSource = new CancellationTokenSource();

            try
            {
                var  cancelReindexHandler = new CancelReindexRequestHandler(_fhirOperationDataStore, DisabledFhirAuthorizationService.Instance);
                Task reindexWorkerTask    = _reindexJobWorker.ExecuteAsync(cancellationTokenSource.Token);
                await cancelReindexHandler.Handle(new CancelReindexRequest(response.Job.JobRecord.Id), CancellationToken.None);

                var reindexWrapper = await _fhirOperationDataStore.GetReindexJobByIdAsync(response.Job.JobRecord.Id, cancellationTokenSource.Token);

                Assert.Equal(OperationStatus.Canceled, reindexWrapper.JobRecord.Status);
            }
            catch (RequestNotValidException ex)
            {
                // Despite the settings above of the create reindex request which processes only one resource
                // every 500ms, sometimes when the test runs the reindex job is completed before the
                // the cancellation request is processed.  We will ignore this error
                if (!ex.Message.Contains("in state Completed and cannot be cancelled", StringComparison.OrdinalIgnoreCase))
                {
                    throw;
                }
            }
            finally
            {
                cancellationTokenSource.Cancel();

                _searchParameterDefinitionManager.DeleteSearchParameter(searchParam.ToTypedElement());
                await _testHelper.DeleteSearchParameterStatusAsync(searchParam.Url, CancellationToken.None);

                await _fixture.DataStore.HardDeleteAsync(sample1.Wrapper.ToResourceKey(), false, CancellationToken.None);

                await _fixture.DataStore.HardDeleteAsync(sample2.Wrapper.ToResourceKey(), false, CancellationToken.None);

                await _fixture.DataStore.HardDeleteAsync(sample3.Wrapper.ToResourceKey(), false, CancellationToken.None);

                await _fixture.DataStore.HardDeleteAsync(sample4.Wrapper.ToResourceKey(), false, CancellationToken.None);
            }
        }
コード例 #57
0
 /// <summary>同步获取字符串</summary>
 /// <param name="client">Http客户端</param>
 /// <param name="requestUri">请求资源地址</param>
 /// <param name="headers">附加头部</param>
 /// <returns></returns>
 public static String GetString(this HttpClient client, String requestUri, IDictionary <String, String> headers = null)
 {
     client.AddHeaders(headers);
     return(TaskEx.Run(() => client.GetStringAsync(requestUri)).Result);
 }
コード例 #58
0
 /// <summary>同步提交表单</summary>
 /// <param name="client">Http客户端</param>
 /// <param name="requestUri">请求资源地址</param>
 /// <param name="data">数据</param>
 /// <param name="headers">附加头部</param>
 /// <returns></returns>
 public static String PostForm(this HttpClient client, String requestUri, Object data, IDictionary <String, String> headers = null) => TaskEx.Run(() => client.PostFormAsync(requestUri, data, headers)).Result;
コード例 #59
0
 public VsPathContextProvider(
     IAsyncServiceProvider asyncServiceProvider,
     Lazy <ISettings> settings,
     Lazy <IVsSolutionManager> solutionManager,
     Lazy <ILogger> logger,
     Lazy <IMachineWideSettings> machineWideSettings)
 {
     _asyncServiceprovider = asyncServiceProvider ?? throw new ArgumentNullException(nameof(asyncServiceProvider));
     _settings             = settings ?? throw new ArgumentNullException(nameof(settings));
     _solutionManager      = solutionManager ?? throw new ArgumentNullException(nameof(solutionManager));
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
     _getLockFileOrNullAsync = BuildIntegratedProjectUtility.GetLockFileOrNull;
     if (machineWideSettings == null)
     {
         throw new ArgumentNullException(nameof(machineWideSettings));
     }
     _projectContext = new Lazy <INuGetProjectContext>(() => new VSAPIProjectContext
     {
         PackageExtractionContext = new PackageExtractionContext(
             PackageSaveMode.Defaultv2,
             PackageExtractionBehavior.XmlDocFileSaveMode,
             ClientPolicyContext.GetClientPolicy(_settings.Value, NullLogger.Instance),
             NullLogger.Instance)
     });
     _userWideSettings = new Microsoft.VisualStudio.Threading.AsyncLazy <ISettings>(() => Task.FromResult(Settings.LoadDefaultSettings(null, null, machineWideSettings.Value)), NuGetUIThreadHelper.JoinableTaskFactory);
 }
コード例 #60
0
        private async void PollMailboxTick(object state)
        {
            StopTimer();
            if (false == monitorMailbox)
            {
                return;
            }

            if ((DateTime.Now - mailboxConnectionTimeStamp).Hours >= 3 ||
                consecutiveFailureCount != 0)
            {
                try
                {
                    RefreshMailBoxConnection();
                }
                catch (Exception ex)
                {
                    consecutiveFailureCount += 1;
                    logger.ErrorFormat(
                        ex,
                        "An Exception was encountered while refreshing the mailbox connection. Consecutive Failure Count = [{0}]...",
                        consecutiveFailureCount);
                    if (consecutiveFailureCount > 10)
                    {
                        logger.ErrorFormat(ex, "Consecutive Failure Count exceeded 10, re-throwing exception...");
                        throw;
                    }

                    if (monitorMailbox)
                    {
                        StartTimer(pollTimeInMilliseconds);
                    }

                    return;
                }
            }

            logger.Debug("Processing Mailbox tick...");

            // Process emails until the mailbox is empty...
            EmailMessage[] emails          = null;
            var            getEmailSuccess = GetEmails(out emails);

            while (getEmailSuccess && emails.Any())
            {
                var tasks = new Task[emails.Count()];
                for (var index = 0; index < emails.Count(); index++)
                {
                    var emailItem = emails[index];
                    tasks[index] = ProcessEmail(emailItem);
                }

                await Task.WhenAll(tasks);

                getEmailSuccess = GetEmails(out emails);
            }

            logger.Debug("Mailbox tick processing complete.");
            if (monitorMailbox)
            {
                StartTimer(pollTimeInMilliseconds);
            }
        }