public PerfCounterData(PerfCounterType perfCounterType, string perfCounterCategory, string perfCounterName, string perfCounterInstanceName)
 {
     this.perfCounterType         = perfCounterType;
     this.PerfCounterCategory     = perfCounterCategory;
     this.PerfCounterName         = perfCounterName;
     this.PerfCounterInstanceName = perfCounterInstanceName;
     this.ResetCounter();
     ProcToMonitor = Process.GetCurrentProcess(); // this will be changed by stress tests
 }
Exemple #2
0
        private PerformanceCounterType ConcretePerfCounterType(PerfCounterType type)
        {
            switch (type)
            {
            case PerfCounterType.NumberOfItems32: return(PerformanceCounterType.NumberOfItems32);

            case PerfCounterType.RateOfCountsPerSecond32: return(PerformanceCounterType.RateOfCountsPerSecond32);

            case PerfCounterType.AverageCount64: return(PerformanceCounterType.AverageCount64);

            case PerfCounterType.AverageBase: return(PerformanceCounterType.AverageBase);

            default: throw new ArgumentException($"Unexpected performance counter type: {type}");
            }
        }
    public static void Main(string[] args)
    {
        ManagementClass c = new ManagementClass("Win32_PerfRawData");

        foreach (ManagementClass mc in c.GetSubclasses())
        {
            Console.WriteLine("Class: {0}", mc["__CLASS"]);
            foreach (PropertyData pd in mc.Properties)
            {
                try {
                    PerfCounterType ct = (PerfCounterType)ulong.Parse(
                        mc.GetPropertyQualifierValue(pd.Name, "CounterType").ToString());
                    Console.WriteLine("   {0} : {1}", pd.Name, ct);
                } catch (Exception e) {}
            }
            Console.WriteLine();
        }
    }
Exemple #4
0
        public PerfGraphToolWindowControl()
        {
            this.InitializeComponent();
            g_PerfGraphToolWindowControl = this;
            try
            {
#if DEBUG
                LogMessage($"Starting {TipString}");
#endif
                var tspanDesiredLeaseLifetime = TimeSpan.FromSeconds(2);
                var oldval = System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseTime;
                if (oldval == tspanDesiredLeaseLifetime)
                {
                    LogMessage($"System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseTime.TotalSeconds already set at {oldval.TotalSeconds} secs");
                }
                else
                {
                    try
                    {
                        System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseTime = tspanDesiredLeaseLifetime;
                        LogMessage($"Success Change System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseTime.TotalSeconds from {oldval.TotalSeconds} secs to {System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseTime.TotalSeconds}");
                    }
                    catch (System.Runtime.Remoting.RemotingException)
                    {
                        LogMessage($"Failed to Change System.Runtime.Remoting.Lifetime.LifetimeServices.LeaseTime.TotalSeconds from {oldval.TotalSeconds} secs to {tspanDesiredLeaseLifetime.TotalSeconds} secs");
                    }
                }
                LstPerfCounterData = PerfCounterData.GetPerfCountersToUse(System.Diagnostics.Process.GetCurrentProcess(), IsForStress: false);
                async Task RefreshCodeToRunAsync()
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    FileInfo mostRecentFileInfo = null;

                    foreach (var file in Directory.GetFiles(CodeSampleDirectory, "*.*", SearchOption.AllDirectories)
                             .Where(f => ".vb|.cs".Contains(Path.GetExtension(f).ToLower()))
                             .OrderByDescending(f => new FileInfo(f).LastWriteTime))
                    {
                        if (!file.Contains(@"\Util\"))// utility folder doesn't contain code with Main program
                        {
                            var finfo = new FileInfo(file);
                            if (mostRecentFileInfo == null || finfo.LastWriteTime > mostRecentFileInfo.LastWriteTime)
                            {
                                mostRecentFileInfo = finfo;
                            }
                        }
                    }
                    _codeSampleControl = new CodeSamples(CodeSampleDirectory, mostRecentFileInfo?.Name);
                    this.spCodeSamples.Children.Clear();
                    this.spCodeSamples.Children.Add(_codeSampleControl);
                }
                _ = Task.Run(() =>
                {
                    _ = RefreshCodeToRunAsync();
                });

                _fileSystemWatcher = new FileSystemWatcher(CodeSampleDirectory);
                FileSystemEventHandler h = new FileSystemEventHandler(
                    (o, e) =>
                {
                    //                                LogMessage($"FileWatcher {e.ChangeType} '{e.FullPath}'");
                    _ = RefreshCodeToRunAsync();
                }
                    );
                // we don't handle Rename here: just save the newly renamed file to trigger the Changed event.
                _fileSystemWatcher.Changed            += h;
                _fileSystemWatcher.Created            += h;
                _fileSystemWatcher.Deleted            += h;
                _fileSystemWatcher.EnableRaisingEvents = true;

                ThreadHelper.JoinableTaskFactory.StartOnIdle(async() =>
                {
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    if (PerfGraphToolWindowCommand.Instance.g_dte == null) // if the toolwindow was already opened, this is set in InitializeToolWindowAsync. 1st time opening set it here
                    {
                        EnvDTE.DTE dte = (EnvDTE.DTE) await PerfGraphToolWindowCommand.Instance.package.GetServiceAsync(typeof(EnvDTE.DTE));
                        PerfGraphToolWindowCommand.Instance.g_dte = dte; // ?? throw new InvalidOperationException(nameof(dte));
                    }
                    _objTracker    = new ObjTracker(this);
                    _editorTracker = PerfGraphToolWindowPackage.ComponentModel.GetService <EditorTracker>();

                    _editorTracker.Initialize(this, _objTracker);
                    _openFolderTracker = PerfGraphToolWindowPackage.ComponentModel.GetService <OpenFolderTracker>();
                    _openFolderTracker.Initialize(this, _objTracker);
                    if (this.IsLeakTrackerServiceSupported())
                    {
                        this.inProcLeakTracerTabItem.Visibility = Visibility.Visible;
                        this.inProcLeakTracker.Content          = new InProcLeakTracker();
                    }
                    await TaskScheduler.Default;
                    var telEvent = new TelemetryEvent(TelemetryEventBaseName + "Start");
                    TelemetryService.DefaultSession.PostEvent(telEvent);
                    await DoProcessAutoexecAsync();
                });

                txtUpdateInterval.LostFocus += (o, e) =>
                {
                    _ = ResetPerfCounterMonitorAsync();
                };

                btnDoSample.Click += (o, e) =>
                {
                    ThreadHelper.JoinableTaskFactory.Run(async() =>
                    {
                        await WaitForInitializationCompleteAsync();
                        await DoSampleAsync(measurementHolderInteractiveUser, DoForceGC: true, descriptionOverride: "Manual");
                    }
                                                         );
                };


                lbPCounters.ItemsSource   = LstPerfCounterData.Select(s => s.perfCounterType);
                lbPCounters.SelectedIndex = 0;
                LstPerfCounterData.Where(s => s.perfCounterType == PerfCounterType.GCBytesInAllHeaps).Single().IsEnabledForGraph = true;
#pragma warning disable VSTHRD101 // Avoid unsupported async delegates
                lbPCounters.SelectionChanged += async(ol, el) =>
                {
                    try
                    {
                        lbPCounters.IsEnabled = false;
                        // cancel the perf monitoring
                        _ctsPcounter?.Cancel();
                        // before we wait for cancel to finish we can do some work
                        PerfCounterType pctrEnum = PerfCounterType.None;
                        foreach (var itm in lbPCounters.SelectedItems)
                        {
                            pctrEnum |= (PerfCounterType)Enum.Parse(typeof(PerfCounterType), itm.ToString());
                        }
                        AddStatusMsgAsync($"Setting counters to {pctrEnum}").Forget();
                        // wait for it to be done cancelling
                        if (_tskDoPerfMonitoring != null)
                        {
                            await _tskDoPerfMonitoring;
                        }
                        await Task.Run(async() =>
                        {
                            // run on threadpool thread
                            lock (LstPerfCounterData)
                            {
                                foreach (var itm in LstPerfCounterData)
                                {
                                    itm.IsEnabledForGraph = pctrEnum.HasFlag(itm.perfCounterType);
                                }
                            }
                            await ResetPerfCounterMonitorAsync();
                        });

                        AddStatusMsgAsync($"SelectionChanged done").Forget();
                        lbPCounters.IsEnabled = true;
                        el.Handled            = true;
                    }
                    catch (Exception)
                    {
                    }
                };

                _chart       = new Chart();
                wfhost.Child = _chart;


                txtStatus.ContextMenu = new ContextMenu();
                txtStatus.ContextMenu.AddMenuItem((o, e) =>
                {
                    txtStatus.Clear();
                }, "_Clear All", "Clear the current contents");

                _ = Task.Run(async() =>
                {
                    //await AddStatusMsgAsync("Waiting 15 seconds to initialize graph");
                    //await Task.Delay(TimeSpan.FromSeconds(15));// delay samples til VS started
                    await ResetPerfCounterMonitorAsync();
                });
#if DEBUG
                var tsk = AddStatusMsgAsync($"PerfGraphVsix curdir= {Environment.CurrentDirectory}");
#endif
                Microsoft.VisualStudio.Shell.Events.SolutionEvents.OnAfterOpenProject += (o, e) =>
                {
                    Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

                    if (this.TrackProjectObjects)
                    {
                        var hier = e.Hierarchy;
                        if (hier.GetProperty((uint)Microsoft.VisualStudio.VSConstants.VSITEMID.Root,
                                             (int)Microsoft.VisualStudio.Shell.Interop.__VSHPROPID.VSHPROPID_ExtObject,
                                             out var extObject) == Microsoft.VisualStudio.VSConstants.S_OK)
                        {
                            var proj    = extObject as EnvDTE.Project;    // comobj or Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject
                            var name    = proj.Name;
                            var context = proj as IVsBrowseObjectContext; // Microsoft.VisualStudio.ProjectSystem.VS.Implementation.Package.Automation.OAProject
                            if (context == null && proj != null)
                            {
                                context = proj.Object as IVsBrowseObjectContext; // {Microsoft.VisualStudio.Project.VisualC.VCProjectEngine.VCProjectShim}
                            }
                            if (context != null)
                            {
                                //                                var task = AddStatusMsgAsync($"{nameof(Microsoft.VisualStudio.Shell.Events.SolutionEvents.OnAfterOpenProject)} {proj.Name}   Context = {context}");
                                _objTracker.AddObjectToTrack(context, ObjSource.FromProject, description: proj.Name);
                                //var x = proj.Object as Microsoft.VisualStudio.ProjectSystem.Properties.IVsBrowseObjectContext;
                            }
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                this.Content = ex.ToString();
            }
        }