Ejemplo n.º 1
0
 internal void SendMessageRequest()
 {
     Task.Run(async() =>
     {
         MessageActionItem selectedAction = await this.languageServer.ShowMessageRequestAsync(message: this.LogMessage, messageType: this.MessageType, actionItems: new string[] { "option 1", "option 2", "option 3" });
         this.ResponseText = $"The user selected: {selectedAction?.Title ?? "cancelled"}";
     });
 }
Ejemplo n.º 2
0
                #pragma warning disable VSTHRD002 // Avoid problematic synchronous waits

        public static MessageActionItem ShowMessage(ShowMessageRequestParams message)
        {
            MessageActionItem result = null;

            Runtime.RunInMainThread(() => {
                result = ShowMessageInternal(message);
            }).Wait();

            return(result);
        }
Ejemplo n.º 3
0
        public void SimpleTest(string expected)
        {
            var model = new MessageActionItem {
                Title = "abc"
            };
            var result = Fixture.SerializeObject(model);

            result.Should().Be(expected);

            var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject <MessageActionItem>(expected);

            deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality());
        }
Ejemplo n.º 4
0
        public void SimpleTest(string expected)
        {
            var model = new MessageActionItem()
            {
                Title = "abc"
            };
            var result = Fixture.SerializeObject(model);

            result.Should().Be(expected);

            var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject <MessageActionItem>(expected);

            deresult.ShouldBeEquivalentTo(model);
        }
        internal void SendMessageRequest()
        {
            var response = Task.Run(async() =>
            {
                List <string> options = new List <string>();
                int optionsCount      = 0;
                optionsCount          = int.TryParse(MessageRequestOptions, out optionsCount) ? Math.Min(optionsCount, 1000) : 3;

                for (int i = 0; i < optionsCount; i++)
                {
                    options.Add($"option {i}");
                }

                MessageActionItem selectedAction = await this.languageServer.ShowMessageRequestAsync(message: this.LogMessage, messageType: this.MessageType, actionItems: options.ToArray());
                this.ResponseText = $"The user selected: {selectedAction?.Title ?? "cancelled"}";
            });
        }
        internal async Task CheckDotNetSdkVersionAsync()
        {
            var isDotNet31Installed = DotNetSdkHelper.IsDotNet31Installed();

            if (isDotNet31Installed == null)
            {
                this.LogToWindow("Unable to detect .NET SDK versions", MessageType.Error);
            }
            else
            {
                if (isDotNet31Installed != true)
                {
                    const string dotnet31Url = "https://dotnet.microsoft.com/download/dotnet-core/3.1";
                    this.LogToWindow($".NET Core SDK 3.1 not found. Quantum Development Kit Extension requires .NET Core SDK 3.1 to work properly ({dotnet31Url}).", MessageType.Error);
                    var downloadAction = new MessageActionItem {
                        Title = "Download"
                    };
                    var cancelAction = new MessageActionItem {
                        Title = "No, thanks"
                    };
                    var selectedAction = await this.ShowDialogInWindowAsync(
                        "Quantum Development Kit Extension requires .NET Core SDK 3.1 to work properly. Please install .NET Core SDK 3.1 and restart Visual Studio.",
                        MessageType.Error,
                        new[] { downloadAction, cancelAction });

                    if (selectedAction != null &&
                        selectedAction.Title == downloadAction.Title)
                    {
                        Process.Start(new ProcessStartInfo
                        {
                            FileName        = dotnet31Url,
                            UseShellExecute = true,
                            CreateNoWindow  = true,
                        });
                    }
                }
            }
        }
        private async Task CheckPackageManagement()
        {
            PSCommand getModule = new PSCommand().AddCommand("Get-Module").AddParameter("ListAvailable").AddParameter("Name", "PackageManagement");

            foreach (PSModuleInfo module in await _powerShellContextService.ExecuteCommandAsync <PSModuleInfo>(getModule).ConfigureAwait(false))
            {
                // The user has a good enough version of PackageManagement
                if (module.Version >= s_desiredPackageManagementVersion)
                {
                    break;
                }

                _logger.LogDebug("Old version of PackageManagement detected.");

                if (_powerShellContextService.CurrentRunspace.Runspace.SessionStateProxy.LanguageMode != PSLanguageMode.FullLanguage)
                {
                    _languageServer.Window.ShowWarning("You have an older version of PackageManagement known to cause issues with the PowerShell extension. Please run the following command in a new Windows PowerShell session and then restart the PowerShell extension: `Install-Module PackageManagement -Force -AllowClobber -MinimumVersion 1.4.6`");
                    return;
                }

                var takeActionText = "Yes";
                MessageActionItem messageAction = await _languageServer.Window.ShowMessageRequest(new ShowMessageRequestParams
                {
                    Message = "You have an older version of PackageManagement known to cause issues with the PowerShell extension. Would you like to update PackageManagement (You will need to restart the PowerShell extension after)?",
                    Type    = MessageType.Warning,
                    Actions = new[]
                    {
                        new MessageActionItem
                        {
                            Title = takeActionText
                        },
                        new MessageActionItem
                        {
                            Title = "Not now"
                        }
                    }
                }).ConfigureAwait(false);

                // If the user chose "Not now" ignore it for the rest of the session.
                if (messageAction?.Title == takeActionText)
                {
                    StringBuilder errors = new StringBuilder();
                    await _powerShellContextService.ExecuteScriptStringAsync(
                        "powershell.exe -NoLogo -NoProfile -Command '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Install-Module -Name PackageManagement -Force -MinimumVersion 1.4.6 -Scope CurrentUser -AllowClobber -Repository PSGallery'",
                        errors,
                        writeInputToHost : true,
                        writeOutputToHost : true,
                        addToHistory : true).ConfigureAwait(false);

                    if (errors.Length == 0)
                    {
                        _logger.LogDebug("PackageManagement is updated.");
                        _languageServer.Window.ShowMessage(new ShowMessageParams
                        {
                            Type    = MessageType.Info,
                            Message = "PackageManagement updated, If you already had PackageManagement loaded in your session, please restart the PowerShell extension."
                        });
                    }
                    else
                    {
                        // There were errors installing PackageManagement.
                        _logger.LogError($"PackageManagement installation had errors: {errors.ToString()}");
                        _languageServer.Window.ShowMessage(new ShowMessageParams
                        {
                            Type    = MessageType.Error,
                            Message = "PackageManagement update failed. This might be due to PowerShell Gallery using TLS 1.2. More info can be found at https://aka.ms/psgallerytls"
                        });
                    }
                }
            }
        }
Ejemplo n.º 8
0
        /// <nodoc />
        public Result <WorkspaceEdit, ResponseError> GetWorkspaceEdits(RenameParams renameParameters, CancellationToken token)
        {
            if (!TryFindNode(renameParameters.ToTextDocumentPosition(), out var node))
            {
                return(s_emptyResult);
            }

            // The logic for IsNodeEligibleForRenameand the checking for the import statement
            // was ported directly from the typescript version. Whe the import statement
            // isn't inside the IsNodeEligibleForRename function isn't clear. Perhaps
            // it is used elsewhere in TypeScript.

            // Do a pre-check to see if this node is even remotely eiligible for rename
            // This is purely based on syntax kind.
            if (!IsNodeEligibleForRename(node))
            {
                return(s_emptyResult);
            }

            // Make sure we aren't trying to rename attempts to rename
            // the "default" keyword from the import statement.
            // TODO: This was ported from the type-script repositiory. I'm not sure I completely understand this.
            var symbol = TypeChecker.GetSymbolAtLocation(node);

            if (symbol != null &&
                symbol.Declarations?.Count > 0 &&
                node.Kind == SyntaxKind.Identifier &&
                node.Cast <IIdentifier>().OriginalKeywordKind == SyntaxKind.DefaultKeyword &&
                (symbol.Parent.Flags & SymbolFlags.Module) != SymbolFlags.Namespace)
            {
                return(s_emptyResult);
            }

            // Call the find all references provider and get all the locations.
            var findReferencesResult = m_findReferencesProvider.GetReferencesAtPosition(renameParameters.ToTextDocumentPosition(), token);

            if (!findReferencesResult.IsSuccess)
            {
                return(Result <WorkspaceEdit, ResponseError> .Error(findReferencesResult.ErrorValue));
            }

            // Next, we need to create a list per document URI (so a dictionary of Document URI to Ranges)
            // to create the workspace edits.
            var rangesByUri = new MultiValueDictionary <string, LanguageServerProtocolRange>();

            foreach (var location in findReferencesResult.SuccessValue)
            {
                rangesByUri.Add(location.Uri, location.Range);
            }

            // If the change is referenced in a lot of places that would cause performance issue
            // as all the files being touched would be opened by the IDE
            int fileReferenceCount = rangesByUri.Count;

            if (fileReferenceCount > ReferenceThreshold)
            {
                string message = string.Format(BuildXL.Ide.LanguageServer.Strings.RenameWarningMessage, fileReferenceCount);

                var actions = new MessageActionItem[] {
                    new MessageActionItem()
                    {
                        Title = BuildXL.Ide.LanguageServer.Strings.ContinueActionTitle
                    },
                    new MessageActionItem()
                    {
                        Title = BuildXL.Ide.LanguageServer.Strings.CancelActionTitle
                    }
                };

                var response = RpcExtensions.ShowMessageRequestAsync(this.JsonRpc, MessageType.Warning, message, actions).GetAwaiter().GetResult();

                if (response == null || response.Title.Equals(BuildXL.Ide.LanguageServer.Strings.CancelActionTitle, System.StringComparison.OrdinalIgnoreCase))
                {
                    return(Result <WorkspaceEdit, ResponseError> .Success(null));
                }
            }

            // Now, create the result which is a URI to an Array of text edits.
            var changes = new Dictionary <string, TextEdit[]>();

            foreach (var uriToRangePair in rangesByUri)
            {
                var edits = new List <TextEdit>();
                foreach (var locationRange in uriToRangePair.Value)
                {
                    edits.Add(new TextEdit
                    {
                        NewText = renameParameters.NewName,
                        Range   = locationRange,
                    });
                }

                changes[uriToRangePair.Key] = edits.ToArray();
            }

            var result = new WorkspaceEdit
            {
                Changes = changes,
            };

            return(Result <WorkspaceEdit, ResponseError> .Success(result));
        }
        private async Task CheckPackageManagement()
        {
            PSCommand getModule = new PSCommand().AddCommand("Get-Module").AddParameter("ListAvailable").AddParameter("Name", "PackageManagement");

            foreach (PSModuleInfo module in await _powerShellContextService.ExecuteCommandAsync <PSModuleInfo>(getModule))
            {
                // The user has a good enough version of PackageManagement
                if (module.Version >= s_desiredPackageManagementVersion)
                {
                    break;
                }

                _logger.LogDebug("Old version of PackageManagement detected. Attempting to update.");

                var takeActionText = "Yes";
                MessageActionItem messageAction = await _languageServer.Window.ShowMessage(new ShowMessageRequestParams
                {
                    Message = "You have an older version of PackageManagement known to cause issues with the PowerShell extension. Would you like to update PackageManagement (You will need to restart the PowerShell extension after)?",
                    Type    = MessageType.Warning,
                    Actions = new []
                    {
                        new MessageActionItem
                        {
                            Title = takeActionText
                        },
                        new MessageActionItem
                        {
                            Title = "Not now"
                        }
                    }
                });

                // If the user chose "Not now" ignore it for the rest of the session.
                if (messageAction?.Title == takeActionText)
                {
                    StringBuilder errors = new StringBuilder();
                    await _powerShellContextService.ExecuteScriptStringAsync(
                        "powershell.exe -NoLogo -NoProfile -Command 'Install-Module -Name PackageManagement -Force -MinimumVersion 1.4.6 -Scope CurrentUser -AllowClobber'",
                        errors,
                        writeInputToHost : true,
                        writeOutputToHost : true,
                        addToHistory : true).ConfigureAwait(false);

                    if (errors.Length == 0)
                    {
                        _languageServer.Window.ShowMessage(new ShowMessageParams
                        {
                            Type    = MessageType.Info,
                            Message = "PackageManagement updated, If you already had PackageManagement loaded in your session, please restart the PowerShell extension."
                        });
                    }
                    else
                    {
                        // There were errors installing PackageManagement.
                        _languageServer.Window.ShowMessage(new ShowMessageParams
                        {
                            Type    = MessageType.Error,
                            Message = "PackageManagement update failed. Please run the following command in a new Windows PowerShell session and then restart the PowerShell extension: `Install-Module PackageManagement -Force -AllowClobber -MinimumVersion 1.4.6`"
                        });
                    }
                }
            }
        }