Example #1
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DiagnosticsClient.TrackEvent("ClickShowRuntimeInfo");

            if (ButtonShowRuntimeVersionInfo.Content.ToString().StartsWith("Show"))
            {
                RuntimeVersionInfo.Text = ThisAppInfo.GetDotNetRuntimeInfo();
                ButtonShowRuntimeVersionInfo.Content = "Hide Runtime Info";
                // deneme
            }
            else
            {
                RuntimeVersionInfo.Text = "";
                ButtonShowRuntimeVersionInfo.Content = "Show Runtime Info";
            }
        }
Example #2
0
        public Guid StartProfilingSession(int processId, ILogger logger)
        {
            string strExeFilePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string strWorkPath    = Path.GetDirectoryName(strExeFilePath);
            string profilerDll    = Path.Combine(strWorkPath, "profiler.dll");

            var sessionId = Guid.NewGuid();

            DiagnosticsClient client = new DiagnosticsClient(processId);

            client.AttachProfiler(TimeSpan.FromSeconds(10), ProfilerId, profilerDll, Encoding.UTF8.GetBytes(sessionId.ToString() + "\0"));

            logger.Log($"Attached profiler {ProfilerId} with session {sessionId} to process {processId}");

            return(sessionId);
        }
        private void OnRemoveGroupClicked(object sender, RoutedEventArgs e)
        {
            DiagnosticsClient.TrackEvent("FrameworkReferencesEditor_OnRemoveGroupClicked");

            // remember the currently selected index;
            var selectedIndex = ReferenceGroupList.SelectedIndex;

            _referenceSets.Remove((EditableFrameworkReferenceGroup)ReferenceGroupList.SelectedItem);

            if (_referenceSets.Count > 0)
            {
                // after removal, restore the previously selected index
                selectedIndex = Math.Min(selectedIndex, _referenceSets.Count - 1);
                ReferenceGroupList.SelectedIndex = selectedIndex;
            }
        }
        private void UserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var info = (FileContentInfo)DataContext;

            if (info != null && info.IsTextFile)
            {
                DiagnosticsClient.TrackEvent("ContentViewer_LoadTextFile");
                LanguageBox.SelectedItem = SyntaxHighlightingHelper.GuessHighligtingDefinition(info.File.Name);
                contentBox.ScrollToHome();
                contentBox.Load(StreamUtility.ToStream((string)info.Content));
            }
            else
            {
                contentBox.Clear();
            }
        }
Example #5
0
        private void EditReferencesButtonClicked(object sender, RoutedEventArgs e)
        {
            DiagnosticsClient.TrackEvent("PackageMetadataEditor_EditReferencesButtonClicked");

            var editor = new PackageReferencesEditor(_referenceSets)
            {
                Owner          = Window.GetWindow(this),
                PackageChooser = PackageChooser
            };
            var result = editor.ShowDialog();

            if (result == true)
            {
                _referenceSets = editor.GetEditedReferencesSets();
            }
        }
Example #6
0
        private void OnRemoveGroupClicked(object sender, RoutedEventArgs e)
        {
            DiagnosticsClient.TrackEvent("PackageDependencyEditor_OnRemoveGroupClicked");

            // remember the currently selected index;
            var selectedIndex = DependencyGroupList.SelectedIndex;

            _dependencySets.Remove((EditablePackageDependencySet)DependencyGroupList.SelectedItem);

            if (_dependencySets.Count > 0)
            {
                // after removal, restore the previously selected index
                selectedIndex = Math.Min(selectedIndex, _dependencySets.Count - 1);
                DependencyGroupList.SelectedIndex = selectedIndex;
            }
        }
Example #7
0
        private void OkButton_Click(object sender, RoutedEventArgs e)
        {
            if (Validation.GetHasError(TargetFrameworkBox))
            {
                return;
            }

            DiagnosticsClient.TrackEvent("PackageDependencyEditor_OkButton");

            var canClose = string.IsNullOrEmpty(NewDependencyId.Text) || AddNewDependency();

            if (canClose)
            {
                DialogResult = true;
            }
        }
        private void EditDependenciesButtonClicked(object sender, RoutedEventArgs e)
        {
            DiagnosticsClient.TrackEvent("PackageMetadataEditor_EditDependenciesButtonClicked");

            var editor = new PackageDependencyEditor(_dependencyGroups)
            {
                Owner          = Window.GetWindow(this),
                PackageChooser = PackageChooser
            };
            var result = editor.ShowDialog();

            if (result == true)
            {
                _dependencyGroups = editor.GetEditedDependencySets();
            }
        }
        private void Window_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            // if the Control key (and only Control key) is pressed
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                DiagnosticsClient.TrackEvent("MainWindow_MouseWheelFontSize");

                var fontSizeDelta = e.Delta > 0 ? 2 : -2;
                var newFontSize   = SettingsManager.FontSize + fontSizeDelta;
                newFontSize = Math.Max(newFontSize, 12);
                newFontSize = Math.Min(newFontSize, 18);
                SettingsManager.FontSize = newFontSize;

                e.Handled = true;
            }
        }
Example #10
0
        public Task <ActionResult> Logs(
            ProcessFilter?processFilter,
            [FromQuery][Range(-1, int.MaxValue)] int durationSeconds = 30,
            [FromQuery] LogLevel level        = LogLevel.Debug,
            [FromQuery] string egressProvider = null)
        {
            return(InvokeForProcess(processInfo =>
            {
                TimeSpan duration = ConvertSecondsToTimeSpan(durationSeconds);

                LogFormat format = ComputeLogFormat(Request.GetTypedHeaders().Accept);
                if (format == LogFormat.None)
                {
                    return this.NotAcceptable();
                }

                string fileName = FormattableString.Invariant($"{GetFileNameTimeStampUtcNow()}_{processInfo.EndpointInfo.ProcessId}.txt");
                string contentType = format == LogFormat.EventStream ? ContentTypes.TextEventStream : ContentTypes.ApplicationNdJson;

                Func <Stream, CancellationToken, Task> action = async(outputStream, token) =>
                {
                    using var loggerFactory = new LoggerFactory();

                    loggerFactory.AddProvider(new StreamingLoggerProvider(outputStream, format, level));

                    var settings = new EventLogsPipelineSettings
                    {
                        Duration = duration,
                        LogLevel = level,
                    };

                    var client = new DiagnosticsClient(processInfo.EndpointInfo.Endpoint);

                    await using EventLogsPipeline pipeline = new EventLogsPipeline(client, settings, loggerFactory);
                    await pipeline.RunAsync(token);
                };

                return Result(
                    ArtifactType_Logs,
                    egressProvider,
                    action,
                    fileName,
                    contentType,
                    processInfo.EndpointInfo,
                    format != LogFormat.EventStream);
            }, processFilter, ArtifactType_Logs));
        }
        public async Task TestCounterEventPipeline()
        {
            var    expectedCounters = new[] { "cpu-usage", "working-set" };
            string expectedProvider = "System.Runtime";

            IDictionary <string, IEnumerable <string> > expectedMap = new Dictionary <string, IEnumerable <string> >();

            expectedMap.Add(expectedProvider, expectedCounters);

            var foundExpectedCountersSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

            var logger = new TestMetricsLogger(expectedMap, foundExpectedCountersSource);

            await using (var testExecution = StartTraceeProcess("CounterRemoteTest"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                var client = new DiagnosticsClient(testExecution.TestRunner.Pid);

                await using EventCounterPipeline pipeline = new EventCounterPipeline(client, new EventPipeCounterPipelineSettings
                {
                    Duration      = Timeout.InfiniteTimeSpan,
                    CounterGroups = new[]
                    {
                        new EventPipeCounterGroup
                        {
                            ProviderName = expectedProvider,
                            CounterNames = expectedCounters
                        }
                    },
                    CounterIntervalSeconds = 1
                }, new[] { logger });

                await PipelineTestUtilities.ExecutePipelineWithDebugee(
                    _output,
                    pipeline,
                    testExecution,
                    foundExpectedCountersSource);
            }

            Assert.True(logger.Metrics.Any());

            var actualMetrics = logger.Metrics.Select(m => m.Name).OrderBy(m => m);

            Assert.Equal(expectedCounters, actualMetrics);
            Assert.True(logger.Metrics.All(m => string.Equals(m.Provider, expectedProvider)));
        }
Example #12
0
        private async void LoadPackage(IPackage package, string packagePath, string packageSource, PackageType packageType)
        {
            DisposeViewModel();

            if (package != null)
            {
                if (!HasLoadedContent <PackageViewer>())
                {
                    var packageViewer = new PackageViewer(SettingsManager, UIServices, PackageChooser);
                    var binding       = new Binding
                    {
                        Converter     = new NullToVisibilityConverter(),
                        FallbackValue = Visibility.Collapsed
                    };
                    packageViewer.SetBinding(VisibilityProperty, binding);

                    MainContentContainer.Children.Add(packageViewer);

#if !HAS_UNO
                    // HACK HACK: set the Export of IPackageMetadataEditor here
                    EditorService = packageViewer.PackageMetadataEditor;
#endif
                }

                try
                {
                    var packageViewModel = await PackageViewModelFactory.CreateViewModel(package, packagePath, packageSource);

                    packageViewModel.PropertyChanged += OnPackageViewModelPropertyChanged;

                    DataContext = packageViewModel;
                    if (!string.IsNullOrEmpty(packageSource))
                    {
                        _mruManager.NotifyFileAdded(package, packageSource, packageType);
                    }
                }
                catch (Exception e)
                {
                    if (!(e is ArgumentException))
                    {
                        DiagnosticsClient.TrackException(e);
                    }
                    Console.WriteLine(e);
                    UIServices.Show($"Error loading package\n{e.Message}", MessageLevel.Error);
                }
            }
        }
        private async void OnPackageDownloadRequested(object sender, EventArgs e)
        {
            DiagnosticsClient.TrackEvent("PackageChooserService_OnPackageDownloadRequested");

            var vm          = (PackageChooserViewModel)sender;
            var repository  = vm.ActiveRepository;
            var packageInfo = vm.SelectedPackage;

            if (packageInfo != null && repository != null)
            {
                var          packageName = packageInfo.Id + "." + packageInfo.Version + NuGetPe.Constants.PackageExtension;
                var          title       = "Save " + packageName;
                const string filter      = "NuGet package file (*.nupkg)|*.nupkg|NuGet Symbols package file (*.snupkg)|*.snupkg|All files (*.*)|*.*";

                var accepted = UIServices.OpenSaveFileDialog(
                    title,
                    packageName,
                    null,
                    filter,
                    overwritePrompt: true,
                    selectedFilePath: out var selectedFilePath,
                    selectedFilterIndex: out var selectedIndex);

                if (accepted)
                {
                    if (selectedIndex == 1 &&
                        !selectedFilePath.EndsWith(NuGetPe.Constants.PackageExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        selectedFilePath += NuGetPe.Constants.PackageExtension;
                    }
                    else if (selectedIndex == 2 &&
                             !selectedFilePath.EndsWith(NuGetPe.Constants.SymbolPackageExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        selectedFilePath += NuGetPe.Constants.SymbolPackageExtension;
                    }

                    try
                    {
                        await PackageDownloader.Download(selectedFilePath, repository, packageInfo.Identity);
                    }
                    catch (Exception ex)
                    {
                        UIServices.Show(ex.Message, MessageLevel.Error);
                    }
                }
            }
        }
 private void PopulatePackages()
 {
     if (_systemPackages.Count < 1)
     {
         foreach (var item in ShellViewModel._cachedListOfPackages)
         {
             if (item.IsFramework == false)
             {
                 if (item.SignatureKind == "None")
                 {
                     _developerPackages.Add(new PackageInfoViewModel(item));
                 }
                 if (item.SignatureKind == "Developer")
                 {
                     _sideloadedPackages.Add(new PackageInfoViewModel(item));
                 }
                 if (item.SignatureKind == "Store")
                 {
                     _storePackages.Add(new PackageInfoViewModel(item));
                 }
                 if (item.SignatureKind == "System")
                 {
                     _systemPackages.Add(new PackageInfoViewModel(item));
                 }
                 if (item.SignatureKind == "Enterprise")
                 {
                     _enterprisePackages.Add(new PackageInfoViewModel(item));
                 }
             }
             else if (item.IsFramework == true)
             {
                 _frameworkPackages.Add(new PackageInfoViewModel(item));
             }
             else
             {
                 DiagnosticsClient.TrackTrace("App not categorized: " + item.PFN);
                 System.Diagnostics.Debug.WriteLine("skipping: " + item.PFN);
             }
         }
         base.OnPropertyChanged("NumStorePackages");
         base.OnPropertyChanged("NumSideloadedPackages");
         base.OnPropertyChanged("NumDeveloperPackages");
         base.OnPropertyChanged("NumFrameworkPackages");
         base.OnPropertyChanged("NumEnterprisePackages");
         base.OnPropertyChanged("NumSystemPackages");
     }
 }
Example #15
0
        public object GetView(IPackageContent selectedFile, IReadOnlyList <IPackageContent> peerFiles)
        {
            DiagnosticsClient.TrackEvent("PdbFileViewer");

            AssemblyDebugDataViewModel?data = null;

            // Get the PE file, exe or dll that matches
            var pe = peerFiles.FirstOrDefault(pc => ".dll".Equals(Path.GetExtension(pc.Name), StringComparison.OrdinalIgnoreCase) ||
                                              ".exe".Equals(Path.GetExtension(pc.Name), StringComparison.OrdinalIgnoreCase) ||
                                              ".winmd".Equals(Path.GetExtension(pc.Name), StringComparison.OrdinalIgnoreCase));

#pragma warning disable CA2000 // Dispose objects before losing scope -- ReadDebugData will dispose
            Stream?peStream = null;

            if (pe != null) // we have a matching file
            {
                peStream = StreamUtility.MakeSeekable(pe.GetStream(), true);
            }


            // This might throw an exception because we don't know if it's a full PDB or portable
            // Try anyway in case it succeeds as a ppdb
            try
            {
                var stream = StreamUtility.MakeSeekable(selectedFile.GetStream(), true);
                data = new AssemblyDebugDataViewModel(AssemblyMetadataReader.ReadDebugData(peStream, stream));


                return(new ScrollViewer
                {
                    HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
                    VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
                    Content = new Controls.PdbFileViewer
                    {
                        DataContext = data
                    }
                });
            }
            catch (ArgumentNullException)
            {
            }
#pragma warning restore CA2000 // Dispose objects before losing scope
            return(new TextBlock()
            {
                Text = "Full PDB files requires the EXE or DLL to be alongside."
            });
        }
        public async Task TestTraceStopAsync()
        {
            Stream eventStream = null;

            await using (var testExecution = StartTraceeProcess("TraceStopTest"))
            {
                //TestRunner should account for start delay to make sure that the diagnostic pipe is available.

                var client   = new DiagnosticsClient(testExecution.TestRunner.Pid);
                var settings = new EventTracePipelineSettings()
                {
                    Duration      = Timeout.InfiniteTimeSpan,
                    Configuration = new CpuProfileConfiguration()
                };

                var foundProviderSource = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

                await using var pipeline = new EventTracePipeline(client, settings, async(s, token) =>
                {
                    eventStream = s;

                    using var eventSource = new EventPipeEventSource(s);

                    // Dispose event source when cancelled.
                    using var _ = token.Register(() => eventSource.Dispose());

                    eventSource.Dynamic.All += (TraceEvent obj) =>
                    {
                        if (string.Equals(obj.ProviderName, MonitoringSourceConfiguration.SampleProfilerProviderName, StringComparison.OrdinalIgnoreCase))
                        {
                            foundProviderSource.TrySetResult(null);
                        }
                    };

                    await Task.Run(() => Assert.True(eventSource.Process()), token);
                });

                await PipelineTestUtilities.ExecutePipelineWithDebugee(
                    _output,
                    pipeline,
                    testExecution,
                    foundProviderSource);
            }

            //Validate that the stream is only valid for the lifetime of the callback in the trace pipeline.
            Assert.Throws <ObjectDisposedException>(() => eventStream.Read(new byte[4], 0, 4));
        }
        public FilteredEndpointInfoSource(IOptions <DiagnosticPortOptions> portOptions)
        {
            _portOptions = portOptions.Value;

            DiagnosticPortConnectionMode connectionMode = _portOptions.ConnectionMode.GetValueOrDefault(DiagnosticPortOptionsDefaults.ConnectionMode);

            switch (connectionMode)
            {
            case DiagnosticPortConnectionMode.Connect:
                _source = new ClientEndpointInfoSource();
                break;

            case DiagnosticPortConnectionMode.Listen:
                _source = new ServerEndpointInfoSource(_portOptions.EndpointName);
                break;

            default:
                throw new InvalidOperationException($"Unhandled connection mode: {connectionMode}");
            }

            // Filter out the current process based on the connection mode.
            if (RuntimeInfo.IsDiagnosticsEnabled)
            {
                int pid = Process.GetCurrentProcess().Id;

                // Regardless of connection mode, can use the runtime instance cookie to filter self out.
                try
                {
                    var  client = new DiagnosticsClient(pid);
                    Guid runtimeInstanceCookie = client.GetProcessInfo().RuntimeInstanceCookie;
                    if (Guid.Empty != runtimeInstanceCookie)
                    {
                        _runtimeInstanceCookieToFilterOut = runtimeInstanceCookie;
                    }
                }
                catch (Exception)
                {
                }

                // If connecting to runtime instances, filter self out. In listening mode, it's likely
                // that multiple processes have the same PID in multi-container scenarios.
                if (DiagnosticPortConnectionMode.Connect == connectionMode)
                {
                    _processIdToFilterOut = pid;
                }
            }
        }
Example #18
0
        public void SetStartupProfiler(Guid profilerGuid, string profilerPath)
        {
            MethodInfo startupProfiler = typeof(DiagnosticsClient).GetMethod("SetStartupProfiler", BindingFlags.Public);

            if (startupProfiler != null)
            {
                throw new Exception("You updated DiagnosticsClient to a version that supports SetStartupProfiler, please remove this nonsense and use the real code.");
            }

            DiagnosticsClient client = new DiagnosticsClient(_processId);

            Console.WriteLine("Sending startup profiler message.");
            // Send StartupProfiler command
            object ipcMessage = MakeStartupProfilerMessage(profilerGuid, profilerPath);

            SendMessage(_processId, ipcMessage);
        }
        public Task <Stream> ProcessEvents(DiagnosticsClient client, TimeSpan duration, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            lock (_lock)
            {
                if (_disposed)
                {
                    throw new ObjectDisposedException(nameof(DiagnosticsMonitor));
                }

                if (_currentTask != null)
                {
                    throw new InvalidOperationException("Only one stream processing is allowed");
                }

                EventPipeSession session = null;
                try
                {
                    session = client.StartEventPipeSession(_sourceConfig.GetProviders(), _sourceConfig.RequestRundown, _sourceConfig.BufferSizeInMB);
                }
                catch (EndOfStreamException e)
                {
                    throw new InvalidOperationException("End of stream", e);
                }
                catch (Exception ex) when(!(ex is OperationCanceledException))
                {
                    throw new InvalidOperationException("Failed to start the event pipe session", ex);
                }

                _currentTask = Task.Run(async() =>
                {
                    using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                    linkedSource.CancelAfter(duration);
                    using var _ = linkedSource.Token.Register(() => _stopProcessingSource.TrySetResult(null));

                    // Use TaskCompletionSource instead of Task.Delay with cancellation to avoid
                    // using exceptions for normal termination of event stream.
                    await _stopProcessingSource.Task.ConfigureAwait(false);

                    StopSession(session);
                });

                return(Task.FromResult(session.EventStream));
            }
        }
Example #20
0
        static void ThreadProc(Object arg)
        {
            Process eventWritingProc = (Process)arg;

            eventCounts[cur_core_count] = 0;
            DiagnosticsClient    client  = new DiagnosticsClient(eventWritingProc.Id);
            EventPipeSession     session = client.StartEventPipeSession(new EventPipeProvider("MySource", EventLevel.Verbose, (long)-1, null));
            EventPipeEventSource source  = new EventPipeEventSource(session.EventStream);

            source.Dynamic.All += (TraceEvent data) => {
                if (data.EventName == "FireSmallEvent")
                {
                    eventCounts[cur_core_count] += 1;
                }
            };
            source.Process();
        }
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
        public PackageChooserDialog(ISettingsManager settings, PackageChooserViewModel viewModel)
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
        {
            InitializeComponent();

            _settings = settings;

            Debug.Assert(viewModel != null);

            _viewModel = viewModel;
            _viewModel.LoadPackagesCompleted += OnLoadPackagesCompleted;
            _viewModel.OpenPackageRequested  += OnOpenPackageRequested;

            DataContext = _viewModel;

            DiagnosticsClient.TrackPageView(nameof(PackageChooserDialog));
        }
Example #22
0
        private static void Main()
        {
            if (Environment.OSVersion.Version.Major >= 6)
            {
                SetProcessDPIAware();
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // TODO: VSR - removed this because it was failing after switching to x64
            // ThemeModule.Load();
            // Application.ApplicationExit += (s, e) => ThemeModule.Unload();

            HighDpiMouseCursors.Enable();

            try
            {
                DiagnosticsClient.Initialize(VsrInfo.IsDirty);

                if (!Debugger.IsAttached)
                {
                    AppDomain.CurrentDomain.UnhandledException += (s, e) => ReportBug((Exception)e.ExceptionObject);
                    Application.ThreadException += (s, e) => ReportBug(e.Exception);
                }
            }
            catch (TypeInitializationException tie)
            {
                // is this exception caused by the configuration?
                if (tie.InnerException != null &&
                    tie.InnerException.GetType()
                    .IsSubclassOf(typeof(ConfigurationException)))
                {
                    HandleConfigurationException((ConfigurationException)tie.InnerException);
                }
            }

            // This is done here so these values can be used in the GitGui project but this project is the authority of the values.
            UserEnvironmentInformation.Initialise(VsrInfo.Sha, VsrInfo.IsDirty);
            AppTitleGenerator.Initialise(VsrInfo.Sha, VsrInfo.Branch);

            // NOTE we perform the rest of the application's startup in another method to defer
            // the JIT processing more types than required to configure NBug.
            // In this way, there's more chance we can handle startup exceptions correctly.
            RunApplication();
        }
Example #23
0
        public void ViewManifest(PackageInfoViewModel package)
        {
            var manifestPath     = Path.Combine(package.PackageInfo.InstallLocation, "AppxManifest.xml");
            Uri manifestUri      = new Uri(manifestPath, UriKind.Absolute);
            ProcessStartInfo psi = new ProcessStartInfo()
            {
                UseShellExecute = true,
                FileName        = manifestUri.AbsoluteUri
            };

            Process.Start(psi);
            DiagnosticsClient.TrackEvent("ViewManifest",
                                         new Dictionary <string, string> {
                { "ManifestToOpen", manifestPath }
            },
                                         null);
        }
Example #24
0
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            InitializeLogging();

            this.InitializeComponent();
            this.Suspending += OnSuspending;

            DiagnosticsClient.Initialize(
#if __WASM__
                new NuGetPackageExplorer.Services.AppInsightsJsTelemetryService(
                    new List <ITelemetryServiceInitializer> {
                new NuGetPe.Utility.AppVersionTelemetryInitializer(),
                new NuGetPe.Utility.EnvironmentTelemetryInitializer()
            })
#endif
                );
        }
Example #25
0
        public static void PrintProcessStatus()
        {
            var processes = DiagnosticsClient.GetPublishedProcesses()
                            .Select(Process.GetProcessById)
                            .Where(process => process != null);

            foreach (var process in processes)
            {
                Console.WriteLine($"ProcessId: {process.Id}");
                Console.WriteLine($"ProcessName: {process.ProcessName}");
                Console.WriteLine($"StartTime: {process.StartTime}");
                Console.WriteLine($"Threads: {process.Threads.Count}");

                Console.WriteLine();
                Console.WriteLine();
            }
        }
Example #26
0
        public CpuEventPipeEventSource(int processId)
        {
            providers = new List <EventPipeProvider>()
            {
                new EventPipeProvider(
                    "System.Runtime",
                    EventLevel.Informational,
                    (long)ClrTraceEventParser.Keywords.None,
                    new Dictionary <string, string>()
                {
                    { "EventCounterIntervalSec", "1" }
                }
                    )
            };

            client = new DiagnosticsClient(processId);
        }
Example #27
0
        private void PackageCommandExecute(LazyPackageCommand packageCommand)
        {
            var package = PackageHelper.BuildPackage(PackageMetadata, GetFiles());

            try
            {
                packageCommand.Value.Execute(package, PackagePath);
            }
            catch (Exception ex)
            {
                DiagnosticsClient.Notify(ex);
                UIServices.Show("The command failed with this error message:" +
                                Environment.NewLine +
                                Environment.NewLine +
                                ex.Message, MessageLevel.Error);
            }
        }
Example #28
0
        /// <summary>
        /// This uses EventPipeEventSource's Stream constructor to parse the events real-time.
        /// It then returns the number of events read.
        /// </summary>
        static void UseEPES(int pid)
        {
            int eventsRead            = 0;
            DiagnosticsClient client  = new DiagnosticsClient(pid);
            EventPipeSession  session = client.StartEventPipeSession(new EventPipeProvider("MySource", EventLevel.Verbose));

            Console.WriteLine("session open");
            EventPipeEventSource epes = new EventPipeEventSource(session.EventStream);

            epes.Dynamic.All += (TraceEvent data) => {
                eventsRead += 1;
            };
            epes.Process();
            Console.WriteLine("Used realtime.");
            Console.WriteLine("Read total: " + eventsRead.ToString());
            Console.WriteLine("Dropped total: " + epes.EventsLost.ToString());
        }
 public ProcessInfo(
     DiagnosticsClient client,
     Guid runtimeInstanceIdentifier,
     int processId,
     string processName,
     string commandLine,
     string operatingSystem,
     string processArchitecture)
 {
     Client                = client;
     CommandLine           = commandLine;
     ProcessId             = processId;
     ProcessName           = processName;
     RuntimeInstanceCookie = runtimeInstanceIdentifier;
     OperatingSystem       = operatingSystem;
     ProcessArchitecture   = processArchitecture;
 }
Example #30
0
        public void Handle(HostSignal signal, DiagnoserActionParameters parameters)
        {
            if (signal != HostSignal.BeforeAnythingElse)
            {
                return;
            }

            var diagnosticsClient = new DiagnosticsClient(parameters.Process.Id);

            EventPipeSession session = diagnosticsClient.StartEventPipeSession(eventPipeProviders, true);

            var fileName = ArtifactFileNameHelper.GetTraceFilePath(parameters, DateTime.Now, "nettrace").EnsureFolderExists();

            benchmarkToTraceFile[parameters.BenchmarkCase] = fileName;

            collectingTask = Task.Run(() => CopyEventStreamToFile(session, fileName, parameters.Config.GetCompositeLogger()));
        }