Example #1
0
        private unsafe void AttachDebugger(Uri uri)
        {
            var debugger  = (IVsDebugger2)NodejsPackage.GetGlobalService(typeof(SVsShellDebugger));
            var debugInfo = new VsDebugTargetInfo2();

            var pDebugEngines = stackalloc Guid[1];

            pDebugEngines[0] = AD7Engine.DebugEngineGuid;

            debugInfo.cbSize = (uint)Marshal.SizeOf(typeof(VsDebugTargetInfo2));
            debugInfo.dlo    = (uint)DEBUG_LAUNCH_OPERATION.DLO_AlreadyRunning;
            debugInfo.guidLaunchDebugEngine = AD7Engine.DebugEngineGuid;
            debugInfo.dwDebugEngineCount    = 1;
            debugInfo.pDebugEngines         = (IntPtr)pDebugEngines;
            debugInfo.guidPortSupplier      = NodeRemoteDebugPortSupplier.PortSupplierGuid;
            debugInfo.bstrPortName          = uri.ToString();
            debugInfo.dwProcessId           = NodeRemoteDebugProcess.RemoteId;
            debugInfo.bstrExe     = (char)0 + "0x" + debugInfo.dwProcessId.ToString("X"); // this must be set to NUL + process ID in hex when DLO_AlreadyRunning is specified
            debugInfo.LaunchFlags = 0;

            var pDebugInfo = stackalloc byte[Marshal.SizeOf(debugInfo)];

            Marshal.StructureToPtr(debugInfo, (IntPtr)pDebugInfo, false);
            Marshal.ThrowExceptionForHR(debugger.LaunchDebugTargets2(1, (IntPtr)pDebugInfo));
        }
        public DataTipTextViewFilter(System.IServiceProvider serviceProvider, IVsTextView vsTextView)
        {
            _debugger = (IVsDebugger)NodejsPackage.GetGlobalService(typeof(IVsDebugger));
            vsTextView.GetBuffer(out _vsTextLines);

            var editorAdaptersFactory = serviceProvider.GetComponentModel().GetService <IVsEditorAdaptersFactoryService>();

            _wpfTextView = editorAdaptersFactory.GetWpfTextView(vsTextView);

            ErrorHandler.ThrowOnFailure(vsTextView.AddCommandFilter(this, out _next));
        }
Example #3
0
        private static string GetSolutionInfo()
        {
            var res = new StringBuilder();

            var dte = (EnvDTE.DTE)NodejsPackage.GetGlobalService(typeof(EnvDTE.DTE));

            res.AppendLine("Projects:");

            foreach (EnvDTE.Project project in dte.Solution.Projects)
            {
                res.AppendLine(Indent(1, GetProjectInfo(project)));
            }

            return(res.ToString());
        }
Example #4
0
        private void ConnectToIdle()
        {
            if (!this._connectedToIdle)
            {
                this._connectedToIdle = true;
                this._idleConnectTime = DateTime.Now;

                // make sure our package is loaded so we can use its
                // OnIdle event
                var nodePackage = new Guid(Guids.NodejsPackageString);
                var shell       = (IVsShell)NodejsPackage.GetGlobalService(typeof(SVsShell));
                shell.LoadPackage(ref nodePackage, out var package);

                NodejsPackage.Instance.OnIdle += this.OnIdle;
            }
        }
Example #5
0
 public static void DoDeployment(TestContext context)
 {
     AssertListener.Initialize();
     NodejsTestData.Deploy();
     if (NodejsPackage.Instance == null)
     {
         // The REPL is open on restart, but our package isn't loaded yet.  Force
         // it to load now.
         var        shell       = (IVsShell)NodejsPackage.GetGlobalService(typeof(SVsShell));
         Guid       packageGuid = typeof(NodejsPackage).GUID;
         IVsPackage package;
         if (ErrorHandler.Failed(shell.LoadPackage(ref packageGuid, out package)))
         {
             return;
         }
         Debug.Assert(NodejsPackage.Instance != null);
     }
 }
Example #6
0
            private void UpdateAnalysisStatusAndSaveToDisk(bool analyzedAnything, TimeSpan elapsedTime)
            {
                string statsMessage = null;

                if (_analyzer._jsAnalyzer != null)
                {
                    int count = _analyzer._jsAnalyzer.GetAndClearAnalysisCount();
                    if (count != 0)
                    {
                        statsMessage = SR.GetString(SR.StatusAnalysisUpToDate, count, FormatTime(elapsedTime));
                    }
                }

                if (_analyzer._saveToDisk && analyzedAnything && (DateTime.Now - _lastSave) > _SaveAnalysisTime)
                {
                    var statusbar = (IVsStatusbar)NodejsPackage.GetGlobalService(typeof(SVsStatusbar));
                    if (statusbar != null)
                    {
                        statusbar.SetText(SR.GetString(SR.StatusAnalysisSaving) + " " + statsMessage);
                    }

                    _analyzer.SaveAnalysis();
                    _lastSave = DateTime.Now;

                    if (statusbar != null)
                    {
                        statusbar.SetText(SR.GetString(SR.StatusAnalysisSaved) + " " + statsMessage);
                    }
                }
                else if (statsMessage != null)
                {
                    var statusbar = (IVsStatusbar)NodejsPackage.GetGlobalService(typeof(SVsStatusbar));
                    if (statusbar != null)
                    {
                        statusbar.SetText(statsMessage);
                    }
                }
            }
Example #7
0
        /// <summary>
        /// Retrieves the publish settings file (.pubxml) for the given Azure Website.
        /// </summary>
        /// <returns>XML document with the contents of .pubxml, or <c>null</c> if it could not be retrieved.</returns>
        private async Task <XDocument> GetPublishXml(AzureWebSiteInfo webSiteInfo)
        {
            // To build the publish settings request URL, we need to know subscription ID, site name, and web region to which it belongs,
            // but we only have subscription ID and the public URL of the site at this point. Use the Azure Website service to look up
            // the site from those two, and retrieve the missing info.

            IVsAzureServices webSiteServices = new VsAzureServicesShim(NodejsPackage.GetGlobalService(_azureServicesType));

            if (webSiteServices == null)
            {
                return(null);
            }

            var webSiteService = webSiteServices.GetAzureWebSitesService();

            if (webSiteService == null)
            {
                return(null);
            }

            var subscriptions = await webSiteService.GetSubscriptionsAsync();

            var subscription = subscriptions.FirstOrDefault(sub => sub.SubscriptionId == webSiteInfo.SubscriptionId);

            if (subscription == null)
            {
                return(null);
            }

            var resources = await subscription.GetResourcesAsync(false);

            var webSite = resources.OfType <IAzureWebSite>().FirstOrDefault(ws => {
                Uri browseUri;
                Uri.TryCreate(ws.BrowseURL, UriKind.Absolute, out browseUri);
                return(browseUri != null && browseUri.Equals(webSiteInfo.Uri));
            });

            if (webSite == null)
            {
                return(null);
            }

            // Prepare a web request to get the publish settings.
            // See http://msdn.microsoft.com/en-us/library/windowsazure/dn166996.aspx
            string requestPath = string.Format(CultureInfo.InvariantCulture,
                                               "{0}/services/WebSpaces/{1}/sites/{2}/publishxml",
                                               subscription.SubscriptionId,
                                               webSite.WebSpace,
                                               webSite.Name);
            Uri            requestUri = new Uri(((IAzureSubscription)subscription).ServiceManagementEndpointUri, requestPath);
            HttpWebRequest request    = (HttpWebRequest)WebRequest.Create(requestUri);

            request.Method      = "GET";
            request.ContentType = "application/xml";
            request.Headers.Add("x-ms-version", "2010-10-28");

            // Set up authentication for the request, depending on whether the associated subscription context is
            // account-based or certificate-based.
            object context     = subscription.AzureCredentials;
            var    certContext = context as IAzureAuthenticationCertificateSubscriptionContext;

            if (certContext != null)
            {
                var cert = await certContext.AuthenticationCertificate.GetCertificateFromStoreAsync();

                request.ClientCertificates.Add(cert);
            }
            else
            {
                var accountCountext = context as IAzureUserAccountSubscriptionContext;
                if (accountCountext != null)
                {
                    string authHeader = await accountCountext.GetAuthenticationHeaderAsync(false);

                    request.Headers.Add(HttpRequestHeader.Authorization, authHeader);
                }
                else
                {
                    return(null);
                }
            }

            using (WebResponse response = await request.GetResponseAsync())
                using (Stream stream = response.GetResponseStream()) {
                    // There is no XDocument.LoadAsync, but we want the networked I/O at least to be async, even if parsing is not.
                    Stream xmlData = new MemoryStream();
                    await stream.CopyToAsync(xmlData);

                    xmlData.Position = 0;
                    return(XDocument.Load(xmlData));
                }
        }
Example #8
0
        /// <returns>
        /// Information about the current selected Azure Website node in Solution Explorer, or <c>null</c>
        /// if no node is selected, it's not a website node, or the information could not be retrieved.
        /// </returns>
        private AzureWebSiteInfo GetSelectedAzureWebSite()
        {
            // Get the current selected node in Solution Explorer.

            var            shell = (IVsUIShell)NodejsPackage.GetGlobalService(typeof(SVsUIShell));
            var            serverExplorerToolWindowGuid = new Guid(ToolWindowGuids.ServerExplorer);
            IVsWindowFrame serverExplorerFrame;

            shell.FindToolWindow(0, ref serverExplorerToolWindowGuid, out serverExplorerFrame);
            if (serverExplorerFrame == null)
            {
                return(null);
            }

            object obj;

            serverExplorerFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out obj);
            var serverExplorerHierWnd = obj as IVsUIHierarchyWindow;

            if (serverExplorerHierWnd == null)
            {
                return(null);
            }

            IntPtr             hierPtr;
            uint               itemid;
            IVsMultiItemSelect mis;

            serverExplorerHierWnd.GetCurrentSelection(out hierPtr, out itemid, out mis);
            if (hierPtr == IntPtr.Zero)
            {
                return(null);
            }

            IVsHierarchy hier;

            try {
                hier = (IVsHierarchy)Marshal.GetObjectForIUnknown(hierPtr);
            } finally {
                Marshal.Release(hierPtr);
            }

            // Get the browse object of that node - this is the object that exposes properties to show in the Properties window.

            hier.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_SelContainer, out obj);
            var selCtr = obj as ISelectionContainer;

            if (selCtr == null)
            {
                return(null);
            }

            var objs = new object[1];

            selCtr.GetObjects((uint)Microsoft.VisualStudio.Shell.Interop.Constants.GETOBJS_SELECTED, 1, objs);
            obj = objs[0];
            if (obj == null)
            {
                return(null);
            }

            // We need to find out whether this is an Azure Website object. We can't do a type check because the type of the
            // browse object is private. We can, however, query for properties with specific names, and we can check the types
            // of those properties. In particular, WebSiteState is a public enum type that is a part of the Azure Explorer contract,
            // so we can check for it, and we can be reasonably sure that it is only exposed by website nodes. It seems that
            // the namespace is subject to change, however, as it was marked internal in VS2015.

            var statusProp = obj.GetType().GetProperty("Status");

            if (statusProp == null ||
                (statusProp.PropertyType.FullName != "Microsoft.VisualStudio.Web.WindowsAzure.Contracts.WebSiteState" &&
                 statusProp.PropertyType.FullName != "Microsoft.VisualStudio.Web.Internal.Contracts.WebSiteState")
                )
            {
                return(null);
            }

            // Is the website running?
            int status = (int)statusProp.GetValue(obj);

            if (status != 1)
            {
                return(null);
            }

            // Get the URI
            var urlProp = obj.GetType().GetProperty("Url");

            if (urlProp == null || urlProp.PropertyType != typeof(string))
            {
                return(null);
            }
            Uri uri;

            if (!Uri.TryCreate((string)urlProp.GetValue(obj), UriKind.Absolute, out uri))
            {
                return(null);
            }

            // Get Azure subscription ID
            var subIdProp = obj.GetType().GetProperty("SubscriptionID");

            if (subIdProp == null || subIdProp.PropertyType != typeof(string))
            {
                return(null);
            }
            string subscriptionId = (string)subIdProp.GetValue(obj);

            return(new AzureWebSiteInfo(uri, subscriptionId));
        }
Example #9
0
        private string GetData()
        {
            StringBuilder res = new StringBuilder();

            res.AppendLine("Use Ctrl-C to copy contents");
            res.AppendLine();

            var dte = (EnvDTE.DTE)NodejsPackage.GetGlobalService(typeof(EnvDTE.DTE));

            res.AppendLine("Projects: ");

            var projects = dte.Solution.Projects;
            var interestingDteProperties = new[] { "StartupFile", "WorkingDirectory", "PublishUrl", "SearchPath", "CommandLineArguments" };

            //var interestingProjectProperties = new[] { "AnalysisLevel" };

            foreach (EnvDTE.Project project in projects)
            {
                string name;
                try {
                    // Some projects will throw rather than give us a unique
                    // name. They are not ours, so we will ignore them.
                    name = project.UniqueName;
                } catch (Exception ex) {
                    if (ex.IsCriticalException())
                    {
                        throw;
                    }
                    bool isNodejsProject = false;
                    try {
                        isNodejsProject = Utilities.GuidEquals(Guids.NodejsProjectFactoryString, project.Kind);
                    } catch (Exception ex2) {
                        if (ex2.IsCriticalException())
                        {
                            throw;
                        }
                    }
                    if (isNodejsProject)
                    {
                        // Actually, it was one of our projects, so we do care
                        // about the exception. We'll add it to the output,
                        // rather than crashing.
                        res.AppendLine("    Project: " + ex.Message);
                        res.AppendLine("        Kind: Node.js");
                    }
                    continue;
                }
                res.AppendLine("    Project: " + name);

                if (Utilities.GuidEquals(Guids.NodejsBaseProjectFactoryString, project.Kind))
                {
                    res.AppendLine("        Kind: Node.js");

                    foreach (var prop in interestingDteProperties)
                    {
                        res.AppendLine("        " + prop + ": " + GetProjectProperty(project, prop));
                    }
                    var njsProj = project.GetNodejsProject();
                    if (njsProj != null)
                    {
                        var jsAnalyzer = njsProj.Analyzer;
                        if (jsAnalyzer != null)
                        {
                            res.AppendLine("Analysis Log: ");

                            using (StringWriter writer = new StringWriter(res)) {
                                jsAnalyzer.DumpLog(writer);
                            }
                        }

                        //foreach (var prop in interestingProjectProperties) {
                        //    var propValue = njsProj.GetProjectProperty(prop);
                        //    if (propValue != null) {
                        //        res.AppendLine("        " + prop + ": " + propValue);
                        //    }
                        //}
                    }
                }
                else
                {
                    res.AppendLine("        Kind: " + project.Kind);
                }

                res.AppendLine();
            }

            try {
                res.AppendLine("Logged events/stats:");
                var inMemLogger = NodejsPackage.Instance.GetComponentModel().GetService <InMemoryLogger>();
                res.AppendLine(inMemLogger.ToString());
                res.AppendLine();
            } catch (Exception ex) {
                if (ex.IsCriticalException())
                {
                    throw;
                }
                res.AppendLine("  Failed to access event log.");
                res.AppendLine(ex.ToString());
                res.AppendLine();
            }

            res.AppendLine("Loaded assemblies:");
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().OrderBy(assem => assem.FullName))
            {
                var assemFileVersion = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false).OfType <AssemblyFileVersionAttribute>().FirstOrDefault();

                res.AppendLine(string.Format("  {0}, FileVersion={1}",
                                             assembly.FullName,
                                             assemFileVersion == null ? "(null)" : assemFileVersion.Version
                                             ));
            }
            res.AppendLine();


            res.AppendLine(String.Format("Analysis Level: {0}", NodejsPackage.Instance.IntellisenseOptionsPage.AnalysisLevel.ToString()));
            res.AppendLine();
            if (NodejsPackage.Instance._analyzer != null)
            {
                var jsAnalyzer = NodejsPackage.Instance._analyzer;
                res.AppendLine("Default Analysis Log: ");

                using (StringWriter writer = new StringWriter(res)) {
                    jsAnalyzer.DumpLog(writer);
                }
            }

            res.AppendLine(String.Format("IntelliSense Completion Only Tab or Enter to Commit: {0}", NodejsPackage.Instance.IntellisenseOptionsPage.OnlyTabOrEnterToCommit));
            res.AppendLine();

            return(res.ToString());
        }
Example #10
0
            private void Worker(object threadStarted)
            {
                ((AutoResetEvent)threadStarted).Set();
                Stopwatch watch = new Stopwatch();

                watch.Start();
                long startTime        = watch.ElapsedMilliseconds;
                bool analyzedAnything = false;

                while (!_cancel.IsCancellationRequested)
                {
                    IAnalyzable workItem;

                    AnalysisPriority pri;
                    lock (_queueLock) {
                        workItem     = GetNextItem(out pri);
                        _isAnalyzing = true;
                    }
                    if (workItem != null)
                    {
                        analyzedAnything = true;
                        var groupable = workItem as IGroupableAnalysisProjectEntry;
                        if (groupable != null)
                        {
                            bool added = _enqueuedGroups.Add(groupable.AnalysisGroup);
                            if (added)
                            {
                                Enqueue(new GroupAnalysis(groupable.AnalysisGroup, this), pri);
                            }

                            groupable.Analyze(_cancel.Token, true);
                        }
                        else
                        {
                            workItem.Analyze(_cancel.Token);
                        }
                    }
                    else
                    {
                        string statsMessage = null;
                        if (_analyzer._jsAnalyzer != null)
                        {
                            int count = _analyzer._jsAnalyzer.GetAndClearAnalysisCount();
                            if (count != 0)
                            {
                                var elapsedTime = TimeSpan.FromMilliseconds(watch.ElapsedMilliseconds - startTime);
                                statsMessage = SR.GetString(SR.StatusAnalysisUpToDate, count, FormatTime(elapsedTime));
                            }
                        }

                        if (_analyzer._saveToDisk && analyzedAnything && (DateTime.Now - _lastSave) > _SaveAnalysisTime)
                        {
                            var statusbar = (IVsStatusbar)NodejsPackage.GetGlobalService(typeof(SVsStatusbar));
                            if (statusbar != null)
                            {
                                statusbar.SetText(SR.GetString(SR.StatusAnalysisSaving) + " " + statsMessage);
                            }

                            _analyzer.SaveAnalysis();
                            _lastSave = DateTime.Now;

                            if (statusbar != null)
                            {
                                statusbar.SetText(SR.GetString(SR.StatusAnalysisSaved) + " " + statsMessage);
                            }
                        }
                        else if (statsMessage != null)
                        {
                            var statusbar = (IVsStatusbar)NodejsPackage.GetGlobalService(typeof(SVsStatusbar));
                            if (statusbar != null)
                            {
                                statusbar.SetText(statsMessage);
                            }
                        }

                        _isAnalyzing = false;
                        WaitHandle.SignalAndWait(
                            _analyzer._queueActivityEvent,
                            _workEvent
                            );
                        startTime = watch.ElapsedMilliseconds;
                    }
                }
                _isAnalyzing = false;
            }