private async Task PendOrSubmitRequests(ProjectAnalyzer analyzer, string path)
            {
                List <string> pendingRequests;
                int           originalCount;

                lock (_containersLock) {
                    pendingRequests = _pendingRequests;
                    _pendingRequests.Add(path);
                    originalCount = _pendingRequests.Count;

                    if (originalCount > 50)
                    {
                        _pendingRequests = new List <string>();
                    }
                }

                await Task.Delay(100).ConfigureAwait(false);

                lock (_containersLock) {
                    if (pendingRequests.Count != originalCount)
                    {
                        return;
                    }
                    if (_pendingRequests == pendingRequests)
                    {
                        _pendingRequests = new List <string>();
                    }
                }

                await UpdateTestCasesAsync(analyzer, pendingRequests, true).ConfigureAwait(false);
            }
Beispiel #2
0
        public async Task CanDeleteTag()
        {
            // Arrange
            var    client   = CreateClient();
            string tag      = "test-delete-tag";
            var    artifact = client.GetArtifact(_repositoryName, tag);

            if (Mode != RecordedTestMode.Playback)
            {
                await ImportImage(TestEnvironment.Registry, _repositoryName, tag);
            }

            // Act
            await artifact.DeleteTagAsync(tag);

            // Assert

            // This will be removed, pending investigation into potential race condition.
            // https://github.com/azure/azure-sdk-for-net/issues/19699
            if (Mode != RecordedTestMode.Playback)
            {
                await Task.Delay(5000);
            }

            Assert.ThrowsAsync <RequestFailedException>(async() => { await artifact.GetTagPropertiesAsync(tag); });
        }
Beispiel #3
0
        private void FormatSelection(ITextView textView, ITextBuffer buffer)
        {
            if (!Options.Instance.FormatOnMoveLine)
            {
                return;
            }

            MoveCaretIfNeeded(textView);

            if (!_formatQueued)
            {
                _formatQueued = true;

                ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
                {
                    await Task.Delay(1);

                    IEditorCommandHandlerService service = _commandService.GetService(textView);
                    var cmd = new FormatSelectionCommandArgs(textView, buffer);
                    service.Execute((v, b) => cmd, null);

                    _formatQueued = false;
                }).FileAndForget(nameof(FormatOnMoveLine));
            }
        }
        /// <summary>
        /// This method implements a workaround for a bug in VS 2015 in which the properties window
        /// will not update the very first time is opened until it gains and loses focus. This method
        /// forces the focus to change to the properties window and then back to the owner frame to force
        /// this behavior.
        /// </summary>
        private async Task TicklePropertiesWindowAsync()
        {
            await GoogleCloudExtensionPackage.Instance.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (_propertiesWindowTickled)
            {
                return;
            }

            // Tickle the properties window, change the focus to force the
            // properties window to update. This apparently only needs to be done once.
            await Task.Delay(1);

            var frame = GetPropertiesWindow(_owner);

            if (frame == null || frame.IsVisible() != Microsoft.VisualStudio.VSConstants.S_OK)
            {
                // If there's no properties frame, or it is not visible, then there's nothing todo.
                return;
            }

            frame?.Show();
            await Task.Delay(1);

            OwnerFrame?.Show();
            _propertiesWindowTickled = true;
        }
Beispiel #5
0
        public async Task CanDeleteRegistryArtifact()
        {
            // Arrange
            string repository = $"library/node";
            string tag        = "test-delete-image";
            ContainerRepositoryClient client = CreateClient(repository);

            if (Mode != RecordedTestMode.Playback)
            {
                await ImportImage(repository, tag);
            }

            TagProperties tagProperties = await client.GetTagPropertiesAsync(tag);

            string digest = tagProperties.Digest;

            // Act
            await client.DeleteRegistryArtifactAsync(digest);

            // Assert

            // This will be removed, pending investigation into potential race condition.
            // https://github.com/azure/azure-sdk-for-net/issues/19699
            if (Mode != RecordedTestMode.Playback)
            {
                await Task.Delay(5000);
            }

            Assert.ThrowsAsync <RequestFailedException>(async() => { await client.GetRegistryArtifactPropertiesAsync(tag); });
        }
Beispiel #6
0
        private void CommandEvents_BeforeExecute(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            //Microsoft.SqlServer.Management.SqlStudio.
            //var objectExplorerService = (ObjectExplorerService)_package.GetServiceAsync(typeof(IObjectExplorerService)).Result;

            //// var oesTreeProperty = objectExplorerService.GetType().GetProperty("Tree", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase);
            ////// if (oesTreeProperty != null)

            ////     var x = (TreeView)oesTreeProperty.GetValue(objectExplorerService, null);

            //int arraySize;
            //INodeInformation[] array;
            //objectExplorerService.GetSelectedNodes(out arraySize, out array);


            //if (arraySize == 0)
            //    return;

            //var node = array[0];

            //var table = (HierarchyObject)node.GetService(typeof(IMenuHandler));
            //table.AddChild("abc", new tableMenuItem());

            //Microsoft.SqlServer.Management.UI.VSIntegration.ObjectExplorer.FilterOperator

            try
            {
                string queryText = GetQueryText();

                if (string.IsNullOrWhiteSpace(queryText))
                {
                    return;
                }

                // Get Current Connection Information
                UIConnectionInfo connInfo = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo.UIConnectionInfo;

                var queryItem = new QueryItem()
                {
                    Query            = queryText,
                    Server           = connInfo.ServerName,
                    Username         = connInfo.UserName,
                    Database         = connInfo.AdvancedOptions["DATABASE"],
                    ExecutionDateUtc = DateTime.UtcNow
                };

                _logger.LogInformation("Enqueued {@quetyItem}", queryItem.Query);

                itemsQueue.Enqueue(queryItem);

                Task.Delay(1000).ContinueWith((t) => this.SavePendingItems());
            }
            catch (Exception ex)
            {
                _logger.LogError("Error on BeforeExecute tracking", ex);
            }
        }
        public async Task WhenItMovesFromDisconnectedToSuspended_ShouldTryDefaultHostAgain()
        {
            Func <DateTimeOffset> nowFunc = () => DateTimeOffset.UtcNow;

            // We want access to the modified closure so we can manipulate time within ConnectionAttemptsInfo
            // ReSharper disable once AccessToModifiedClosure
            DateTimeOffset NowWrapperFn() => nowFunc();

            var client = GetConnectedClient(opts =>
            {
                opts.DisconnectedRetryTimeout = TimeSpan.FromMilliseconds(10);
                opts.SuspendedRetryTimeout    = TimeSpan.FromMilliseconds(10);
                opts.NowFunc = NowWrapperFn;
            });

            List <ConnectionState> states = new List <ConnectionState>();

            client.Connection.InternalStateChanged += (sender, args) =>
            {
                states.Add(args.Current);
            };

            List <string> retryHosts = new List <string>();

            await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
            {
                Error = new ErrorInfo()
                {
                    StatusCode = HttpStatusCode.GatewayTimeout
                }
            });

            for (int i = 0; i < 5; i++)
            {
                var now = nowFunc();
                nowFunc = () => now.AddSeconds(60);
                if (client.Connection.State == ConnectionState.Connecting)
                {
                    retryHosts.Add(LastCreatedTransport.Parameters.Host);
                }
                else
                {
                    await Task.Delay(50); //wait just enough for the disconnect timer to kick in

                    retryHosts.Add(LastCreatedTransport.Parameters.Host);
                }

                await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
                {
                    Error = new ErrorInfo()
                    {
                        StatusCode = HttpStatusCode.GatewayTimeout
                    }
                });
            }

            retryHosts.Should().Contain("realtime.ably.io");
            retryHosts.Count(x => x == "realtime.ably.io").Should().Be(1);
        }
Beispiel #8
0
        private async Task ProcessProjectRefsAsync(IVsHierarchy project = null)
        {
            await Task.Delay(TimeSpan.FromSeconds(1));

            await JoinableTaskFactory.SwitchToMainThreadAsync();

            ProcessProjectRefs(project);
        }
 /// <summary>
 /// Collects solution structure in the background
 /// </summary>
 /// <param name="token"></param>
 /// <returns></returns>
 private async Task CollectInBackgroundAsync(CancellationToken token)
 {
     while (!token.IsCancellationRequested)
     {
         CollectProjects();
         await Task.Delay(WATCH_PERIOD, token);
     }
 }
Beispiel #10
0
        async System.Threading.Tasks.Task doDownload()
        {
            await Task.Delay(1);

            return;

            //try
            //{
            //    const string url = "ftp://ftp.equation.com/make/64/make.exe";
            //    NetworkCredential credentials = new NetworkCredential("anonymous", "*****@*****.**");

            //    // Query size of the file to be downloaded
            //    WebRequest sizeRequest = WebRequest.Create(url);
            //    sizeRequest.Credentials = credentials;
            //    sizeRequest.Method = WebRequestMethods.Ftp.GetFileSize;

            //    var t = sizeRequest.GetResponseAsync();
            //    while(!t.IsCompleted)
            //    {
            //        Console.Write(".");
            //        await System.Threading.Tasks.Task.Delay(10);
            //    }


            //    int size = (int) (t.Result ).ContentLength;
            //    Console.WriteLine();
            //    Console.WriteLine(size);

            //    //progressBar1.Invoke(
            //    //    (MethodInvoker)(() => progressBar1.Maximum = size));

            //    // Download the file
            //    WebRequest request = WebRequest.Create(url);
            //    request.Credentials = credentials;
            //    request.Method = WebRequestMethods.Ftp.DownloadFile;

            //    var response  = await request.GetResponseAsync();
            //    var ftpStream = response.GetResponseStream();


            //    using (Stream fileStream = File.Create(@"C:\toolchain\test.exe"))
            //    {
            //        byte[] buffer = new byte[10240];
            //        int read;
            //        while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
            //        {
            //            fileStream.Write(buffer, 0, read);
            //            int position = (int)fileStream.Position;
            //            //progressBar1.Invoke(
            //            //    (MethodInvoker)(() => progressBar1.Value = position));
            //        }
            //    }
            //}
            //catch (Exception e)
            //{
            //   // MessageBox.Show(e.Message);
            //}
        }
Beispiel #11
0
        private void radio_checked_changed(object sender, RoutedEventArgs e)
        {
            if (!this.settingsLoaded)
            {
                return;
            }

            MonikaiSettings.Default.LeftAlign = this.radioLeft.IsChecked.GetValueOrDefault(false);

            if (this.radioManual.IsChecked.GetValueOrDefault(false))
            {
                if (this.IsPositioning)
                {
                    return;
                }

                MonikaiSettings.Default.ManualPosition  = true;
                MonikaiSettings.Default.ManualPositionX = 0;
                MonikaiSettings.Default.ManualPositionY = 0;
                this.IsPositioning = true;
                this.Dispatcher.Invoke(() => this.IsEnabled = false);

                MessageBox.Show(
                    "MonikAI will now follow your mouse cursor so you can position her wherever you want. Click the LEFT MOUSE BUTTON once you're satisfied with her position.",
                    "Manual Position");

                Task.Run(async() =>
                {
                    var mouseDown = SettingsWindow.GetAsyncKeyState(0x01) != 0;

                    do
                    {
                        var pos = Point.Empty;
                        SettingsWindow.GetCursorPos(ref pos);

                        MonikaiSettings.Default.ManualPositionX = pos.X;
                        MonikaiSettings.Default.ManualPositionY = pos.Y;

                        var prevMouseDown = mouseDown;
                        mouseDown         = SettingsWindow.GetAsyncKeyState(0x01) != 0; // 0x01 is code for LEFT_MOUSE

                        if (mouseDown && !prevMouseDown)
                        {
                            break;
                        }

                        await Task.Delay(1);
                    } while (true);

                    this.Dispatcher.Invoke(() => this.IsEnabled = true);
                    this.IsPositioning = false;
                });
            }
            else
            {
                MonikaiSettings.Default.ManualPosition = false;
            }
        }
        public async void VsTextViewCreated(VisualStudio.TextManager.Interop.IVsTextView textViewAdapter)
        {
            var textView = _editorAdaptersFactory.GetWpfTextView(textViewAdapter);

            if (textView == null)
            {
                return;
            }

            // Only track text views in Python projects (we don't get called for loose files)
            // For example, we may get called for xaml files in UWP projects, in which case we do nothing
            if (!IsInPythonProject(textView))
            {
                return;
            }

            // Load Python services now that we know we'll need them
            if (_services == null)
            {
                _services = _site.GetComponentModel().GetService <PythonEditorServices>();
                if (_services == null)
                {
                    return;
                }
            }

            var bi = _services.GetBufferInfo(textView.TextBuffer);

            if (bi == null)
            {
                return;
            }

            var entry = bi.AnalysisEntry ?? await AnalyzeXamlFileAsync(textView, bi);

            for (int retries = 3; retries > 0 && entry == null; --retries)
            {
                // Likely in the process of changing analyzer, so we'll delay slightly and retry.
                await Task.Delay(100);

                entry = bi.AnalysisEntry ?? await AnalyzeXamlFileAsync(textView, bi);
            }

            if (entry == null)
            {
                Debug.Fail($"Failed to analyze XAML file {bi.Filename}");
                return;
            }

            if (bi.TrySetAnalysisEntry(entry, null) != entry)
            {
                // Failed to start analyzing
                Debug.Fail("Failed to analyze xaml file");
                return;
            }
            await entry.EnsureCodeSyncedAsync(bi.Buffer);
        }
        private async Task WaitForKeyChange()
        {
            var state = SettingsWindow.GetKeyboardState().ToList();

            while (state.SequenceEqual(SettingsWindow.GetKeyboardState()))
            {
                await Task.Delay(10);
            }
        }
Beispiel #14
0
        private async Task WaitForUserConfiguredDelayAsync()
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken);

            var optionsPage        = (OptionPageGrid)GetDialogPage(typeof(OptionPageGrid));
            var timeDelayInSeconds = optionsPage.TimeDelay;

            await Task.Delay(1000 *timeDelayInSeconds);
        }
Beispiel #15
0
        private void Parse(ITextSnapshot snapshot)
        {
            if (_isParsing)
            {
                return;
            }

            _isParsing = true;

            ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await Task.Delay(200);

                var list          = new List <Span>();
                var start         = 0;
                var end           = 0;
                var numberOfLines = 0;

                try
                {
                    foreach (ITextSnapshotLine line in snapshot.Lines)
                    {
                        if (IsAttributeLine(line, out Span attributeSpan))
                        {
                            if (start == 0)
                            {
                                start = attributeSpan.Start;
                            }

                            end = attributeSpan.End;
                            numberOfLines++;
                        }
                        else
                        {
                            if (start > 0 && (numberOfLines > 1 || (numberOfLines > 0 && _isShortCollapsedForm)))
                            {
                                list.Add(Span.FromBounds(start, end));
                            }

                            numberOfLines = 0;
                            start         = 0;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Trace.Write(ex);
                }

                _spans     = list;
                _isParsing = false;
                var args   = new SnapshotSpanEventArgs(new SnapshotSpan(snapshot, 0, snapshot.Length));

                TagsChanged?.Invoke(this, args);
            }).FileAndForget(nameof(CollapseAttributeTagger));
        }
Beispiel #16
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                CacheConfluenceStats();

                const int delayInMilliseconds = MinutesBetweenSyncs * 60 * 60;
                await Task.Delay(delayInMilliseconds, stoppingToken);
            }
        }
Beispiel #17
0
        private async Task ForceNanoDeviceSelection(NanoDeviceBase nanoDevice)
        {
            await Task.Delay(100);

            // select the device
            SelectedDevice = nanoDevice;

            // request forced selection of device in UI
            MessengerInstance.Send(new NotificationMessage(""), MessagingTokens.ForceSelectionOfNanoDevice);
        }
        private async void FadeIn(int interval = 50)
        {
            while (Opacity < 1.0)
            {
                await Task.Delay(interval);

                Opacity += 0.05;
            }
            Opacity = 1;
        }
        private async void FadeOut(int interval = 50)
        {
            while (Opacity > 0.0)
            {
                await Task.Delay(interval);

                Opacity -= 0.05;
            }
            Opacity = 0;
        }
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            ReportProgress(1, 3);
            await Task.Delay(3000);

            ReportProgress(2, 3);
            await Task.Delay(3000);

            ReportProgress(3, 3);
        }
Beispiel #21
0
        public async Task WriteTooManyData()
        {
            _writeApi?.Dispose();

            const int count     = 500_000;
            const int batchSize = 50_000;

            var measurements = new List <H20Measurement>();

            for (var i = 0; i < count; i++)
            {
                measurements.Add(new H20Measurement
                {
                    Level = i, Time = DateTime.UnixEpoch.Add(TimeSpan.FromSeconds(i)), Location = "Europe"
                });
            }

            var successEvents = new List <WriteSuccessEvent>();

            _writeApi = Client.GetWriteApi(WriteOptions.CreateNew().BatchSize(batchSize).FlushInterval(10_000).Build());
            _writeApi.EventHandler += (sender, args) => { successEvents.Add(args as WriteSuccessEvent); };

            var start = 0;

            for (;;)
            {
                var history = measurements.Skip(start).Take(batchSize).ToArray();
                if (history.Length == 0)
                {
                    break;
                }

                if (start != 0)
                {
                    Trace.WriteLine("Delaying...");
                    await Task.Delay(100);
                }

                start += batchSize;
                Trace.WriteLine(
                    $"Add measurement to buffer From: {history.First().Time}, To: {history.Last().Time}. Remaining {count - start}");
                _writeApi.WriteMeasurements(_bucket.Name, _organization.Name, WritePrecision.S,
                                            history);
            }

            Trace.WriteLine("Flushing data...");
            Client.Dispose();
            Trace.WriteLine("Finished");

            Assert.AreEqual(10, successEvents.Count);
            foreach (var successEvent in successEvents)
            {
                Assert.AreEqual(50_000, successEvent.LineProtocol.Split("\n").Length);
            }
        }
Beispiel #22
0
 public void TextChanged(string searchText)
 {
     latestSearch = searchText;
     TPLTask.Delay(ThrottlingDelayMilliseconds).ContinueWith(_ =>
     {
         if (latestSearch == searchText)
         {
             StartOperation(searchText);
         }
     });
 }
Beispiel #23
0
        private static async Task GetMeetingsLoop()
        {
            Console.WriteLine(">> Starting GetMeetings Loop ");

            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                GetMeetings();
            }

            await Task.Delay(5000);
        }
Beispiel #24
0
 private void ProcessInput(string value)
 {
     Task.Factory.StartNew(() =>
     {
         value.ForEach(c =>
         {
             _remoteService.Send(GetIp(), new EventModel(EventType.KeyPress, EventKey.Lit_, c.ToString()));
             Task.Delay(100).Wait();
         });
     });
 }
Beispiel #25
0
        private async void SolutionEvents_AfterClosing()
        {
            // If the user closed a solution, switch back
            // to the global (or new solution's) settings
            // Wait a bit to avoid double-loading in case
            // the user opened a new solution, as opposed
            // to closing this one only.
            await Task.Delay(750);

            persister.ActivateSettingsFile(locator.GetActiveFile(dte.Solution));
        }
Beispiel #26
0
        private async void FadeIn(Form o, int interval = 80)
        {
            //Object is not fully invisible. Fade it in
            while (o.Opacity < 1.0)
            {
                await Task.Delay(interval);

                o.Opacity += 0.05;
            }
            o.Opacity = 1; //make fully visible
        }
Beispiel #27
0
        private async void ChangeColor()
        {
            do
            {
                await AsyncOperation.Delay(1000);

                var mod = Count % 5;
                FontColor = Colors[Math.Abs(Count - (Count - (4 - Count % 5)))];
                Message   = $"Color ha cambiado {Count} beses.";
            } while (Count++ < 50);
        }
Beispiel #28
0
        /// <summary>
        /// SendWithDelay
        /// </summary>
        /// <param name="title"></param>
        /// <param name="shortcut"></param>
        /// <returns></returns>
        /// <exception cref="OperationCanceledException">Ignore.</exception>
        private async Task StatusBarWithDelayAsync(string text, int delayMs)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            Dte.StatusBar.Text = text;

            Dte.StatusBar.Highlight(true);

            await Task.Delay(delayMs);

            Dte.StatusBar.Text = "";
        }
Beispiel #29
0
            protected override async Task ExecuteAsync()
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var folder   = HostPackage.Options.VmStateSaveFileFolder;
                var filename = VsxDialogs.FileOpen(VMSTATE_FILTER, folder);

                if (filename == null)
                {
                    return;
                }

                // --- Stop the virtual machine, provided it runs
                var options      = HostPackage.Options;
                var pane         = OutputWindow.GetPane <SpectrumVmOutputPane>();
                var vm           = HostPackage.EmulatorViewModel;
                var machineState = vm.MachineState;

                if ((machineState == VmState.Running || machineState == VmState.Paused))
                {
                    if (options.ConfirmMachineRestart)
                    {
                        var answer = VsxDialogs.Show("Are you sure, you want to restart " +
                                                     "the ZX Spectrum virtual machine?",
                                                     "The ZX Spectum virtual machine is running",
                                                     MessageBoxButton.YesNo, VsxMessageBoxIcon.Question, 1);
                        if (answer == VsxDialogResult.No)
                        {
                            return;
                        }
                    }

                    // --- Stop the machine and allow 50ms to stop.
                    await HostPackage.EmulatorViewModel.Machine.Stop();

                    await Task.Delay(50);

                    if (vm.MachineState != VmState.Stopped)
                    {
                        const string MESSAGE = "The ZX Spectrum virtual machine did not stop.";
                        await pane.WriteLineAsync(MESSAGE);

                        VsxDialogs.Show(MESSAGE, "Unexpected issue",
                                        MessageBoxButton.OK, VsxMessageBoxIcon.Error);
                        return;
                    }
                }

                // --- Load the file and keep it paused
                VmStateFileManager.LoadVmStateFile(filename);
                HostPackage.EmulatorViewModel.ForceScreenRefresh();
                HostPackage.EmulatorViewModel.ForcePauseVmAfterStateRestore();
            }
Beispiel #30
0
        public async Task CanDeleteRepostitory()
        {
            // Arrange
            string        registry   = TestEnvironment.Registry;
            string        repository = $"library/hello-world";
            List <string> tags       = new List <string>()
            {
                "latest",
                "v1",
                "v2",
                "v3",
                "v4",
            };
            var client = CreateClient();

            try
            {
                if (Mode != RecordedTestMode.Playback)
                {
                    await ImportImage(registry, repository, tags);
                }

                // Act
                await client.DeleteRepositoryAsync(repository);

                // Assert
                // This will be removed, pending investigation into potential race condition.
                // https://github.com/azure/azure-sdk-for-net/issues/19699
                if (Mode != RecordedTestMode.Playback)
                {
                    await Task.Delay(5000);
                }

                var repositories = client.GetRepositoryNamesAsync();

                await foreach (var item in repositories)
                {
                    if (item.Contains(repository))
                    {
                        Assert.Fail($"Repository {repository} was not deleted.");
                    }
                }
            }
            finally
            {
                // Clean up - put the repository with tags back.
                if (Mode != RecordedTestMode.Playback)
                {
                    await ImportImage(registry, repository, tags);
                }
            }
        }