From b327b9a81a94f0eeafd906e65fc2026e659b9625 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 25 Aug 2026 09:56:23 -0700 Subject: [PATCH 1/6] Modernize next System.Diagnostics snippets Update the second batch of 60 System.Diagnostics C# samples to current syntax and consolidate their net10.0 snippet projects while preserving the documented APIs and runtime behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 81f0fa5e-3bcf-4d3b-b652-f7dc76e7ae03 --- .../EventLog/Overview/Project.csproj | 2 +- .../EventLog/Overview/source.cs | 44 ++-- .../EventLog/Source/Project.csproj | 2 +- .../EventLog/Source/source.cs | 47 ++--- .../EventLog/WriteEntry/Program.cs | 14 ++ .../EventLog/WriteEntry/Project.csproj | 3 +- .../WriteEntry/eventlog_writeentry_1_3.cs | 37 ++-- .../WriteEntry/eventlog_writeentry_4.cs | 72 +++---- .../WriteEntry/eventlog_writeentry_5.cs | 94 ++++----- .../EventLog/WriteEntry/source.cs | 16 +- .../EventLog/WriteEntry/source1.cs | 11 +- .../EventLog/WriteEntry/source2.cs | 12 +- .../EventLogEntry/Overview/Project.csproj | 7 +- .../Overview/eventlogentry_source.cs | 70 +++---- .../Count/Project.csproj | 7 +- .../Count/eventlogentry_item.cs | 107 +++++----- .../Overview/Project.csproj | 7 +- .../Overview/eventlogentry_copyto.cs | 120 +++++------ .../EventLogEntryType/Overview/Project.csproj | 7 +- .../Overview/eventlogentrytype_6.cs | 155 +++++++------- .../Overview/Project.csproj | 4 +- .../EventLogTraceListener/Overview/source.cs | 2 +- .../Overview/Project.csproj | 7 +- .../Overview/source.cs | 192 ++++++++---------- .../FileVersionInfo/Comments/Project.csproj | 9 +- .../FileVersionInfo/Comments/source.cs | 21 +- .../CompanyName/Project.csproj | 9 +- .../FileVersionInfo/CompanyName/source.cs | 22 +- .../FileBuildPart/Project.csproj | 9 +- .../FileVersionInfo/FileBuildPart/source.cs | 24 +-- .../FileDescription/Project.csproj | 9 +- .../FileVersionInfo/FileDescription/source.cs | 24 +-- .../FileMajorPart/Project.csproj | 9 +- .../FileVersionInfo/FileMajorPart/source.cs | 18 +- .../FileMinorPart/Project.csproj | 9 +- .../FileVersionInfo/FileMinorPart/source.cs | 24 +-- .../FileVersionInfo/FileName/Project.csproj | 9 +- .../FileVersionInfo/FileName/source.cs | 24 +-- .../FilePrivatePart/Project.csproj | 9 +- .../FileVersionInfo/FilePrivatePart/source.cs | 24 +-- .../InternalName/Project.csproj | 9 +- .../FileVersionInfo/InternalName/source.cs | 24 +-- .../FileVersionInfo/IsDebug/Project.csproj | 9 +- .../FileVersionInfo/IsDebug/source.cs | 25 +-- .../FileVersionInfo/IsPatched/Project.csproj | 9 +- .../FileVersionInfo/IsPatched/source.cs | 24 +-- .../IsPreRelease/Project.csproj | 9 +- .../FileVersionInfo/IsPreRelease/source.cs | 24 +-- .../IsPrivateBuild/Project.csproj | 9 +- .../FileVersionInfo/IsPrivateBuild/source.cs | 24 +-- .../IsSpecialBuild/Project.csproj | 9 +- .../FileVersionInfo/IsSpecialBuild/source.cs | 24 +-- .../LegalCopyright/Project.csproj | 9 +- .../FileVersionInfo/LegalCopyright/source.cs | 24 +-- .../LegalTrademarks/Project.csproj | 9 +- .../FileVersionInfo/LegalTrademarks/source.cs | 24 +-- .../OriginalFilename/Project.csproj | 9 +- .../OriginalFilename/source.cs | 24 +-- .../FileVersionInfo/Overview/Project.csproj | 6 +- .../FileVersionInfo/Overview/source.cs | 19 +- .../PrivateBuild/Project.csproj | 9 +- .../FileVersionInfo/PrivateBuild/source.cs | 24 +-- .../ProductBuildPart/Project.csproj | 9 +- .../ProductBuildPart/source.cs | 24 +-- .../ProductMajorPart/Project.csproj | 9 +- .../ProductMajorPart/source.cs | 24 +-- .../ProductMinorPart/Project.csproj | 9 +- .../ProductMinorPart/source.cs | 24 +-- .../ProductName/Project.csproj | 9 +- .../FileVersionInfo/ProductName/source.cs | 24 +-- .../ProductPrivatePart/Project.csproj | 9 +- .../ProductPrivatePart/source.cs | 24 +-- .../ProductVersion/Project.csproj | 9 +- .../FileVersionInfo/ProductVersion/source.cs | 24 +-- .../SpecialBuild/Project.csproj | 9 +- .../FileVersionInfo/SpecialBuild/source.cs | 24 +-- .../FileVersionInfo/ToString/Project.csproj | 9 +- .../FileVersionInfo/ToString/source.cs | 24 +-- .../InstanceData/Overview/Project.csproj | 5 +- .../InstanceData/Overview/instdatacopyto.cs | 54 ++--- .../Contains/Project.csproj | 5 +- .../Contains/instdatacolitemcontains.cs | 59 +++--- .../Overview/Project.csproj | 5 +- .../Overview/instdatakeysvalues.cs | 46 ++--- .../Contains/Project.csproj | 5 +- .../Contains/instdatacolcolitermcontains.cs | 62 +++--- .../PerformanceCounter/.ctor/Project.csproj | 5 +- .../PerformanceCounter/.ctor/perfcounter.cs | 100 ++------- .../NextValue/Project.csproj | 5 +- .../NextValue/elapsedtime.cs | 125 ++++++------ .../.ctor/Program.cs | 3 + .../.ctor/Project.csproj | 5 +- .../.ctor/perfCounterCatDelete.cs | 19 +- .../.ctor/perfCounterCatProps.cs | 32 ++- .../.ctor/perfcountercatctor.cs | 48 ++--- .../CounterExists/Program.cs | 5 + .../CounterExists/Project.csproj | 5 +- .../CounterExists/percounterexists.cs | 21 +- .../CounterExists/perfcountercatobjexists.cs | 49 ++--- .../perfcountercatstatcounterexists.cs | 46 ++--- .../perfcountercatstatinstexists.cs | 54 ++--- .../CounterExists/perfcounterobjinstexists.cs | 57 ++---- .../Create/Project.csproj | 5 +- .../PerformanceCounterCategory/Create/ccd.cs | 45 ++-- .../Create/program.cs | 163 ++++++++------- .../GetCategories/Program.cs | 4 + .../GetCategories/Project.csproj | 5 +- .../GetCategories/perfcountercatgetcount.cs | 76 +++---- .../GetCategories/perfcountercatgetinst.cs | 73 +++---- .../GetCategories/perfcountergetcat.cs | 47 ++--- 110 files changed, 1265 insertions(+), 1885 deletions(-) create mode 100644 snippets/csharp/System.Diagnostics/EventLog/WriteEntry/Program.cs create mode 100644 snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/Program.cs create mode 100644 snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/Program.cs create mode 100644 snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/Program.cs diff --git a/snippets/csharp/System.Diagnostics/EventLog/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/EventLog/Overview/Project.csproj index 7d669796595..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLog/Overview/Project.csproj @@ -8,5 +8,5 @@ - + diff --git a/snippets/csharp/System.Diagnostics/EventLog/Overview/source.cs b/snippets/csharp/System.Diagnostics/EventLog/Overview/source.cs index 76722e90f95..d757f3f39b1 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Overview/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/Overview/source.cs @@ -1,33 +1,25 @@ // using System; using System.Diagnostics; -using System.Threading; -class MySample{ - - public static void Main(){ - - // Create the source, if it does not already exist. - if(!EventLog.SourceExists("MySource")) - { - //An event log source should not be created and immediately used. - //There is a latency time to enable the source, it should be created - //prior to executing the application that uses the source. - //Execute this sample a second time to use the new source. - EventLog.CreateEventSource("MySource", "MyNewLog"); - Console.WriteLine("CreatedEventSource"); - Console.WriteLine("Exiting, execute the application a second time to use the source."); - // The source is created. Exit the application to allow it to be registered. - return; - } - - // Create an EventLog instance and assign its source. - EventLog myLog = new EventLog(); - myLog.Source = "MySource"; - - // Write an informational entry to the event log. - myLog.WriteEntry("Writing to event log."); - } +// Create the source if it doesn't already exist. +if (!EventLog.SourceExists("MySource")) +{ + // An event log source shouldn't be created and immediately used. + // The source takes time to become enabled. + // Create it before executing the application that uses it. + // Execute this sample a second time to use the new source. + EventLog.CreateEventSource("MySource", "MyNewLog"); + Console.WriteLine("CreatedEventSource"); + Console.WriteLine("Exiting, execute the application a second time to use the source."); + // The source is created. Exit the application to allow it to be registered. + return; } +// Create an EventLog instance and assign its source. +using EventLog myLog = new(); +myLog.Source = "MySource"; + +// Write an informational entry to the event log. +myLog.WriteEntry("Writing to event log."); // diff --git a/snippets/csharp/System.Diagnostics/EventLog/Source/Project.csproj b/snippets/csharp/System.Diagnostics/EventLog/Source/Project.csproj index 7d669796595..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Source/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLog/Source/Project.csproj @@ -8,5 +8,5 @@ - + diff --git a/snippets/csharp/System.Diagnostics/EventLog/Source/source.cs b/snippets/csharp/System.Diagnostics/EventLog/Source/source.cs index 0d977af7933..48518870434 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Source/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/Source/source.cs @@ -1,35 +1,26 @@ // using System; using System.Diagnostics; -using System.Threading; -class MySample{ - - public static void Main(){ - - // Create the source, if it does not already exist. - if(!EventLog.SourceExists("MySource")) - { - // An event log source should not be created and immediately used. - // There is a latency time to enable the source, it should be created - // prior to executing the application that uses the source. - // Execute this sample a second time to use the new source. - EventLog.CreateEventSource("MySource", "MyNewLog"); - Console.WriteLine("CreatingEventSource"); - Console.WriteLine("Exiting, execute the application a second time to use the source."); - // The source is created. Exit the application to allow it to be registered. - return; - } - - // Create an EventLog instance and assign its source. - EventLog myLog = new EventLog(); - myLog.Source = "MySource"; - - // Write an informational entry to the event log. - myLog.WriteEntry("Writing to event log."); - - Console.WriteLine("Message written to event log."); - } +// Create the source if it doesn't already exist. +if (!EventLog.SourceExists("MySource")) +{ + // An event log source shouldn't be created and immediately used. + // The source takes time to become enabled. + // Create it before executing the application that uses it. + // Execute this sample a second time to use the new source. + EventLog.CreateEventSource("MySource", "MyNewLog"); + Console.WriteLine("CreatingEventSource"); + Console.WriteLine("Exiting, execute the application a second time to use the source."); + // The source is created. Exit the application to allow it to be registered. + return; } +// Create an EventLog instance and assign its source. +using EventLog myLog = new(); +myLog.Source = "MySource"; + +// Write an informational entry to the event log. +myLog.WriteEntry("Writing to event log."); +Console.WriteLine("Message written to event log."); // diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/Program.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/Program.cs new file mode 100644 index 00000000000..458034bbdf9 --- /dev/null +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/Program.cs @@ -0,0 +1,14 @@ +using System.Diagnostics; + +bool sourceExists = EventLog.SourceExists("MySource"); +MySample.Run(); +if (!sourceExists) +{ + return; +} + +MyEventLog.Run(); +EventLog_WriteEntry_4.Run(); +EventLog_WriteEntry_5.Run(); +MySample1.Run(); +MySample2.Run(); diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/Project.csproj b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/Project.csproj index 2684d9cb806..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/Project.csproj @@ -3,11 +3,10 @@ Exe net10.0 - MySample - + diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_1_3.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_1_3.cs index a9653e02fee..84545b2adee 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_1_3.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_1_3.cs @@ -13,41 +13,52 @@ class MyEventLog { - public static void Main() + public static void Run() { - // int myEventID = 20; short myCategory = 10; // Write an informational entry to the event log. Console.WriteLine("Write from first source "); - EventLog.WriteEntry("FirstSource", "Writing warning to event log.", - EventLogEntryType.Information, myEventID, myCategory); + EventLog.WriteEntry( + "FirstSource", + "Writing warning to event log.", + EventLogEntryType.Information, + myEventID, + myCategory); // // - //Create a byte array for binary data to associate with the entry. + // Create a byte array for binary data to associate with the entry. byte[] myByte = new byte[10]; - //Populate the byte array with simulated data. - for (int i = 0; i < 10; i++) + // Populate the byte array with simulated data. + for (int i = 0; i < myByte.Length; i++) { myByte[i] = (byte)(i % 2); } // Write an entry to the event log that includes associated binary data. Console.WriteLine("Write from second source "); - EventLog.WriteEntry("SecondSource", "Writing warning to event log.", - EventLogEntryType.Error, myEventID, myCategory, myByte); + EventLog.WriteEntry( + "SecondSource", + "Writing warning to event log.", + EventLogEntryType.Error, + myEventID, + myCategory, + myByte); // // // Create an EventLog instance and assign its source. - EventLog myLog = new EventLog(); + using EventLog myLog = new(); myLog.Source = "ThirdSource"; - // Write an informational entry to the event log. + // Write a warning entry to the event log. Console.WriteLine("Write from third source "); - myLog.WriteEntry("Writing warning to event log.", - EventLogEntryType.Warning, myEventID, myCategory); + myLog.WriteEntry( + "Writing warning to event log.", + EventLogEntryType.Warning, + myEventID, + myCategory); // } } diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_4.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_4.cs index ff0f411612d..5ca15b48595 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_4.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_4.cs @@ -9,41 +9,45 @@ The following sample demonstrates the using System; using System.Diagnostics; + class EventLog_WriteEntry_4 { - public static void Main() - { - try - { -// - // Create the source, if it does not already exist. - if(!EventLog.SourceExists("MySource")) - { - // An event log source should not be created and immediately used. - // There is a latency time to enable the source, it should be created - // prior to executing the application that uses the source. - // Execute this sample a second time to use the new source. - EventLog.CreateEventSource("MySource", "myNewLog"); - Console.WriteLine("Creating EventSource"); - Console.WriteLine("Exiting, execute the application a second time to use the source."); - // The source is created. Exit the application to allow it to be registered. - return; - } + public static void Run() + { + try + { + // + // Create the source if it doesn't already exist. + if (!EventLog.SourceExists("MySource")) + { + // An event log source shouldn't be created and immediately used. + // The source takes time to become enabled. + // Create it before executing the application that uses it. + // Execute this sample a second time to use the new source. + EventLog.CreateEventSource("MySource", "myNewLog"); + Console.WriteLine("Creating EventSource"); + Console.WriteLine("Exiting, execute the application a second time to use the source."); + // The source is created. Exit the application to allow it to be registered. + return; + } - // Set the 'description' for the event. - string myMessage = "This is my event."; - EventLogEntryType myEventLogEntryType = EventLogEntryType.Warning; - int myApplicationEventId = 100; + // Set the description for the event. + string myMessage = "This is my event."; + EventLogEntryType myEventLogEntryType = EventLogEntryType.Warning; + int myApplicationEventId = 100; - // Write the entry in the event log. - Console.WriteLine("Writing to EventLog.. "); - EventLog.WriteEntry("MySource",myMessage, - myEventLogEntryType, myApplicationEventId); -// - } - catch(Exception e) - { - Console.WriteLine("Exception:{0}",e.Message); - } - } -} \ No newline at end of file + // Write the entry in the event log. + Console.WriteLine("Writing to EventLog.. "); + EventLog.WriteEntry( + "MySource", + myMessage, + myEventLogEntryType, + myApplicationEventId); + // + } + catch (Exception e) + { + Console.WriteLine($"Exception:{e.Message}"); + } + } +} diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_5.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_5.cs index 6dd60eff141..9cd8ee6825a 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_5.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_5.cs @@ -7,7 +7,7 @@ The following sample demonstrates the It creates the source "MySource" if the source does not already exist. It creates an 'EventLog' object and calls 'WriteEntry' passing the description, Log entry type, application specific identifier for the event, - application specific subcategory and data to be associated with the entry. + application specific subcategory and data to be associated with the entry. */ using System; @@ -15,54 +15,54 @@ application specific subcategory and data to be associated with the entry. class EventLog_WriteEntry_5 { - public static void Main() - { - try - { -// - // Create the source, if it does not already exist. - string myLogName = "myNewLog"; - if(!EventLog.SourceExists("MySource")) - { - // An event log source should not be created and immediately used. - // There is a latency time to enable the source, it should be created - // prior to executing the application that uses the source. - // Execute this sample a second time to use the new source. - EventLog.CreateEventSource("MySource", myLogName); - Console.WriteLine("Created EventSource"); - Console.WriteLine("Exiting, execute the application a second time to use the source."); - return; - } - else + public static void Run() + { + try + { + // + // Create the source if it doesn't already exist. + string myLogName = "myNewLog"; + if (!EventLog.SourceExists("MySource")) { - myLogName = EventLog.LogNameFromSourceName("MySource","."); + // An event log source shouldn't be created and immediately used. + // The source takes time to become enabled. + // Create it before executing the application that uses it. + // Execute this sample a second time to use the new source. + EventLog.CreateEventSource("MySource", myLogName); + Console.WriteLine("Created EventSource"); + Console.WriteLine("Exiting, execute the application a second time to use the source."); + return; } - // Create an EventLog and assign source. - EventLog myEventLog = new EventLog(); - myEventLog.Source = "MySource"; - myEventLog.Log = myLogName; - // Set the 'description' for the event. - string myMessage = "This is my event."; - EventLogEntryType myEventLogEntryType = EventLogEntryType.Warning; - int myApplicatinEventId = 1100; - short myApplicatinCategoryId = 1; + myLogName = EventLog.LogNameFromSourceName("MySource", "."); - // Set the 'data' for the event. - byte[] myRawData = new byte[4]; - for(int i=0;i<4;i++) - { - myRawData[i]=1; - } - // Write the entry in the event log. - Console.WriteLine("Writing to EventLog.. "); - myEventLog.WriteEntry(myMessage,myEventLogEntryType, - myApplicatinEventId, myApplicatinCategoryId, myRawData); -// - } - catch(Exception e) - { - Console.WriteLine("Exception:{0}",e.Message); - } - } + // Create an EventLog and assign its source. + using EventLog myEventLog = new(); + myEventLog.Source = "MySource"; + myEventLog.Log = myLogName; + + // Set the description for the event. + string myMessage = "This is my event."; + EventLogEntryType myEventLogEntryType = EventLogEntryType.Warning; + int myApplicationEventId = 1100; + short myApplicationCategoryId = 1; + + // Set the data for the event. + byte[] myRawData = [1, 1, 1, 1]; + + // Write the entry in the event log. + Console.WriteLine("Writing to EventLog.. "); + myEventLog.WriteEntry( + myMessage, + myEventLogEntryType, + myApplicationEventId, + myApplicationCategoryId, + myRawData); + // + } + catch (Exception e) + { + Console.WriteLine($"Exception:{e.Message}"); + } + } } diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source.cs index 8813e2c3007..0ebbe774bbb 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source.cs @@ -1,25 +1,22 @@ // using System; using System.Diagnostics; -using System.Threading; class MySample { - - public static void Main() + public static void Run() { - - // Create the source, if it does not already exist. + // Create the source if it doesn't already exist. if (!EventLog.SourceExists("MySource")) { - // An event log source should not be created and immediately used. - // There is a latency time to enable the source, it should be created - // prior to executing the application that uses the source. + // An event log source shouldn't be created and immediately used. + // The source takes time to become enabled. + // Create it before executing the application that uses it. // Execute this sample a second time to use the new source. EventLog.CreateEventSource("MySource", "myNewLog"); Console.WriteLine("CreatingEventSource"); Console.WriteLine("Exiting, execute the application a second time to use the source."); - // The source is created. Exit the application to allow it to be registered. + // The source is created. Exit the application to allow it to be registered. return; } @@ -27,5 +24,4 @@ public static void Main() EventLog.WriteEntry("MySource", "Writing to event log."); } } - // diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source1.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source1.cs index e4006ffb9b2..c5e23666e65 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source1.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source1.cs @@ -1,21 +1,16 @@ // -using System; using System.Diagnostics; -using System.Threading; class MySample1 { - - public static void Main() + public static void Run() { - // Create an EventLog instance and assign its source. - EventLog myLog = new EventLog("MyNewLog"); + using EventLog myLog = new("MyNewLog"); myLog.Source = "MyNewLogSource"; - // Write an informational entry to the event log. + // Write a warning entry to the event log. myLog.WriteEntry("Writing warning to event log.", EventLogEntryType.Warning); } } - // diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source2.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source2.cs index 7c507b9d65b..881e549b372 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source2.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source2.cs @@ -1,19 +1,15 @@ // -using System; using System.Diagnostics; -using System.Threading; class MySample2 { - - public static void Main() + public static void Run() { - - // Write an informational entry to the event log. - EventLog.WriteEntry("MySource", + // Write a warning entry to the event log. + EventLog.WriteEntry( + "MySource", "Writing warning to event log.", EventLogEntryType.Warning); } } - // diff --git a/snippets/csharp/System.Diagnostics/EventLogEntry/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/EventLogEntry/Overview/Project.csproj index e17ba622dbc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntry/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLogEntry/Overview/Project.csproj @@ -1,13 +1,12 @@ - Library - net10.0-windows - true + Exe + net10.0 - + diff --git a/snippets/csharp/System.Diagnostics/EventLogEntry/Overview/eventlogentry_source.cs b/snippets/csharp/System.Diagnostics/EventLogEntry/Overview/eventlogentry_source.cs index 8d5403a7279..f6bfd95e8e0 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntry/Overview/eventlogentry_source.cs +++ b/snippets/csharp/System.Diagnostics/EventLogEntry/Overview/eventlogentry_source.cs @@ -6,52 +6,40 @@ The following example demonstrates the properties 'EntryType' and 'Source' of the class 'EventLogEntry'. A new instance of 'EventLog' class is created and is associated to existing System Log file of local machine. User selects the event type and the latest -entry in the log file of that type and it's source is displayed. +entry in the log file of that type and its source is displayed. */ // // using System; using System.Diagnostics; - class MyEventlogClass - { - public static void Main() - { - String myEventType=null; - // Associate the instance of 'EventLog' with local System Log. - EventLog myEventLog = new EventLog("System", "."); - Console.WriteLine("1:Error"); - Console.WriteLine("2:Information"); - Console.WriteLine("3:Warning"); - Console.WriteLine("Select the Event Type"); - int myOption=Convert.ToInt32(Console.ReadLine()); - switch(myOption) - { - case 1: myEventType="Error"; - break; - case 2: myEventType="Information"; - break; - case 3: myEventType="Warning"; - break; - default: break; - } - EventLogEntryCollection myLogEntryCollection=myEventLog.Entries; - int myCount =myLogEntryCollection.Count; - // Iterate through all 'EventLogEntry' instances in 'EventLog'. - for(int i=myCount-1;i>-1;i--) - { - EventLogEntry myLogEntry = myLogEntryCollection[i]; - // Select the entry having desired EventType. - if(myLogEntry.EntryType.ToString().Equals(myEventType)) - { - // Display Source of the event. - Console.WriteLine(myLogEntry.Source - +" was the source of last event of type " - +myLogEntry.EntryType); - return; - } - } - } - } +using EventLog myEventLog = new("System", "."); +Console.WriteLine("1:Error"); +Console.WriteLine("2:Information"); +Console.WriteLine("3:Warning"); +Console.WriteLine("Select the Event Type"); +int myOption = Convert.ToInt32(Console.ReadLine()); +EventLogEntryType? myEventType = myOption switch +{ + 1 => EventLogEntryType.Error, + 2 => EventLogEntryType.Information, + 3 => EventLogEntryType.Warning, + _ => null +}; + +EventLogEntryCollection myLogEntryCollection = myEventLog.Entries; +int myCount = myLogEntryCollection.Count; +// Iterate through all EventLogEntry instances in EventLog. +for (int i = myCount - 1; i > -1; i--) +{ + EventLogEntry myLogEntry = myLogEntryCollection[i]; + // Select the entry that has the desired EventType. + if (myLogEntry.EntryType == myEventType) + { + // Display the source of the event. + Console.WriteLine($"{myLogEntry.Source} was the source of last event of type {myLogEntry.EntryType}"); + return; + } +} // // diff --git a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/Project.csproj b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/Project.csproj index e17ba622dbc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/Project.csproj @@ -1,13 +1,12 @@ - Library - net10.0-windows - true + Exe + net10.0 - + diff --git a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/eventlogentry_item.cs b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/eventlogentry_item.cs index 26f44ac69bd..cf7ea5355a8 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/eventlogentry_item.cs +++ b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/eventlogentry_item.cs @@ -3,71 +3,60 @@ /* The following example demonstrates 'Item' and 'Count' properties of the - EventLogEntryCollection class. A new Source for eventlog 'MyNewLog' is created. - The program checks if a Event source exists. If the source already exists, it gets - the Log name associated with it otherwise, creates a new event source. - A new entry is created for 'MyNewLog'.Entries of 'MyNewLog' are obtained and - the count and the messages are displayed. - - */ + EventLogEntryCollection class. A new source for event log 'MyNewLog' is created. + The program checks whether an event source exists. If the source already exists, + it gets the log name associated with it. Otherwise, it creates a new event source. + A new entry is created for 'MyNewLog'. Entries of 'MyNewLog' are obtained, and + the count and messages are displayed. +*/ using System; -using System.Collections; using System.Diagnostics; -class EventLogEntryCollection_Item +try { - public static void Main() + string myLogName = "MyNewLog"; + // Check whether the source exists. + if (!EventLog.SourceExists("MySource")) { - try - { - string myLogName = "MyNewLog"; - // Check if the source exists. - if (!EventLog.SourceExists("MySource")) - { - // Create the source. - // An event log source should not be created and immediately used. - // There is a latency time to enable the source, it should be created - // prior to executing the application that uses the source. - // Execute this sample a second time to use the new source. - EventLog.CreateEventSource("MySource", myLogName); - Console.WriteLine("Creating EventSource"); - Console.WriteLine("Exiting, execute the application a second time to use the source."); - // The source is created. Exit the application to allow it to be registered. - return; - } - else - { - // Get the EventLog associated if the source exists. - myLogName = EventLog.LogNameFromSourceName("MySource", "."); - } + // Create the source. + // An event log source shouldn't be created and immediately used. + // The source takes time to become enabled. + // Create it before executing the application that uses it. + // Execute this sample a second time to use the new source. + EventLog.CreateEventSource("MySource", myLogName); + Console.WriteLine("Creating EventSource"); + Console.WriteLine("Exiting, execute the application a second time to use the source."); + // The source is created. Exit the application to allow it to be registered. + return; + } + + // Get the EventLog associated with the source. + myLogName = EventLog.LogNameFromSourceName("MySource", "."); + + // Create an EventLog instance and assign its source. + using EventLog myEventLog2 = new(); + myEventLog2.Source = "MySource"; + // Write an entry to the event log. + myEventLog2.WriteEntry("Successfully created a new Entry in the Log. "); - // Create an EventLog instance and assign its source. - EventLog myEventLog2 = new EventLog(); - myEventLog2.Source = "MySource"; - //Write an entry to the event log. - myEventLog2.WriteEntry("Successfully created a new Entry in the Log. "); - // - // - // Create a new EventLog object. - EventLog myEventLog1 = new EventLog(); - myEventLog1.Log = myLogName; - // Obtain the Log Entries of the Event Log - EventLogEntryCollection myEventLogEntryCollection = myEventLog1.Entries; - Console.WriteLine("The number of entries in 'MyNewLog' = " + - myEventLogEntryCollection.Count); - // Display the 'Message' property of EventLogEntry. - for (int i = 0; i < myEventLogEntryCollection.Count; i++) - { - Console.WriteLine("The Message of the EventLog is :" + - myEventLogEntryCollection[i].Message); - } - // - // - } - catch (Exception e) - { - Console.WriteLine("Exception Caught!" + e.Message); - } + // + // + // Create a new EventLog object. + using EventLog myEventLog1 = new(); + myEventLog1.Log = myLogName; + // Obtain the log entries of the event log. + EventLogEntryCollection myEventLogEntryCollection = myEventLog1.Entries; + Console.WriteLine($"The number of entries in 'MyNewLog' = {myEventLogEntryCollection.Count}"); + // Display the Message property of EventLogEntry. + for (int i = 0; i < myEventLogEntryCollection.Count; i++) + { + Console.WriteLine($"The Message of the EventLog is :{myEventLogEntryCollection[i].Message}"); } + // + // +} +catch (Exception e) +{ + Console.WriteLine($"Exception Caught!{e.Message}"); } diff --git a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/Project.csproj index e17ba622dbc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/Project.csproj @@ -1,13 +1,12 @@ - Library - net10.0-windows - true + Exe + net10.0 - + diff --git a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/eventlogentry_copyto.cs b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/eventlogentry_copyto.cs index 822771c49c6..1df0d523d2f 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/eventlogentry_copyto.cs +++ b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/eventlogentry_copyto.cs @@ -3,85 +3,73 @@ /* The following example demonstrates the EventLogEntryCollection class and the - CopyTo method of EventLogEntryCollection class. A new Source for eventlog 'MyNewLog' + CopyTo method of EventLogEntryCollection class. A new source for event log 'MyNewLog' is created. A new entry is created for 'MyNewLog'. The entries of EventLog are copied - to an Array. - */ + to an array. +*/ // using System; using System.Collections; using System.Diagnostics; -class EventLogEntryCollection_Item +try { - public static void Main() + string myLogName = "MyNewLog"; + // Check whether the source exists. + if (!EventLog.SourceExists("MySource")) { - try - { - string myLogName = "MyNewLog"; - // Check if the source exists. - if (!EventLog.SourceExists("MySource")) - { - // Create the source. - // An event log source should not be created and immediately used. - // There is a latency time to enable the source, it should be created - // prior to executing the application that uses the source. - // Execute this sample a second time to use the new source. - EventLog.CreateEventSource("MySource", myLogName); - Console.WriteLine("Creating EventSource"); - Console.WriteLine("Exiting, execute the application a second time to use the source."); - // The source is created. Exit the application to allow it to be registered. - return; - } - else - { - // Get the EventLog associated if the source exists. - myLogName = EventLog.LogNameFromSourceName("MySource", "."); - } + // Create the source. + // An event log source shouldn't be created and immediately used. + // The source takes time to become enabled. + // Create it before executing the application that uses it. + // Execute this sample a second time to use the new source. + EventLog.CreateEventSource("MySource", myLogName); + Console.WriteLine("Creating EventSource"); + Console.WriteLine("Exiting, execute the application a second time to use the source."); + // The source is created. Exit the application to allow it to be registered. + return; + } + + // Get the EventLog associated with the source. + myLogName = EventLog.LogNameFromSourceName("MySource", "."); + + // Create an EventLog instance and assign its source. + using (EventLog myEventLog2 = new()) + { + myEventLog2.Source = "MySource"; + // Write an informational entry to the event log. + myEventLog2.WriteEntry("Successfully created a new Entry in the Log"); + } - // Create an EventLog instance and assign its source. - EventLog myEventLog2 = new EventLog(); - myEventLog2.Source = "MySource"; - // Write an informational entry to the event log. - myEventLog2.WriteEntry("Successfully created a new Entry in the Log"); - myEventLog2.Close(); - // Create a new EventLog object. - EventLog myEventLog1 = new EventLog(); - myEventLog1.Log = myLogName; + // Create a new EventLog object. + using EventLog myEventLog1 = new(); + myEventLog1.Log = myLogName; - // Obtain the Log Entries of "MyNewLog". - EventLogEntryCollection myEventLogEntryCollection = - myEventLog1.Entries; - myEventLog1.Close(); - Console.WriteLine("The number of entries in 'MyNewLog' = " - + myEventLogEntryCollection.Count); + // Obtain the log entries of MyNewLog. + EventLogEntryCollection myEventLogEntryCollection = myEventLog1.Entries; + Console.WriteLine($"The number of entries in 'MyNewLog' = {myEventLogEntryCollection.Count}"); - // Display the 'Message' property of EventLogEntry. - for (int i = 0; i < myEventLogEntryCollection.Count; i++) - { - Console.WriteLine("The Message of the EventLog is :" - + myEventLogEntryCollection[i].Message); - } - // + // Display the Message property of EventLogEntry. + for (int i = 0; i < myEventLogEntryCollection.Count; i++) + { + Console.WriteLine($"The Message of the EventLog is :{myEventLogEntryCollection[i].Message}"); + } + // - // Copy the EventLog entries to Array of type EventLogEntry. - EventLogEntry[] myEventLogEntryArray = - new EventLogEntry[myEventLogEntryCollection.Count]; - myEventLogEntryCollection.CopyTo(myEventLogEntryArray, 0); - IEnumerator myEnumerator = myEventLogEntryArray.GetEnumerator(); - while (myEnumerator.MoveNext()) - { - EventLogEntry myEventLogEntry = (EventLogEntry)myEnumerator.Current; - Console.WriteLine("The LocalTime the Event is generated is " - + myEventLogEntry.TimeGenerated); - } - // - } - catch (Exception e) - { - Console.WriteLine("Exception:{0}", e.Message); - } + // Copy the EventLog entries to an array of type EventLogEntry. + EventLogEntry[] myEventLogEntryArray = new EventLogEntry[myEventLogEntryCollection.Count]; + myEventLogEntryCollection.CopyTo(myEventLogEntryArray, 0); + IEnumerator myEnumerator = myEventLogEntryArray.GetEnumerator(); + while (myEnumerator.MoveNext()) + { + EventLogEntry myEventLogEntry = (EventLogEntry)myEnumerator.Current; + Console.WriteLine($"The LocalTime the Event is generated is {myEventLogEntry.TimeGenerated}"); } + // +} +catch (Exception e) +{ + Console.WriteLine($"Exception:{e.Message}"); } // diff --git a/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/Project.csproj index e17ba622dbc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/Project.csproj @@ -1,13 +1,12 @@ - Library - net10.0-windows - true + Exe + net10.0 - + diff --git a/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/eventlogentrytype_6.cs b/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/eventlogentrytype_6.cs index 2d14971a0bb..e4e83b775f7 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/eventlogentrytype_6.cs +++ b/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/eventlogentrytype_6.cs @@ -6,102 +6,83 @@ // System.Diagnostics.EventLogEntryType.SuccessAudit /* The following program demonstrates 'Error', 'Warning', - 'Information', 'FailureAudit' and 'SuccessAudit' members of - 'EventLogEntryType' enumerator. It creates new source with a - specified event log, new ID, EventLogEntryType and message, - if does not exist. + 'Information', 'FailureAudit', and 'SuccessAudit' members of + the 'EventLogEntryType' enumeration. It creates a new source with a + specified event log, ID, EventLogEntryType, and message if it doesn't exist. */ // using System; using System.Diagnostics; -using System.Runtime.Serialization; -class MyEventLogEntryType +try { - public static void Main() + string myMessage = "A new event is created."; + Console.Write("Enter source name for new event (eg: Print ): "); + string mySource = Console.ReadLine(); + Console.Write("Enter log name in which to write an event( eg: System ): "); + string myLog = Console.ReadLine(); + // Check whether the source exists in the event log. + if (!EventLog.SourceExists(mySource)) { - try - { - EventLog myEventLog; - string mySource = null; - string myLog = null; - string myType = null; - string myMessage = "A new event is created."; - string myEventID = null; - int myIntLog = 0; - int myID = 0; - Console.Write("Enter source name for new event (eg: Print ): "); - mySource = Console.ReadLine(); - Console.Write("Enter log name in which to write an event( eg: System ): "); - myLog = Console.ReadLine(); - // Check whether source exist in event log. - if (false == EventLog.SourceExists(mySource)) - { - // Create a new source in a specified log on a system. - // An event log source should not be created and immediately used. - // There is a latency time to enable the source, it should be created - // prior to executing the application that uses the source. - // Execute this sample a second time to use the new source. - EventLog.CreateEventSource(mySource, myLog); - Console.WriteLine("Creating the event source, press the Enter key to exit the application, \n" + - "then run the applicaton again to use the new event source."); - Console.Read(); - } - Console.WriteLine(""); - Console.WriteLine(" Select type of event to write:"); - Console.WriteLine(" 1. Error "); - Console.WriteLine(" 2. Warning"); - Console.WriteLine(" 3. Information"); - Console.WriteLine(" 4. FailureAudit"); - Console.WriteLine(" 5. SuccessAudit"); - Console.Write("Enter the choice(eg. 1): "); - myType = Console.ReadLine(); - myIntLog = Convert.ToInt32(myType); - Console.Write("Enter ID with which to write an event( eg: 0-65535 ): "); - myEventID = Console.ReadLine(); - myID = Convert.ToInt32(myEventID); - // + // Create a new source in a specified log on a system. + // An event log source shouldn't be created and immediately used. + // The source takes time to become enabled. + // Create it before executing the application that uses it. + // Execute this sample a second time to use the new source. + EventLog.CreateEventSource(mySource, myLog); + Console.WriteLine("Creating the event source, press the Enter key to exit the application, \n" + + "then run the applicaton again to use the new event source."); + Console.Read(); + } + Console.WriteLine(); + Console.WriteLine(" Select type of event to write:"); + Console.WriteLine(" 1. Error "); + Console.WriteLine(" 2. Warning"); + Console.WriteLine(" 3. Information"); + Console.WriteLine(" 4. FailureAudit"); + Console.WriteLine(" 5. SuccessAudit"); + Console.Write("Enter the choice(eg. 1): "); + int myIntLog = Convert.ToInt32(Console.ReadLine()); + Console.Write("Enter ID with which to write an event( eg: 0-65535 ): "); + int myID = Convert.ToInt32(Console.ReadLine()); + // - // Create an event log instance. - myEventLog = new EventLog(myLog); - // Initialize source property of obtained instance. - myEventLog.Source = mySource; - switch (myIntLog) - { - case 1: - // Write an 'Error' entry in specified log of event log. - myEventLog.WriteEntry(myMessage, EventLogEntryType.Error, myID); - break; - case 2: - // Write a 'Warning' entry in specified log of event log. - myEventLog.WriteEntry(myMessage, EventLogEntryType.Warning, myID); - break; - case 3: - // Write an 'Information' entry in specified log of event log. - myEventLog.WriteEntry(myMessage, EventLogEntryType.Information, myID); - break; - case 4: - // Write a 'FailureAudit' entry in specified log of event log. - myEventLog.WriteEntry(myMessage, EventLogEntryType.FailureAudit, myID); - break; - case 5: - // Write a 'SuccessAudit' entry in specified log of event log. - myEventLog.WriteEntry(myMessage, EventLogEntryType.SuccessAudit, myID); - break; - default: - Console.WriteLine("Error: Failed to create an event in event log."); - break; - } - Console.WriteLine("A new event in log '{0}' with ID '{1}' " - + "is successfully written into event log.", - myEventLog.Log, myID); - // - } - catch (Exception e) - { - Console.WriteLine("Exception: {0}", e.Message); - } + // Create an event log instance. + using EventLog myEventLog = new(myLog); + // Initialize the Source property of the obtained instance. + myEventLog.Source = mySource; + switch (myIntLog) + { + case 1: + // Write an Error entry in the specified event log. + myEventLog.WriteEntry(myMessage, EventLogEntryType.Error, myID); + break; + case 2: + // Write a Warning entry in the specified event log. + myEventLog.WriteEntry(myMessage, EventLogEntryType.Warning, myID); + break; + case 3: + // Write an Information entry in the specified event log. + myEventLog.WriteEntry(myMessage, EventLogEntryType.Information, myID); + break; + case 4: + // Write a FailureAudit entry in the specified event log. + myEventLog.WriteEntry(myMessage, EventLogEntryType.FailureAudit, myID); + break; + case 5: + // Write a SuccessAudit entry in the specified event log. + myEventLog.WriteEntry(myMessage, EventLogEntryType.SuccessAudit, myID); + break; + default: + Console.WriteLine("Error: Failed to create an event in event log."); + break; } + Console.WriteLine($"A new event in log '{myEventLog.Log}' with ID '{myID}' is successfully written into event log."); + // +} +catch (Exception e) +{ + Console.WriteLine($"Exception: {e.Message}"); } // diff --git a/snippets/csharp/System.Diagnostics/EventLogTraceListener/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/EventLogTraceListener/Overview/Project.csproj index ea2d5c6b0fc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventLogTraceListener/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLogTraceListener/Overview/Project.csproj @@ -8,5 +8,5 @@ - - \ No newline at end of file + + diff --git a/snippets/csharp/System.Diagnostics/EventLogTraceListener/Overview/source.cs b/snippets/csharp/System.Diagnostics/EventLogTraceListener/Overview/source.cs index f3522bdb7e2..064a2581773 100644 --- a/snippets/csharp/System.Diagnostics/EventLogTraceListener/Overview/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLogTraceListener/Overview/source.cs @@ -2,7 +2,7 @@ // // Create a trace listener for the event log. -EventLogTraceListener myTraceListener = new EventLogTraceListener("myEventLogSource"); +using EventLogTraceListener myTraceListener = new("myEventLogSource"); // Add the event log trace listener to the collection. Trace.Listeners.Add(myTraceListener); diff --git a/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/Project.csproj index e17ba622dbc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/Project.csproj @@ -1,13 +1,12 @@ - Library - net10.0-windows - true + Exe + net10.0 - + diff --git a/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs b/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs index 3f372400b2e..abcb9504969 100644 --- a/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs +++ b/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs @@ -1,138 +1,118 @@ -// +// using System; -using System.Globalization; using System.Diagnostics; +using System.Globalization; +using System.IO; -namespace EventLogSamples +namespace EventLogSamples; + +class CreateSourceSample { - class CreateSourceSample + [STAThread] + static void Main(string[] args) { - [STAThread] - static void Main(string[] args) + // + EventSourceCreationData mySourceData = new("", ""); + bool registerSource = true; + + // Process input parameters. + if (args.Length > 0) { - // - EventSourceCreationData mySourceData = new EventSourceCreationData("", ""); - bool registerSource = true; + // Require at least the source name. + mySourceData.Source = args[0]; - // Process input parameters. - if (args.Length > 0) + if (args.Length > 1) { - // Require at least the source name. - - mySourceData.Source = args[0]; - - if (args.Length > 1) - { - mySourceData.LogName = args[1]; - } - - if (args.Length > 2) - { - mySourceData.MachineName = args[2]; - } - if ((args.Length > 3) && (args[3].Length > 0)) - { - mySourceData.MessageResourceFile = args[3]; - } - } - else - { - // Display a syntax help message. - Console.WriteLine("Input:"); - Console.WriteLine(" source [event log] [machine name] [resource file]"); - - registerSource = false; + mySourceData.LogName = args[1]; } - // Set defaults for parameters missing input. - if (mySourceData.MachineName.Length == 0) + if (args.Length > 2) { - // Default to the local computer. - mySourceData.MachineName = "."; + mySourceData.MachineName = args[2]; } - if (mySourceData.LogName.Length == 0) + + if (args.Length > 3 && args[3].Length > 0) { - // Default to the Application log. - mySourceData.LogName = "Application"; + mySourceData.MessageResourceFile = args[3]; } - // + } + else + { + // Display a syntax help message. + Console.WriteLine("Input:"); + Console.WriteLine(" source [event log] [machine name] [resource file]"); + registerSource = false; + } - // Determine if the source exists on the specified computer. - if (!EventLog.SourceExists(mySourceData.Source, - mySourceData.MachineName)) - { - // The source does not exist. + // Set defaults for parameters missing input. + if (mySourceData.MachineName.Length == 0) + { + // Default to the local computer. + mySourceData.MachineName = "."; + } - // Verify that the message file exists - // and the event log is local. + if (mySourceData.LogName.Length == 0) + { + // Default to the Application log. + mySourceData.LogName = "Application"; + } + // - if ((mySourceData.MessageResourceFile != null) && - (mySourceData.MessageResourceFile.Length > 0)) + // Determine whether the source exists on the specified computer. + if (!EventLog.SourceExists(mySourceData.Source, mySourceData.MachineName)) + { + // Verify that the message file exists and the event log is local. + if (!string.IsNullOrEmpty(mySourceData.MessageResourceFile)) + { + if (mySourceData.MachineName == ".") { - if (mySourceData.MachineName == ".") + if (!File.Exists(mySourceData.MessageResourceFile)) { - if (!System.IO.File.Exists(mySourceData.MessageResourceFile)) - { - Console.WriteLine("File {0} not found - message file not set for source.", - mySourceData.MessageResourceFile); - registerSource = false; - } - } - else - { - // For simplicity, do not allow setting the message - // file for a remote event log. To set the message - // for a remote event log, and for source registration, - // the file path should be specified with system-wide - // environment variables that are valid on the remote - // computer, such as - // "%SystemRoot%\system32\myresource.dll". - - Console.WriteLine("Message resource file ignored for remote event log."); + Console.WriteLine($"File {mySourceData.MessageResourceFile} not found - message file not set for source."); registerSource = false; } } - } - else - { - // Do not register the source, it already exists. - registerSource = false; - - // Get the event log corresponding to the existing source. - string sourceLog; - sourceLog = EventLog.LogNameFromSourceName(mySourceData.Source, - mySourceData.MachineName); - - // Determine if the event source is registered for the - // specified log. - - if (sourceLog.ToUpper(CultureInfo.InvariantCulture) != mySourceData.LogName.ToUpper(CultureInfo.InvariantCulture)) - { - // An existing source is registered - // to write to a different event log. - Console.WriteLine("Warning: source {0} is already registered to write to event log {1}", - mySourceData.Source, sourceLog); - } else { - // The source is already registered - // to write to the specified event log. - - Console.WriteLine("Source {0} already registered to write to event log {1}", - mySourceData.Source, sourceLog); + // For simplicity, don't allow setting the message file for a remote event log. + // To set the message and register the source remotely, use system-wide environment variables. + // Use variables that are valid on that computer, such as "%SystemRoot%\system32\myresource.dll". + Console.WriteLine("Message resource file ignored for remote event log."); + registerSource = false; } } + } + else + { + // Don't register the source because it already exists. + registerSource = false; - if (registerSource) - { - // Register the new event source for the specified event log. + // Get the event log corresponding to the existing source. + string sourceLog = EventLog.LogNameFromSourceName( + mySourceData.Source, + mySourceData.MachineName); - Console.WriteLine("Registering new source {0} for event log {1}.", - mySourceData.Source, mySourceData.LogName); - EventLog.CreateEventSource(mySourceData); - Console.WriteLine("Event source was registered successfully!"); + // Determine whether the event source is registered for the specified log. + if (sourceLog.ToUpper(CultureInfo.InvariantCulture) != + mySourceData.LogName.ToUpper(CultureInfo.InvariantCulture)) + { + // An existing source is registered to write to a different event log. + Console.WriteLine($"Warning: source {mySourceData.Source} is already registered to write to event log {sourceLog}"); } + else + { + // The source is already registered to write to the specified event log. + Console.WriteLine($"Source {mySourceData.Source} already registered to write to event log {sourceLog}"); + } + } + + if (registerSource) + { + // Register the new event source for the specified event log. + Console.WriteLine($"Registering new source {mySourceData.Source} for event log {mySourceData.LogName}."); + EventLog.CreateEventSource(mySourceData); + Console.WriteLine("Event source was registered successfully!"); } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/Comments/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/Comments/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/Comments/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/Comments/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/Comments/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/Comments/source.cs index 4365a9c4d57..9c6ae1bb212 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/Comments/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/Comments/source.cs @@ -1,19 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - void GetComments() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - // Print the comments in a text box. - textBox1.Text = "Comments: " + myFileVersionInfo.Comments; - } +// Display the Comments property. +Console.WriteLine($"Comments: {fileVersionInfo.Comments}"); // -} diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/CompanyName/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/CompanyName/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/CompanyName/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/CompanyName/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/CompanyName/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/CompanyName/source.cs index 1d1591fea4c..98b0ee33109 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/CompanyName/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/CompanyName/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetCompanyName() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the company name. - textBox1.Text = "The company name: " + myFileVersionInfo.CompanyName; - } +// Display the CompanyName property. +Console.WriteLine($"The company name: {fileVersionInfo.CompanyName}"); // -} diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileBuildPart/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileBuildPart/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileBuildPart/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileBuildPart/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileBuildPart/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileBuildPart/source.cs index 31934a1f680..20a69fd0058 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileBuildPart/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileBuildPart/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetFileBuildPart() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the file build number. - textBox1.Text = "File build number: " + myFileVersionInfo.FileBuildPart; - } - // -} +// Display the FileBuildPart property. +Console.WriteLine($"File build number: {fileVersionInfo.FileBuildPart}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileDescription/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileDescription/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileDescription/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileDescription/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileDescription/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileDescription/source.cs index a27b1129c15..5dd1a20cb62 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileDescription/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileDescription/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetFileDescription() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the file description. - textBox1.Text = "File description: " + myFileVersionInfo.FileDescription; - } - // -} +// Display the FileDescription property. +Console.WriteLine($"File description: {fileVersionInfo.FileDescription}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMajorPart/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMajorPart/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMajorPart/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMajorPart/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMajorPart/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMajorPart/source.cs index cd1bb8f6bb9..be845b5ddb8 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMajorPart/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMajorPart/source.cs @@ -1,18 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; // -private void GetFileMajorPart() { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo("%systemroot%\\Notepad.exe"); - - // Print the file major part number. - textBox1.Text = "File major part number: " + myFileVersionInfo.FileMajorPart; - } +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); +// Display the FileMajorPart property. +Console.WriteLine($"File major part number: {fileVersionInfo.FileMajorPart}"); // -} diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMinorPart/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMinorPart/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMinorPart/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMinorPart/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMinorPart/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMinorPart/source.cs index a3c5e8957ed..40ef5d03cf2 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMinorPart/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileMinorPart/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetFileMinorPart() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the file minor part number. - textBox1.Text = "File minor part number: " + myFileVersionInfo.FileMinorPart; - } - // -} +// Display the FileMinorPart property. +Console.WriteLine($"File minor part number: {fileVersionInfo.FileMinorPart}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileName/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileName/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileName/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileName/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileName/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileName/source.cs index 300b8c7c634..919dfe8dc6b 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FileName/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FileName/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetFileName() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the file name. - textBox1.Text = "File name: " + myFileVersionInfo.FileName; - } - // -} +// Display the FileName property. +Console.WriteLine($"File name: {fileVersionInfo.FileName}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FilePrivatePart/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/FilePrivatePart/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FilePrivatePart/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FilePrivatePart/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/FilePrivatePart/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/FilePrivatePart/source.cs index 9abd4db1f60..7db2da216e8 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/FilePrivatePart/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/FilePrivatePart/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetFilePrivatePart() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the file private part number. - textBox1.Text = "File private part number: " + myFileVersionInfo.FilePrivatePart; - } - // -} +// Display the FilePrivatePart property. +Console.WriteLine($"File private part number: {fileVersionInfo.FilePrivatePart}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/InternalName/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/InternalName/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/InternalName/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/InternalName/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/InternalName/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/InternalName/source.cs index dedbc9d6f7b..d10bc514d57 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/InternalName/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/InternalName/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetInternalName() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the internal name. - textBox1.Text = "Internal name: " + myFileVersionInfo.InternalName; - } - // -} +// Display the InternalName property. +Console.WriteLine($"Internal name: {fileVersionInfo.InternalName}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsDebug/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsDebug/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsDebug/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsDebug/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsDebug/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsDebug/source.cs index 9666ccb849c..7739599db8f 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsDebug/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsDebug/source.cs @@ -1,21 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetIsDebug() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print whether the file contains debugging information. - textBox1.Text = "File contains debugging information: " + - myFileVersionInfo.IsDebug; - } - // -} +// Display the IsDebug property. +Console.WriteLine($"File contains debugging information: {fileVersionInfo.IsDebug}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPatched/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPatched/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPatched/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPatched/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPatched/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPatched/source.cs index 1d85d280f95..546000d9f29 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPatched/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPatched/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetIsPatched() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print whether the file has a patch installed. - textBox1.Text = "File has patch installed: " + myFileVersionInfo.IsPatched; - } - // -} +// Display the IsPatched property. +Console.WriteLine($"File has patch installed: {fileVersionInfo.IsPatched}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPreRelease/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPreRelease/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPreRelease/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPreRelease/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPreRelease/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPreRelease/source.cs index ca773918a7c..0c0b7bc2e16 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPreRelease/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPreRelease/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetIsPreRelease() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print whether the file is a prerelease version. - textBox1.Text = "File is prerelease version " + myFileVersionInfo.IsPreRelease; - } - // -} +// Display the IsPreRelease property. +Console.WriteLine($"File is prerelease version {fileVersionInfo.IsPreRelease}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPrivateBuild/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPrivateBuild/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPrivateBuild/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPrivateBuild/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPrivateBuild/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPrivateBuild/source.cs index ef550cab291..181fb3e1611 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPrivateBuild/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsPrivateBuild/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetIsPrivateBuild() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print whether the version is a private build. - textBox1.Text = "Version is a private build: " + myFileVersionInfo.IsPrivateBuild; - } - // -} +// Display the IsPrivateBuild property. +Console.WriteLine($"Version is a private build: {fileVersionInfo.IsPrivateBuild}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsSpecialBuild/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsSpecialBuild/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsSpecialBuild/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsSpecialBuild/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsSpecialBuild/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsSpecialBuild/source.cs index 13000bbbddd..cb9b8f68fb7 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/IsSpecialBuild/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/IsSpecialBuild/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1 : Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetIsSpecialBuild() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print whether the file is a special build. - textBox1.Text = "File is a special build: " + myFileVersionInfo.IsSpecialBuild; - } - // -} +// Display the IsSpecialBuild property. +Console.WriteLine($"File is a special build: {fileVersionInfo.IsSpecialBuild}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalCopyright/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalCopyright/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalCopyright/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalCopyright/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalCopyright/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalCopyright/source.cs index acea2581a87..b45e0cf1e73 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalCopyright/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalCopyright/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1 : Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetCopyright() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the copyright notice. - textBox1.Text = "Copyright notice: " + myFileVersionInfo.LegalCopyright; - } - // -} +// Display the LegalCopyright property. +Console.WriteLine($"Copyright notice: {fileVersionInfo.LegalCopyright}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalTrademarks/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalTrademarks/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalTrademarks/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalTrademarks/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalTrademarks/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalTrademarks/source.cs index 1578fad8853..1f5145b06fd 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalTrademarks/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/LegalTrademarks/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetTrademarks() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the trademarks. - textBox1.Text = "Trademarks: " + myFileVersionInfo.LegalTrademarks; - } - // -} +// Display the LegalTrademarks property. +Console.WriteLine($"Trademarks: {fileVersionInfo.LegalTrademarks}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/OriginalFilename/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/OriginalFilename/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/OriginalFilename/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/OriginalFilename/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/OriginalFilename/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/OriginalFilename/source.cs index d67c86454b4..6cac0f9b06e 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/OriginalFilename/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/OriginalFilename/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetOriginalName() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the original file name. - textBox1.Text = "Original file name: " + myFileVersionInfo.OriginalFilename; - } - // -} +// Display the OriginalFilename property. +Console.WriteLine($"Original file name: {fileVersionInfo.OriginalFilename}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/Overview/Project.csproj index a369cfa8a80..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/Overview/Project.csproj @@ -1,8 +1,8 @@ - Library + Exe net10.0 - - \ No newline at end of file + + diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/Overview/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/Overview/source.cs index fa905b751bd..d55767aacd3 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/Overview/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/Overview/source.cs @@ -1,19 +1,12 @@ // - using System; -using System.IO; using System.Diagnostics; +using System.IO; -class Class1 -{ - public static void Main(string[] args) - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // Print the file name and version number. - Console.WriteLine("File: " + myFileVersionInfo.FileDescription + Environment.NewLine + - "Version number: " + myFileVersionInfo.FileVersion); - } -} +// Display the file name and version number. +Console.WriteLine($"File: {fileVersionInfo.FileDescription}{Environment.NewLine}Version number: {fileVersionInfo.FileVersion}"); // diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/PrivateBuild/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/PrivateBuild/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/PrivateBuild/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/PrivateBuild/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/PrivateBuild/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/PrivateBuild/source.cs index bc75ba7a4c8..1ddca8e7c90 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/PrivateBuild/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/PrivateBuild/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetPrivateBuild() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the private build number. - textBox1.Text = "Private build number: " + myFileVersionInfo.PrivateBuild; - } - // -} +// Display the PrivateBuild property. +Console.WriteLine($"Private build number: {fileVersionInfo.PrivateBuild}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductBuildPart/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductBuildPart/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductBuildPart/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductBuildPart/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductBuildPart/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductBuildPart/source.cs index 23b1c7e9c33..8c7ebaa7b15 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductBuildPart/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductBuildPart/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetProductBuildPart() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the product build part number. - textBox1.Text = "Product build part number: " + myFileVersionInfo.ProductBuildPart; - } - // -} +// Display the ProductBuildPart property. +Console.WriteLine($"Product build part number: {fileVersionInfo.ProductBuildPart}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMajorPart/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMajorPart/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMajorPart/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMajorPart/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMajorPart/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMajorPart/source.cs index 2deb9ae453e..655c9af038e 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMajorPart/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMajorPart/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1 : Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetProductMajorPart() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the product major part number. - textBox1.Text = "Product major part number: " + myFileVersionInfo.ProductMajorPart; - } - // -} +// Display the ProductMajorPart property. +Console.WriteLine($"Product major part number: {fileVersionInfo.ProductMajorPart}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMinorPart/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMinorPart/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMinorPart/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMinorPart/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMinorPart/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMinorPart/source.cs index 551ff0a56b5..9db79ca3a87 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMinorPart/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductMinorPart/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1 : Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetProductMinorPart() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the product minor part number. - textBox1.Text = "Product minor part number: " + myFileVersionInfo.ProductMinorPart; - } - // -} +// Display the ProductMinorPart property. +Console.WriteLine($"Product minor part number: {fileVersionInfo.ProductMinorPart}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductName/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductName/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductName/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductName/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductName/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductName/source.cs index 6a8cee4f773..2e89f7f5860 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductName/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductName/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetProductName() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the product name. - textBox1.Text = "Product name: " + myFileVersionInfo.ProductName; - } - // -} +// Display the ProductName property. +Console.WriteLine($"Product name: {fileVersionInfo.ProductName}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductPrivatePart/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductPrivatePart/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductPrivatePart/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductPrivatePart/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductPrivatePart/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductPrivatePart/source.cs index 56adb14b490..b8bef90a5e8 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductPrivatePart/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductPrivatePart/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1 : Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetProductPrivatePart() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the product private part number. - textBox1.Text = "Product private part number: " + myFileVersionInfo.ProductPrivatePart; - } - // -} +// Display the ProductPrivatePart property. +Console.WriteLine($"Product private part number: {fileVersionInfo.ProductPrivatePart}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductVersion/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductVersion/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductVersion/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductVersion/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductVersion/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductVersion/source.cs index 6fe2d7c4919..eae2ef04203 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductVersion/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ProductVersion/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1 : Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetProductVersion() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the product version number. - textBox1.Text = "Product version number: " + myFileVersionInfo.ProductVersion; - } - // -} +// Display the ProductVersion property. +Console.WriteLine($"Product version number: {fileVersionInfo.ProductVersion}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/SpecialBuild/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/SpecialBuild/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/SpecialBuild/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/SpecialBuild/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/SpecialBuild/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/SpecialBuild/source.cs index 811fe458814..65b6b8b1eba 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/SpecialBuild/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/SpecialBuild/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetSpecialBuild() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print the special build information. - textBox1.Text = "Special build information: " + myFileVersionInfo.SpecialBuild; - } - // -} +// Display the SpecialBuild property. +Console.WriteLine($"Special build information: {fileVersionInfo.SpecialBuild}"); +// diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ToString/Project.csproj b/snippets/csharp/System.Diagnostics/FileVersionInfo/ToString/Project.csproj index e17ba622dbc..a15a29bf12c 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ToString/Project.csproj +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ToString/Project.csproj @@ -1,13 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 - - - - diff --git a/snippets/csharp/System.Diagnostics/FileVersionInfo/ToString/source.cs b/snippets/csharp/System.Diagnostics/FileVersionInfo/ToString/source.cs index 5c4379d11d4..5e869e47134 100644 --- a/snippets/csharp/System.Diagnostics/FileVersionInfo/ToString/source.cs +++ b/snippets/csharp/System.Diagnostics/FileVersionInfo/ToString/source.cs @@ -1,20 +1,12 @@ using System; -using System.Windows.Forms; using System.Diagnostics; +using System.IO; -public class Form1: Form -{ - protected TextBox textBox1; +// +// Get the file version for Notepad. +FileVersionInfo fileVersionInfo = + FileVersionInfo.GetVersionInfo(Path.Combine(Environment.SystemDirectory, "Notepad.exe")); - // - private void GetFileVersion2() - { - // Get the file version for the notepad. - FileVersionInfo myFileVersionInfo = - FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); - - // Print all the version information. - textBox1.Text = myFileVersionInfo.ToString(); - } - // -} +// Display all the version information. +Console.WriteLine(fileVersionInfo.ToString()); +// diff --git a/snippets/csharp/System.Diagnostics/InstanceData/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/InstanceData/Overview/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/InstanceData/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/InstanceData/Overview/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/InstanceData/Overview/instdatacopyto.cs b/snippets/csharp/System.Diagnostics/InstanceData/Overview/instdatacopyto.cs index 29b04a0126a..aff283f6380 100644 --- a/snippets/csharp/System.Diagnostics/InstanceData/Overview/instdatacopyto.cs +++ b/snippets/csharp/System.Diagnostics/InstanceData/Overview/instdatacopyto.cs @@ -1,13 +1,13 @@ -// +// using System; using System.Diagnostics; class InstDataCopyToMod { - // + // private static string categoryName; - // + // public static void Main() { @@ -19,7 +19,7 @@ public static void Main() // Create and sort an array of category names. string[] categoryNames = new string[categories.Length]; int catX; - for(catX=0; catXcategories.Length) + if (categoryNum < 1 || categoryNum > categories.Length) { - throw new Exception(String.Format("The category number must be in the " + + throw new Exception(string.Format("The category number must be in the " + "range 1..{0}.", categories.Length)); } - categoryName = categoryNames[(categoryNum-1)]; + categoryName = categoryNames[(categoryNum - 1)]; } - catch(Exception ex) + catch (Exception ex) { Console.WriteLine("\"{0}\" is not a valid category number." + "\r\n{1}", catNumStr, ex.Message); return; } - // - // + // + // // Process the InstanceDataCollectionCollection for this category. - PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName); + PerformanceCounterCategory pcc = new(categoryName); InstanceDataCollectionCollection idColCol = pcc.ReadCategory(); InstanceDataCollection[] idColArray = new InstanceDataCollection[idColCol.Count]; Console.WriteLine("InstanceDataCollectionCollection for \"{0}\" " + "has {1} elements.", categoryName, idColCol.Count); - // + // // Copy and process the InstanceDataCollection array. idColCol.CopyTo(idColArray, 0); - foreach ( InstanceDataCollection idCol in idColArray ) + foreach (InstanceDataCollection idCol in idColArray) { ProcessInstanceDataCollection(idCol); } - // + // } - // + // // Display the contents of an InstanceDataCollection. public static void ProcessInstanceDataCollection(InstanceDataCollection idCol) { @@ -89,23 +89,23 @@ public static void ProcessInstanceDataCollection(InstanceDataCollection idCol) idCol.CopyTo(instDataArray, 0); int idX; - for(idX=0; idX + // - // - // + // + // // Display the contents of an InstanceData object. public static void ProcessInstanceDataObject(string name, CounterSample CSRef) { - InstanceData instData = new InstanceData(name, CSRef); + InstanceData instData = new(name, CSRef); Console.WriteLine(" Data from InstanceData object:\r\n" + " InstanceName: {0,-31} RawValue: {1}", instData.InstanceName, instData.RawValue); - // + // CounterSample sample = instData.Sample; Console.WriteLine(" Data from CounterSample object:\r\n" + @@ -113,9 +113,9 @@ public static void ProcessInstanceDataObject(string name, CounterSample CSRef) " BaseValue: {2,-34} RawValue: {3}\r\n" + " CounterFrequency: {4,-27} CounterTimeStamp: {5}\r\n" + " TimeStamp: {6,-34} TimeStamp100nSec: {7}", sample.CounterType, sample.SystemFrequency, sample.BaseValue, sample.RawValue, sample.CounterFrequency, sample.CounterTimeStamp, sample.TimeStamp, sample.TimeStamp100nSec); - // + // } - // - // + // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Contains/Project.csproj b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Contains/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Contains/Project.csproj +++ b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Contains/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Contains/instdatacolitemcontains.cs b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Contains/instdatacolitemcontains.cs index f40adac9ef9..adef4f8fa05 100644 --- a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Contains/instdatacolitemcontains.cs +++ b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Contains/instdatacolitemcontains.cs @@ -1,21 +1,17 @@ -// +// using System; using System.Diagnostics; -using Microsoft.VisualBasic; class InstDataColItemContainsMod { - - // + // public static void Main(string[] args) { // These values can be used as arguments. string categoryName = "Process"; string counterName = "Private Bytes"; string instanceName = "Explorer"; - - InstanceDataCollection idCol; - const string SINGLE_INSTANCE_NAME = "systemdiagnosticsperfcounterlibsingleinstance"; + const string SingleInstanceName = "systemdiagnosticsperfcounterlibsingleinstance"; // Copy the supplied arguments into the local variables. try @@ -29,56 +25,51 @@ public static void Main(string[] args) // Ignore the exception from non-supplied arguments. } + InstanceDataCollection idCol; try { // Get the InstanceDataCollectionCollection for this category. - PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName); + PerformanceCounterCategory pcc = new(categoryName); InstanceDataCollectionCollection idColCol = pcc.ReadCategory(); // Get the InstanceDataCollection for this counter. idCol = idColCol[counterName]; - if (idCol==null) + if (idCol == null) { throw new Exception("Counter does not exist."); } } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("An error occurred getting the InstanceDataCollection for " + - "category \"{0}\", counter \"{1}\"." + "\n" + ex.Message, categoryName, counterName); + Console.WriteLine($"An error occurred getting the InstanceDataCollection for category \"{categoryName}\", counter \"{counterName}\".\n{ex.Message}"); return; } // If the instance name is empty, use the single-instance name. - if (instanceName.Length==0) + if (instanceName.Length == 0) { - instanceName = SINGLE_INSTANCE_NAME; + instanceName = SingleInstanceName; } - // - // Check if this instance name exists using the Contains - // method of the InstanceDataCollection. + // + // Check whether this instance name exists by using the Contains method. if (!idCol.Contains(instanceName)) - // + // { - Console.WriteLine("Instance \"{0}\" does not exist in counter \"{1}\", " + - "category \"{2}\".", instanceName, counterName, categoryName); + Console.WriteLine($"Instance \"{instanceName}\" does not exist in counter \"{counterName}\", category \"{categoryName}\"."); return; } - else - { - // - // The instance name exists, now get its InstanceData object - // using the indexer (Item property) for the InstanceDataCollection. - InstanceData instData = idCol[instanceName]; - // - Console.WriteLine("CategoryName: {0}", categoryName); - Console.WriteLine("CounterName: {0}", counterName); - Console.WriteLine("InstanceName: {0}", instData.InstanceName); - Console.WriteLine("RawValue: {0}", instData.RawValue); - } + // + // Get the InstanceData object by using the indexer (Item property). + InstanceData instData = idCol[instanceName]; + // + + Console.WriteLine($"CategoryName: {categoryName}"); + Console.WriteLine($"CounterName: {counterName}"); + Console.WriteLine($"InstanceName: {instData.InstanceName}"); + Console.WriteLine($"RawValue: {instData.RawValue}"); } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs index ae42842d873..f2e548f55ff 100644 --- a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs +++ b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs @@ -1,14 +1,14 @@ -// +// using System; -using System.Diagnostics; using System.Collections; +using System.Diagnostics; class InstDataKeysValuesMod { - // + // private static string categoryName; - // + // public static void Main() { @@ -20,9 +20,9 @@ public static void Main() Console.WriteLine("These categories are registered on this computer:"); int catX; - for(catX=0; catXcategories.Length) + if (categoryNum < 1 || categoryNum > categories.Length) { - throw new Exception(String.Format("The category number must be in the " + + throw new Exception(string.Format("The category number must be in the " + "range 1..{0}.", categories.Length)); } categoryName = categories[(categoryNum - 1)].CategoryName; } - catch(Exception ex) + catch (Exception ex) { Console.WriteLine("\"{0}\" is not a valid category number." + "\r\n{1}", catNumStr, ex.Message); return; } - // + // // Process the InstanceDataCollectionCollection for this category. - PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName); + PerformanceCounterCategory pcc = new(categoryName); InstanceDataCollectionCollection idColCol = pcc.ReadCategory(); ICollection idColColKeys = idColCol.Keys; @@ -66,21 +66,21 @@ public static void Main() // Display the InstanceDataCollectionCollection Keys and Values. // The Keys and Values collections have the same number of elements. int index; - for(index=0; index + // } - // - // + // + // // Display the contents of an InstanceDataCollection. public static void ProcessInstanceDataCollection(InstanceDataCollection idCol) { - // + // ICollection idColKeys = idCol.Keys; string[] idColKeysArray = new string[idColKeys.Count]; @@ -89,25 +89,25 @@ public static void ProcessInstanceDataCollection(InstanceDataCollection idCol) ICollection idColValues = idCol.Values; InstanceData[] idColValuesArray = new InstanceData[idColValues.Count]; idColValues.CopyTo(idColValuesArray, 0); - // + // Console.WriteLine(" InstanceDataCollection for \"{0}\" " + "has {1} elements.", idCol.CounterName, idCol.Count); - // + // // Display the InstanceDataCollection Keys and Values. // The Keys and Values collections have the same number of elements. int index; - for(index=0; index + // } - // - // + // + // // Display the contents of an InstanceData object. public static void ProcessInstanceDataObject(InstanceData instData) @@ -123,4 +123,4 @@ public static void ProcessInstanceDataObject(InstanceData instData) " TimeStamp: {6,-34} TimeStamp100nSec: {7}", sample.CounterType, sample.SystemFrequency, sample.BaseValue, sample.RawValue, sample.CounterFrequency, sample.CounterTimeStamp, sample.TimeStamp, sample.TimeStamp100nSec); } } -// +// diff --git a/snippets/csharp/System.Diagnostics/InstanceDataCollectionCollection/Contains/Project.csproj b/snippets/csharp/System.Diagnostics/InstanceDataCollectionCollection/Contains/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/InstanceDataCollectionCollection/Contains/Project.csproj +++ b/snippets/csharp/System.Diagnostics/InstanceDataCollectionCollection/Contains/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/InstanceDataCollectionCollection/Contains/instdatacolcolitermcontains.cs b/snippets/csharp/System.Diagnostics/InstanceDataCollectionCollection/Contains/instdatacolcolitermcontains.cs index b0a42b4b8f3..9c21d7ebb87 100644 --- a/snippets/csharp/System.Diagnostics/InstanceDataCollectionCollection/Contains/instdatacolcolitermcontains.cs +++ b/snippets/csharp/System.Diagnostics/InstanceDataCollectionCollection/Contains/instdatacolcolitermcontains.cs @@ -1,21 +1,17 @@ -// +// using System; -using System.Diagnostics; using System.Collections; -using Microsoft.VisualBasic; +using System.Diagnostics; class InstDataColColItemContainsMod { - - // + // public static void Main(string[] args) { // The following values can be used as arguments. string categoryName = "Process"; string counterName = "Private Bytes"; - InstanceDataCollectionCollection idColCol; - // Copy the supplied arguments into the local variables. try { @@ -27,51 +23,45 @@ public static void Main(string[] args) // Ignore the exception from non-supplied arguments. } + InstanceDataCollectionCollection idColCol; try { // Get the InstanceDataCollectionCollection for this category. - PerformanceCounterCategory pcc = new PerformanceCounterCategory(categoryName); + PerformanceCounterCategory pcc = new(categoryName); idColCol = pcc.ReadCategory(); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("An error occurred getting the InstanceDataCollection for " + - "category \"{0}\"."+ "\n" +ex.Message, categoryName); + Console.WriteLine($"An error occurred getting the InstanceDataCollection for category \"{categoryName}\".\n{ex.Message}"); return; } - // - // Check if this counter name exists using the Contains - // method of the InstanceDataCollectionCollection. + // + // Check whether this counter name exists by using the Contains method. if (!idColCol.Contains(counterName)) - // + // { - Console.WriteLine("Counter \"{0}\" does not exist in category \"{1}\".", counterName, categoryName); + Console.WriteLine($"Counter \"{counterName}\" does not exist in category \"{categoryName}\"."); return; } - else - { - // - // Now get the counter's InstanceDataCollection object using the - // indexer (Item property) for the InstanceDataCollectionCollection. - InstanceDataCollection countData = idColCol[counterName]; - // - ICollection idColKeys = countData.Keys; - string[] idColKeysArray = new string[idColKeys.Count]; - idColKeys.CopyTo(idColKeysArray, 0); + // + // Get the counter's InstanceDataCollection by using the indexer (Item property). + InstanceDataCollection countData = idColCol[counterName]; + // - Console.WriteLine("Counter \"{0}\" of category \"{1}\" " + - "has {2} instances.", counterName, categoryName, idColKeys.Count); + ICollection idColKeys = countData.Keys; + string[] idColKeysArray = new string[idColKeys.Count]; + idColKeys.CopyTo(idColKeysArray, 0); - // Display the instance names for this counter. - int index; - for(index=0; index + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/Project.csproj b/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/Project.csproj +++ b/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/perfcounter.cs b/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/perfcounter.cs index 340b42c3e7f..fc193e2f1d1 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/perfcounter.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/perfcounter.cs @@ -1,91 +1,15 @@ using System; -using System.Drawing; -using System.Collections; -using System.ComponentModel; -using System.Windows.Forms; -using System.Data; using System.Diagnostics; -namespace PerfCounter -{ - /// - /// Summary description for Form1. - /// - public class Form1 : System.Windows.Forms.Form - { - /// - /// Required designer variable. - /// - private System.ComponentModel.Container components = null; - - public Form1() - { - // - // Required for Windows Form Designer support - // - InitializeComponent(); - - // - // TODO: Add any constructor code after InitializeComponent call - // - } - - /// - /// Clean up any resources being used. - /// - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (components != null) - { - components.Dispose(); - } - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - // - // Form1 - // - this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); - this.ClientSize = new System.Drawing.Size(292, 266); - this.Name = "Form1"; - this.Text = "Form1"; - this.Load += new System.EventHandler(this.Form1_Load); - } - #endregion - - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - Application.Run(new Form1()); - } - - private void Form1_Load(object sender, System.EventArgs e) - { - // - PerformanceCounter performanceCounter = new PerformanceCounter(); - performanceCounter.CategoryName = "Process"; - performanceCounter.CounterName = "Private Bytes"; - performanceCounter.InstanceName = "Explorer"; - MessageBox.Show(performanceCounter.NextValue().ToString()); - // - - // - var performanceCounterCategories = PerformanceCounterCategory.GetCategories(); - MessageBox.Show($"The number of performance counter categories in the local machine is {performanceCounterCategories.Length}"); - // - } - } -} +// +using PerformanceCounter performanceCounter = new PerformanceCounter(); +performanceCounter.CategoryName = "Process"; +performanceCounter.CounterName = "Private Bytes"; +performanceCounter.InstanceName = "Explorer"; +Console.WriteLine(performanceCounter.NextValue()); +// + +// +PerformanceCounterCategory[] performanceCounterCategories = PerformanceCounterCategory.GetCategories(); +Console.WriteLine($"The number of performance counter categories on the local computer is {performanceCounterCategories.Length}"); +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/Project.csproj b/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/Project.csproj +++ b/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/elapsedtime.cs b/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/elapsedtime.cs index a6b02ebaa7d..6d157571a2c 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/elapsedtime.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/elapsedtime.cs @@ -1,14 +1,12 @@ -// Notice that the sample is conditionally compiled for Everett vs. -// Whidbey builds. Whidbey introduced new APIs that are not available -// in Everett. Snippet IDs do not overlap between Whidbey and Everett; -// Snippet #1 is Everett, Snippet #2 and #3 are Whidbey. +// The sample is conditionally compiled for Everett and Whidbey builds. +// Whidbey introduced APIs that aren't available in Everett. +// Snippet IDs don't overlap: snippet 1 is Everett, and snippets 2 and 3 are Whidbey. #if (BELOW_WHIDBEY_BUILD) // using System; using System.Collections; -using System.Collections.Specialized; using System.Diagnostics; using System.Runtime.InteropServices; @@ -18,7 +16,7 @@ public class App public static void Main() { - ArrayList samplesList = new ArrayList(); + ArrayList samplesList = new(); SetupCategory(); CreateCounters(); @@ -29,10 +27,10 @@ private static bool SetupCategory() { if ( !PerformanceCounterCategory.Exists("ElapsedTimeSampleCategory") ) { - CounterCreationDataCollection CCDC = new CounterCreationDataCollection(); + CounterCreationDataCollection CCDC = new(); // Add the counter. - CounterCreationData ETimeData = new CounterCreationData(); + CounterCreationData ETimeData = new(); ETimeData.CounterType = PerformanceCounterType.ElapsedTime; ETimeData.CounterName = "ElapsedTimeSample"; CCDC.Add(ETimeData); @@ -75,8 +73,8 @@ private static void CollectSamples(ArrayList samplesList) // Output the values. if ((j % 10) == 9) { - Console.WriteLine("NextValue() = " + PC.NextValue().ToString()); - Console.WriteLine("Actual elapsed time = " + DateTime.Now.Subtract(Start).ToString()); + Console.WriteLine($"NextValue() = {PC.NextValue()}"); + Console.WriteLine($"Actual elapsed time = {DateTime.Now.Subtract(Start)}"); OutputSample(PC.NextSample()); samplesList.Add( PC.NextSample() ); } @@ -91,7 +89,7 @@ private static void CollectSamples(ArrayList samplesList) System.Threading.Thread.Sleep(50); } - Console.WriteLine("Elapsed time = " + DateTime.Now.Subtract(Start).ToString()); + Console.WriteLine($"Elapsed time = {DateTime.Now.Subtract(Start)}"); } private static void OutputSample(CounterSample s) @@ -118,101 +116,92 @@ private static void OutputSample(CounterSample s) #else // Build sample for Whidbey or higher. -// +// using System; -using System.Collections; -using System.Collections.Specialized; using System.Diagnostics; -using System.Runtime.InteropServices; +using System.Threading; public class App { - public static void Main() - { - CollectSamples(); - } + public static void Main() => CollectSamples(); public static void CollectSamples() { - const String categoryName = "ElapsedTimeSampleCategory"; - const String counterName = "ElapsedTimeSample"; + const string CategoryName = "ElapsedTimeSampleCategory"; + const string CounterName = "ElapsedTimeSample"; - // If the category does not exist, create the category and exit. - // Performance counters should not be created and immediately used. - // There is a latency time to enable the counters, they should be created - // prior to executing the application that uses the counters. + // If the category doesn't exist, create it and exit. + // Performance counters shouldn't be created and immediately used. + // The counters take time to become enabled. + // Create them before executing the application that uses them. // Execute this sample a second time to use the category. - if ( !PerformanceCounterCategory.Exists(categoryName) ) + if (!PerformanceCounterCategory.Exists(CategoryName)) { + CounterCreationData elapsedTimeData = new() + { + CounterType = PerformanceCounterType.ElapsedTime, + CounterName = CounterName + }; + CounterCreationDataCollection counterData = new() { elapsedTimeData }; - CounterCreationDataCollection CCDC = new CounterCreationDataCollection(); - - // Add the counter. - CounterCreationData ETimeData = new CounterCreationData(); - ETimeData.CounterType = PerformanceCounterType.ElapsedTime; - ETimeData.CounterName = counterName; - CCDC.Add(ETimeData); - // Create the category. - PerformanceCounterCategory.Create(categoryName, - "Demonstrates ElapsedTime performance counter usage.", - PerformanceCounterCategoryType.SingleInstance, CCDC); - // Return, rerun the application to make use of the new counters. + PerformanceCounterCategory.Create( + CategoryName, + "Demonstrates ElapsedTime performance counter usage.", + PerformanceCounterCategoryType.SingleInstance, + counterData); + // Return and rerun the application to use the new counters. return; } - else - { - Console.WriteLine("Category exists - {0}", categoryName); - } - // + Console.WriteLine($"Category exists - {CategoryName}"); + + // // Create the performance counter. - PerformanceCounter PC = new PerformanceCounter(categoryName, - counterName, - false); + using PerformanceCounter performanceCounter = new(CategoryName, CounterName, false); // Initialize the counter. - PC.RawValue = Stopwatch.GetTimestamp(); - // + performanceCounter.RawValue = Stopwatch.GetTimestamp(); + // - DateTime Start = DateTime.Now; + DateTime start = DateTime.Now; // Loop for the samples. for (int j = 0; j < 100; j++) { // Output the values. - if ((j % 10) == 9) + if (j % 10 == 9) { - Console.WriteLine("NextValue() = " + PC.NextValue().ToString()); - Console.WriteLine("Actual elapsed time = " + DateTime.Now.Subtract(Start).ToString()); - OutputSample(PC.NextSample()); + Console.WriteLine($"NextValue() = {performanceCounter.NextValue()}"); + Console.WriteLine($"Actual elapsed time = {DateTime.Now.Subtract(start)}"); + OutputSample(performanceCounter.NextSample()); } // Reset the counter on every 20th iteration. if (j % 20 == 0) { - PC.RawValue = Stopwatch.GetTimestamp(); - Start = DateTime.Now; + performanceCounter.RawValue = Stopwatch.GetTimestamp(); + start = DateTime.Now; } - System.Threading.Thread.Sleep(50); + Thread.Sleep(50); } - Console.WriteLine("Elapsed time = " + DateTime.Now.Subtract(Start).ToString()); + Console.WriteLine($"Elapsed time = {DateTime.Now.Subtract(start)}"); } - private static void OutputSample(CounterSample s) + private static void OutputSample(CounterSample sample) { Console.WriteLine("\r\n+++++++++++"); Console.WriteLine("Sample values - \r\n"); - Console.WriteLine(" BaseValue = " + s.BaseValue); - Console.WriteLine(" CounterFrequency = " + s.CounterFrequency); - Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp); - Console.WriteLine(" CounterType = " + s.CounterType); - Console.WriteLine(" RawValue = " + s.RawValue); - Console.WriteLine(" SystemFrequency = " + s.SystemFrequency); - Console.WriteLine(" TimeStamp = " + s.TimeStamp); - Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec); + Console.WriteLine($" BaseValue = {sample.BaseValue}"); + Console.WriteLine($" CounterFrequency = {sample.CounterFrequency}"); + Console.WriteLine($" CounterTimeStamp = {sample.CounterTimeStamp}"); + Console.WriteLine($" CounterType = {sample.CounterType}"); + Console.WriteLine($" RawValue = {sample.RawValue}"); + Console.WriteLine($" SystemFrequency = {sample.SystemFrequency}"); + Console.WriteLine($" TimeStamp = {sample.TimeStamp}"); + Console.WriteLine($" TimeStamp100nSec = {sample.TimeStamp100nSec}"); Console.WriteLine("++++++++++++++++++++++"); } } -// -#endif \ No newline at end of file +// +#endif diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/Program.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/Program.cs new file mode 100644 index 00000000000..d89bc3260eb --- /dev/null +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/Program.cs @@ -0,0 +1,3 @@ +PerfCounterCatCtorMod.Run(args); +PerfCounterCatDeleteMod.Run(args); +PerfCounterCatPropsMod.Run(args); diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/Project.csproj b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/Project.csproj +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatDelete.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatDelete.cs index 970c52a36d6..2389eda56b6 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatDelete.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatDelete.cs @@ -1,13 +1,11 @@ -// +// using System; using System.Diagnostics; -using Microsoft.VisualBasic; class PerfCounterCatDeleteMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; @@ -16,7 +14,7 @@ public static void Main(string[] args) { categoryName = args[0]; } - catch (Exception ex) + catch (Exception) { Console.WriteLine("Missing argument identifying category to be deleted."); } @@ -27,7 +25,7 @@ public static void Main(string[] args) if (PerformanceCounterCategory.Exists(categoryName)) { PerformanceCounterCategory.Delete(categoryName); - Console.WriteLine("Category \"{0}\" deleted from this computer.", categoryName); + Console.WriteLine($"Category \"{categoryName}\" deleted from this computer."); } else { @@ -36,10 +34,9 @@ public static void Main(string[] args) } catch (Exception ex) { - Console.WriteLine("Unable to delete " + - "category \"{0}\" from this computer:" + "\n" + ex.Message, categoryName); + Console.WriteLine($"Unable to delete category \"{categoryName}\" from this computer:\n{ex.Message}"); } } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatProps.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatProps.cs index 3ee84b8f2fa..6f30093cf0f 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatProps.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatProps.cs @@ -1,33 +1,32 @@ -// +// using System; using System.Diagnostics; -using Microsoft.VisualBasic; class PerfCounterCatPropsMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; string machineName = ""; PerformanceCounterCategory pcc = new PerformanceCounterCategory(); // Prompt for fields and set the corresponding properties. - while (categoryName.Length==0) + while (categoryName.Length == 0) { Console.Write("Please enter a non-blank category name: "); categoryName = Console.ReadLine().Trim(); - if (categoryName.Length>0) + if (categoryName.Length > 0) { pcc.CategoryName = categoryName; } } - while (machineName.Length==0) + + while (machineName.Length == 0) { Console.Write("Enter a non-blank computer name ['.' for local]: "); machineName = Console.ReadLine().Trim(); - if (machineName.Length>0) + if (machineName.Length > 0) { pcc.MachineName = machineName; } @@ -36,17 +35,16 @@ public static void Main(string[] args) // Display the properties of the PerformanceCounterCategory object. try { - Console.WriteLine(" Category: {0}", pcc.CategoryName); - Console.WriteLine(" Computer: {0}", pcc.MachineName); - Console.WriteLine(" Help text: {0}", pcc.CategoryHelp); + Console.WriteLine($" Category: {pcc.CategoryName}"); + Console.WriteLine($" Computer: {pcc.MachineName}"); + Console.WriteLine($" Help text: {pcc.CategoryHelp}"); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("Error getting the properties of the " + - "PerformanceCounterCategory object:"); + Console.WriteLine("Error getting the properties of the PerformanceCounterCategory object:"); Console.WriteLine(ex.Message); } } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfcountercatctor.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfcountercatctor.cs index 381770ae702..5b6fbb9837b 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfcountercatctor.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfcountercatctor.cs @@ -1,58 +1,46 @@ -// +// using System; using System.Diagnostics; -using Microsoft.VisualBasic; class PerfCounterCatCtorMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; string machineName = ""; - PerformanceCounterCategory pcc; // Copy the supplied arguments into the local variables. try { categoryName = args[0]; - machineName = args[1]=="."? "": args[1]; + machineName = args[1] == "." ? "" : args[1]; } - catch(Exception ex) + catch (Exception) { // Ignore the exception from non-supplied arguments. } - // Create a PerformanceCounterCategory object using - // the appropriate constructor. - if (categoryName.Length==0) - { - pcc = new PerformanceCounterCategory(); - } - else if(machineName.Length==0) - { - pcc = new PerformanceCounterCategory(categoryName); - } - else - { - pcc = new PerformanceCounterCategory(categoryName, machineName); - } + // Create a PerformanceCounterCategory object using the appropriate constructor. + PerformanceCounterCategory pcc = categoryName.Length == 0 + ? new PerformanceCounterCategory() + : machineName.Length == 0 + ? new PerformanceCounterCategory(categoryName) + : new PerformanceCounterCategory(categoryName, machineName); // Display the properties of the PerformanceCounterCategory object. try { - Console.WriteLine(" Category: {0}", pcc.CategoryName); - Console.WriteLine(" Computer: {0}", pcc.MachineName); - Console.WriteLine(" Help text: {0}", pcc.CategoryHelp); + Console.WriteLine($" Category: {pcc.CategoryName}"); + Console.WriteLine($" Computer: {pcc.MachineName}"); + Console.WriteLine($" Help text: {pcc.CategoryHelp}"); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("Error getting the properties of the " + - "PerformanceCounterCategory object:"); + Console.WriteLine("Error getting the properties of the PerformanceCounterCategory object:"); Console.WriteLine(ex.Message); } } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/Program.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/Program.cs new file mode 100644 index 00000000000..8986ea5c935 --- /dev/null +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/Program.cs @@ -0,0 +1,5 @@ +PerfCounterCatObjCountExistsMod.Run(args); +PerfCounterCatStatCountExistsMod.Run(args); +PerfCounterCatStatInstExistsMod.Run(args); +PerfCounterCatObjInstExistsMod.Run(args); +PerfCounterCatDeleteMod.Run(args); diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/Project.csproj b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/Project.csproj +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/percounterexists.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/percounterexists.cs index 1954a802820..4d3ee724083 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/percounterexists.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/percounterexists.cs @@ -1,13 +1,11 @@ -// +// using System; using System.Diagnostics; -using Microsoft.VisualBasic; class PerfCounterCatDeleteMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; @@ -16,7 +14,7 @@ public static void Main(string[] args) { categoryName = args[0]; } - catch(Exception ex) + catch (Exception) { } @@ -24,14 +22,13 @@ public static void Main(string[] args) try { PerformanceCounterCategory.Delete(categoryName); - Console.WriteLine("Category \"{0}\" deleted from this computer.", categoryName); + Console.WriteLine($"Category \"{categoryName}\" deleted from this computer."); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("Unable to delete " + - "category \"{0}\" from this computer:"+ "\n" + ex.Message, categoryName); + Console.WriteLine($"Unable to delete category \"{categoryName}\" from this computer:\n{ex.Message}"); } } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatobjexists.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatobjexists.cs index cefc31adafa..727d8c7a00d 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatobjexists.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatobjexists.cs @@ -1,61 +1,48 @@ -// +// using System; using System.Diagnostics; -using Microsoft.VisualBasic; class PerfCounterCatObjCountExistsMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; string counterName = ""; string machineName = ""; - bool objectExists = false; - PerformanceCounterCategory pcc; // Copy the supplied arguments into the local variables. try { categoryName = args[0]; counterName = args[1]; - machineName = (args[2]=="."? "": args[2]); + machineName = args[2] == "." ? "" : args[2]; } - catch(Exception ex) + catch (Exception) { // Ignore the exception from non-supplied arguments. } try { - if (machineName.Length==0) - { - pcc = new PerformanceCounterCategory(categoryName); - } - else - { - pcc = new PerformanceCounterCategory(categoryName, machineName); - } + PerformanceCounterCategory pcc = machineName.Length == 0 + ? new(categoryName) + : new(categoryName, machineName); // Check whether the specified counter exists. // Use the per-instance overload of CounterExists. - objectExists = pcc.CounterExists(counterName); + bool objectExists = pcc.CounterExists(counterName); + + // Tell the user whether the counter exists. + string location = machineName.Length > 0 ? $"computer \"{pcc.MachineName}\"." : "this computer."; + Console.WriteLine($"Counter \"{counterName}\" {(objectExists ? "exists" : "does not exist")} in category \"{pcc.CategoryName}\" on {location}"); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("Unable to check for the existence of " + - "counter \"{0}\" in category \"{1}\" on "+ - (machineName.Length>0? "computer \"{2}\".": "this computer.")+ "\n" + - ex.Message, counterName, categoryName, machineName); - return; + string location = machineName.Length > 0 ? $"computer \"{machineName}\"." : "this computer."; + Console.WriteLine($"Unable to check for the existence of counter \"{counterName}\" in category \"{categoryName}\" on {location}\n{ex.Message}"); } - - // Tell the user whether the counter exists. - Console.WriteLine("Counter \"{0}\" " + (objectExists? "exists": "does not exist") + - " in category \"{1}\" on " + (machineName.Length>0? "computer \"{2}\".": "this computer."), - counterName, pcc.CategoryName, pcc.MachineName); } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatstatcounterexists.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatstatcounterexists.cs index f19f8aa0836..3f595b92bcb 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatstatcounterexists.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatstatcounterexists.cs @@ -1,27 +1,24 @@ -// +// using System; using System.Diagnostics; -using Microsoft.VisualBasic; class PerfCounterCatStatCountExistsMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; string counterName = ""; string machineName = ""; - bool objectExists = false; // Copy the supplied arguments into the local variables. try { categoryName = args[0]; counterName = args[1]; - machineName = args[2]=="."? "": args[2]; + machineName = args[2] == "." ? "" : args[2]; } - catch(Exception ex) + catch (Exception) { // Ignore the exception from non-supplied arguments. } @@ -30,29 +27,20 @@ public static void Main(string[] args) { // Check whether the specified counter exists. // Use the static forms of the CounterExists method. - if (machineName.Length==0) - { - objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName); - } - else - { - objectExists = PerformanceCounterCategory.CounterExists(counterName, categoryName, machineName); - } + bool objectExists = machineName.Length == 0 + ? PerformanceCounterCategory.CounterExists(counterName, categoryName) + : PerformanceCounterCategory.CounterExists(counterName, categoryName, machineName); + + // Tell the user whether the counter exists. + string location = machineName.Length > 0 ? $"computer \"{machineName}\"." : "this computer."; + Console.WriteLine($"Counter \"{counterName}\" {(objectExists ? "exists" : "does not exist")} in category \"{categoryName}\" on {location}"); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("Unable to check for the existence of " + - "counter \"{0}\" in category \"{1}\" on " + - (machineName.Length>0? "computer \"{2}\".": "this computer.") + "\n" + - ex.Message, counterName, categoryName, machineName); - return; + string location = machineName.Length > 0 ? $"computer \"{machineName}\"." : "this computer."; + Console.WriteLine($"Unable to check for the existence of counter \"{counterName}\" in category \"{categoryName}\" on {location}\n{ex.Message}"); } - - // Tell the user whether the counter exists. - Console.WriteLine("Counter \"{0}\" "+ (objectExists? "exists": "does not exist") + - " in category \"{1}\" on " + (machineName.Length>0? "computer \"{2}\".": "this computer."), - counterName, categoryName, machineName); } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatstatinstexists.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatstatinstexists.cs index 6f65e768d66..fe44e88977f 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatstatinstexists.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcountercatstatinstexists.cs @@ -1,65 +1,53 @@ -// +// using System; using System.Diagnostics; -using Microsoft.VisualBasic; class PerfCounterCatStatInstExistsMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; string instanceName = ""; string machineName = ""; - bool objectExists = false; - const string SINGLE_INSTANCE_NAME = "systemdiagnosticsperfcounterlibsingleinstance"; + const string SingleInstanceName = "systemdiagnosticsperfcounterlibsingleinstance"; // Copy the supplied arguments into the local variables. try { categoryName = args[0]; instanceName = args[1]; - machineName = args[2]=="."? "": args[2]; + machineName = args[2] == "." ? "" : args[2]; } - catch(Exception ex) + catch (Exception) { // Ignore the exception from non-supplied arguments. } - // Use the given instance name or use the default single-instance name. - if (instanceName.Length==0) + // Use the given instance name or the default single-instance name. + if (instanceName.Length == 0) { - instanceName = SINGLE_INSTANCE_NAME; + instanceName = SingleInstanceName; } try { // Check whether the specified instance exists. // Use the static forms of the InstanceExists method. - if (machineName.Length==0) - { - objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName); - } - else - { - objectExists = PerformanceCounterCategory.InstanceExists(instanceName, categoryName, machineName); - } + bool objectExists = machineName.Length == 0 + ? PerformanceCounterCategory.InstanceExists(instanceName, categoryName) + : PerformanceCounterCategory.InstanceExists(instanceName, categoryName, machineName); + + // Tell the user whether the instance exists. + string location = machineName.Length > 0 ? $"computer \"{machineName}\"." : "this computer."; + Console.WriteLine($"Instance \"{instanceName}\" {(objectExists ? "exists" : "does not exist")} in category \"{categoryName}\" on {location}"); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("Unable to check for the existence of " + - "instance \"{0}\" in category \"{1}\" on " + - (machineName.Length>0? "computer \"{2}\":": "this computer:") + "\n" + - ex.Message, instanceName, categoryName, machineName); - return; + string location = machineName.Length > 0 ? $"computer \"{machineName}\":" : "this computer:"; + Console.WriteLine($"Unable to check for the existence of instance \"{instanceName}\" in category \"{categoryName}\" on {location}\n{ex.Message}"); } - - // Tell the user whether the instance exists. - Console.WriteLine("Instance \"{0}\" " + (objectExists? "exists": "does not exist") + - " in category \"{1}\" on " + (machineName.Length>0? "computer \"{2}\".": "this computer."), - instanceName, categoryName, machineName); } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcounterobjinstexists.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcounterobjinstexists.cs index 4234dfd76ca..7393b69648d 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcounterobjinstexists.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/CounterExists/perfcounterobjinstexists.cs @@ -1,68 +1,55 @@ -// +// using System; using System.Diagnostics; -using Microsoft.VisualBasic; class PerfCounterCatObjInstExistsMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; string instanceName = ""; string machineName = ""; - bool objectExists = false; - PerformanceCounterCategory pcc; - const string SINGLE_INSTANCE_NAME = "systemdiagnosticsperfcounterlibsingleinstance"; + const string SingleInstanceName = "systemdiagnosticsperfcounterlibsingleinstance"; // Copy the supplied arguments into the local variables. try { categoryName = args[0]; instanceName = args[1]; - machineName = (args[2]=="."? "": args[2]); + machineName = args[2] == "." ? "" : args[2]; } - catch(Exception ex) + catch (Exception) { // Ignore the exception from non-supplied arguments. } - // Use the given instance name or use the default single-instance name. - if (instanceName.Length==0) + // Use the given instance name or the default single-instance name. + if (instanceName.Length == 0) { - instanceName = SINGLE_INSTANCE_NAME; + instanceName = SingleInstanceName; } try { - if (machineName.Length==0) - { - pcc = new PerformanceCounterCategory(categoryName); - } - else - { - pcc = new PerformanceCounterCategory(categoryName, machineName); - } + PerformanceCounterCategory pcc = machineName.Length == 0 + ? new(categoryName) + : new(categoryName, machineName); // Check whether the instance exists. // Use the per-instance overload of InstanceExists. - objectExists = pcc.InstanceExists(instanceName); + bool objectExists = pcc.InstanceExists(instanceName); + + // Tell the user whether the instance exists. + string location = machineName.Length > 0 ? $"computer \"{pcc.MachineName}\"." : "this computer."; + Console.WriteLine($"Instance \"{instanceName}\" {(objectExists ? "exists" : "does not exist")} in category \"{pcc.CategoryName}\" on {location}"); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("Unable to check for the existence of " + - "instance \"{0}\" in category \"{1}\" on " + - (machineName.Length>0? "computer \"{2}\":": "this computer:") + - "\n" + ex.Message, instanceName, categoryName, machineName); - return; + string location = machineName.Length > 0 ? $"computer \"{machineName}\":" : "this computer:"; + Console.WriteLine($"Unable to check for the existence of instance \"{instanceName}\" in category \"{categoryName}\" on {location}\n{ex.Message}"); } - - // Tell the user whether the instance exists. - Console.WriteLine("Instance \"{0}\" " + (objectExists? "exists": "does not exist") + - " in category \"{1}\" on " + (machineName.Length>0? "computer \"{2}\".": "this computer."), - instanceName, pcc.CategoryName, pcc.MachineName); } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/Project.csproj b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/Project.csproj +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/ccd.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/ccd.cs index 338618a9c7a..d422bac6343 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/ccd.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/ccd.cs @@ -1,29 +1,34 @@ -using System; -using System.Diagnostics; +using System.Diagnostics; public class Snippet { - public static void Main() + public static void Run() { - - // + // if (!PerformanceCounterCategory.Exists("Orders")) { - CounterCreationData milk = new CounterCreationData(); - milk.CounterName = "milk"; - milk.CounterType = PerformanceCounterType.NumberOfItems32; - - CounterCreationData milkPerSecond = new CounterCreationData(); - milkPerSecond.CounterName = "milk orders/second"; - milkPerSecond.CounterType = PerformanceCounterType.RateOfCountsPerSecond32; - - CounterCreationDataCollection ccds = new CounterCreationDataCollection(); - ccds.Add(milkPerSecond); - ccds.Add(milk); + CounterCreationData milk = new() + { + CounterName = "milk", + CounterType = PerformanceCounterType.NumberOfItems32 + }; + CounterCreationData milkPerSecond = new() + { + CounterName = "milk orders/second", + CounterType = PerformanceCounterType.RateOfCountsPerSecond32 + }; + CounterCreationDataCollection counterData = new() + { + milkPerSecond, + milk + }; - PerformanceCounterCategory.Create("Orders", "Number of processed orders", - PerformanceCounterCategoryType.SingleInstance, ccds); + PerformanceCounterCategory.Create( + "Orders", + "Number of processed orders", + PerformanceCounterCategoryType.SingleInstance, + counterData); } - // + // } -} \ No newline at end of file +} diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs index 233e4733841..69e2ea5b1be 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs @@ -1,18 +1,14 @@ -// +// using System; -using System.Text; -using System.Timers; -using System.Threading; -using Microsoft.Win32; -using System.Reflection; using System.Diagnostics; -using System.Globalization; +using System.Threading; +using System.Timers; public class PerfCounter1 { [STAThread] - public static void Main(string[] args) + public static void Run(string[] args) { try { @@ -20,17 +16,17 @@ public static void Main(string[] args) { // If the category does not exist, create the category and exit. // Performance counters should not be created and immediately used. - // There is a latency time to enable the counters, they should be created - // prior to executing the application that uses the counters. + // The counters take time to become enabled. + // Create them before executing the application that uses them. // Create custom counters. Writer.CreateCounters(); return; } - Writer server = new Writer(); + Writer server = new(); // Start the counters. server.StartCounters(); - Reader client = new Reader(); + Reader client = new(); // Read the counters from the client. client.StartCounters(); server.CloseTimer(); @@ -41,13 +37,13 @@ public static void Main(string[] args) } catch (Exception e) { - Console.WriteLine("Sample failed with exception: " + e.ToString()); + Console.WriteLine($"Sample failed with exception: {e}"); } } public class Writer { - private System.Timers.Timer timer1; + private readonly System.Timers.Timer timer1; private PerformanceCounter counter1; private PerformanceCounter counter2; private PerformanceCounter counter3; @@ -56,70 +52,74 @@ public class Writer public Writer() { - this.timer1 = new System.Timers.Timer(100); - this.finalCount = 0; - timer1.Elapsed += new ElapsedEventHandler(this.OnTimer1); + timer1 = new(100); + finalCount = 0; + timer1.Elapsed += OnTimer1; } - // + // public static void CreateCounters() { - // - CounterCreationData data1 = new CounterCreationData("Trucks", + // + CounterCreationData data1 = new("Trucks", "Number of orders", PerformanceCounterType.NumberOfItems32); - CounterCreationData data2 = new CounterCreationData("Rate of sales", + CounterCreationData data2 = new("Rate of sales", "Orders/second", PerformanceCounterType.RateOfCountsPerSecond32); - CounterCreationDataCollection ccds = new CounterCreationDataCollection(); + CounterCreationDataCollection ccds = new(); ccds.Add(data1); ccds.Add(data2); Console.WriteLine("Creating Orders custom counter."); if (!PerformanceCounterCategory.Exists("Orders")) + { PerformanceCounterCategory.Create("Orders", "Processed orders", PerformanceCounterCategoryType.MultiInstance, ccds); - // + } + // - // + // Console.WriteLine("Creating Inventory custom counter"); if (!PerformanceCounterCategory.Exists("Inventory")) + { PerformanceCounterCategory.Create("Inventory", "Truck inventory", PerformanceCounterCategoryType.SingleInstance, "Trucks", "Number of trucks on hand"); - // + } + // } - // + // public void StartCounters() { Console.WriteLine( "Instantiating Custom Counter Orders, Trucks, United States"); - this.counter1 = new PerformanceCounter( + counter1 = new PerformanceCounter( "Orders", "Trucks", "United States", false); - this.counter1.RawValue = 5; + counter1.RawValue = 5; Console.WriteLine( "Instantiating Custom Counter Orders, Trucks, Europe"); - this.counter2 = new PerformanceCounter( + counter2 = new PerformanceCounter( "Orders", "Trucks", "Europe", false); - this.counter2.RawValue = 10; + counter2.RawValue = 10; Console.WriteLine( "Instantiating Custom Counter Orders, Rate of Sales, Total"); - this.counter3 = new PerformanceCounter( + counter3 = new PerformanceCounter( "Orders", "Rate of Sales", "Total", false); - this.counter3.RawValue = 10; + counter3.RawValue = 10; Console.WriteLine( "Instantiating Custom Counter Inventory, Trucks"); - this.counter4 = new PerformanceCounter( + counter4 = new PerformanceCounter( "Inventory", "Trucks", false); - this.counter4.RawValue = 15; + counter4.RawValue = 15; - this.timer1.Start(); + timer1.Start(); } public void CloseTimer() { - this.timer1.Close(); + timer1.Close(); } public static void DeleteCounters() @@ -131,7 +131,7 @@ public static void DeleteCounters() } catch (Exception e) { - Console.WriteLine(e.ToString()); + Console.WriteLine(e); } } @@ -139,25 +139,25 @@ private void OnTimer1(object sender, ElapsedEventArgs args) { try { - this.counter1.IncrementBy(100); - this.counter1.Increment(); - this.counter2.IncrementBy(50); - this.counter2.Decrement(); - this.counter3.IncrementBy(1); - this.counter4.IncrementBy(150); - ++this.finalCount; + counter1.IncrementBy(100); + counter1.Increment(); + counter2.IncrementBy(50); + counter2.Decrement(); + counter3.IncrementBy(1); + counter4.IncrementBy(150); + ++finalCount; } catch (Exception e) { - Console.WriteLine("Unexpected exception thrown :" + e.ToString()); + Console.WriteLine($"Unexpected exception thrown :{e}"); } } } public class Reader { - private ManualResetEvent signal; - private System.Timers.Timer timer1; + private readonly ManualResetEvent signal; + private readonly System.Timers.Timer timer1; private PerformanceCounter counter1; private PerformanceCounter counter2; private PerformanceCounter counter3; @@ -166,16 +166,16 @@ public class Reader public Reader() { - signal = new ManualResetEvent(false); - this.timer1 = new System.Timers.Timer(500); - this.finalCount = 0; - timer1.Elapsed += new ElapsedEventHandler(this.OnTimer1); + signal = new(false); + timer1 = new(500); + finalCount = 0; + timer1.Elapsed += OnTimer1; } public void Finish() { - this.signal.WaitOne(); - this.timer1.Close(); + signal.WaitOne(); + timer1.Close(); PerformanceCounter.CloseSharedResources(); } @@ -185,40 +185,40 @@ private void OnTimer1(object sender, ElapsedEventArgs args) { lock (this) { - if (this.finalCount >= 10) + if (finalCount >= 10) return; - float value1 = this.counter1.NextValue(); + float value1 = counter1.NextValue(); Console.WriteLine( - "Custom Counter Orders, Trucks, United States: {0}", value1.ToString()); + "Custom Counter Orders, Trucks, United States: {0}", value1); - float value2 = this.counter2.NextValue(); + float value2 = counter2.NextValue(); Console.WriteLine( - "Custom Counter Orders, Trucks, Europe: {0}", value2.ToString()); + "Custom Counter Orders, Trucks, Europe: {0}", value2); - float value3 = this.counter3.NextValue(); + float value3 = counter3.NextValue(); Console.WriteLine( - "Custom Counter Orders, Rate of sales, United Total: {0}", value3.ToString()); + "Custom Counter Orders, Rate of sales, United Total: {0}", value3); - float value4 = this.counter4.NextValue(); + float value4 = counter4.NextValue(); Console.WriteLine( - "Custom Counter Inventory, Trucks, United States: {0}", value4.ToString()); + "Custom Counter Inventory, Trucks, United States: {0}", value4); - if (this.finalCount < 5) + if (finalCount < 5) { - ++this.finalCount; + ++finalCount; } else { - ++this.finalCount; - this.signal.Set(); + ++finalCount; + signal.Set(); } } } catch (Exception e) { - Console.WriteLine("Sample failure :" + e.ToString()); - this.signal.Set(); + Console.WriteLine($"Sample failure :{e}"); + signal.Set(); } } @@ -226,24 +226,33 @@ public void StartCounters() { Console.WriteLine( "Instantiating Custom Counter Orders, Trucks, United States"); - // Instantiate a counter, category "Orders, counter name "Trucks", instance "United States" - this.counter1 = new PerformanceCounter( + // Instantiate a counter with category "Orders", counter name "Trucks", and instance "United States". + counter1 = new PerformanceCounter( "Orders", "Trucks", "United States"); Console.WriteLine("Instantiating Custom Counter Orders, Trucks, Europe"); - // Instantiate a counter, category "Orders, counter name "Trucks", instance "Europe" - this.counter2 = new PerformanceCounter( + // Instantiate a counter with category "Orders", counter name "Trucks", and instance "Europe". + counter2 = new PerformanceCounter( "Orders", "Trucks", "Europe"); Console.WriteLine("Instantiating Custom Counter Orders, Rate of Sales."); - // Instantiate a counter, category "Orders", counter name "Rate of Sales", single instance. - this.counter3 = new PerformanceCounter( + // Instantiate a counter with category "Orders", counter name "Rate of Sales", and a single instance. + counter3 = new PerformanceCounter( "Orders", "Rate of Sales", "Total"); Console.WriteLine("Instantiating Custom Counter Inventory, Trucks, Only instance."); // Instantiate a single instance counter, category "Inventory", counter name "Trucks". - this.counter4 = new PerformanceCounter( + counter4 = new PerformanceCounter( "Inventory", "Trucks", false); - this.timer1.Start(); + timer1.Start(); } } } -// +// +public static class Program +{ + public static void Main(string[] args) + { + Snippet.Run(); + PerformanceCounterCategory.Delete("Orders"); + PerfCounter1.Run(args); + } +} diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/Program.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/Program.cs new file mode 100644 index 00000000000..1a36584439f --- /dev/null +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/Program.cs @@ -0,0 +1,4 @@ +PerfCounterCatGetCountMod.Run(args); +PerfCounterCatGetInstMod.Run(args); +string[] machineArgs = args.Length > 1 ? [args[1]] : []; +PerfCounterCatGetCatMod.Run(machineArgs); diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/Project.csproj b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/Project.csproj +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountercatgetcount.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountercatgetcount.cs index e338992768c..339e9b8cc2f 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountercatgetcount.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountercatgetcount.cs @@ -1,80 +1,66 @@ -// +// using System; using System.Diagnostics; class PerfCounterCatGetCountMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; string machineName = ""; string instanceName = ""; - PerformanceCounterCategory pcc; - PerformanceCounter[] counters; // Copy the supplied arguments into the local variables. try { categoryName = args[0]; - machineName = args[1]=="."? "": args[1]; + machineName = args[1] == "." ? "" : args[1]; instanceName = args[2]; } - catch + catch (Exception) { // Ignore the exception from non-supplied arguments. } + PerformanceCounter[] counters; try { // Create the appropriate PerformanceCounterCategory object. - if (machineName.Length>0) - { - pcc = new PerformanceCounterCategory(categoryName, machineName); - } - else - { - pcc = new PerformanceCounterCategory(categoryName); - } + PerformanceCounterCategory pcc = machineName.Length > 0 + ? new(categoryName, machineName) + : new(categoryName); - // Get the counters for this instance or a single instance - // of the selected category. - if (instanceName.Length>0) - { - counters = pcc.GetCounters(instanceName); - } - else - { - counters = pcc.GetCounters(); - } + // Get the counters for this instance or a single instance of the selected category. + counters = instanceName.Length > 0 + ? pcc.GetCounters(instanceName) + : pcc.GetCounters(); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("Unable to get counter information for " + - (instanceName.Length>0? "instance \"{2}\" in ": "single-instance ") + - "category \"{0}\" on " + (machineName.Length>0? "computer \"{1}\":": "this computer:"), - categoryName, machineName, instanceName); + string categoryDescription = instanceName.Length > 0 + ? $"instance \"{instanceName}\" in category" + : "single-instance category"; + string location = machineName.Length > 0 ? $"computer \"{machineName}\":" : "this computer:"; + Console.WriteLine($"Unable to get counter information for {categoryDescription} \"{categoryName}\" on {location}"); Console.WriteLine(ex.Message); return; } // Display the counter names if GetCounters was successful. - if (counters!=null) - { - Console.WriteLine("These counters exist in " + - (instanceName.Length>0? "instance \"{1}\" of": "single instance") + - " category {0} on " + (machineName.Length>0? "computer \"{2}\":": "this computer:"), - categoryName, instanceName, machineName); + string counterDescription = instanceName.Length > 0 + ? $"instance \"{instanceName}\" of" + : "single instance"; + string registeredLocation = machineName.Length > 0 ? $"computer \"{machineName}\":" : "this computer:"; + Console.WriteLine($"These counters exist in {counterDescription} category {categoryName} on {registeredLocation}"); - // Display a numbered list of the counter names. - int objX; - for(objX=0; objX + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountercatgetinst.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountercatgetinst.cs index 026eba5523f..efabc5cff92 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountercatgetinst.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountercatgetinst.cs @@ -1,25 +1,22 @@ -// +// using System; using System.Diagnostics; class PerfCounterCatGetInstMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string categoryName = ""; string machineName = ""; - PerformanceCounterCategory pcc; - string[] instances; // Copy the supplied arguments into the local variables. try { categoryName = args[0]; - machineName = args[1]=="."? "": args[1]; + machineName = args[1] == "." ? "" : args[1]; } - catch + catch (Exception) { // Ignore the exception from non-supplied arguments. } @@ -27,50 +24,38 @@ public static void Main(string[] args) try { // Create the appropriate PerformanceCounterCategory object. - if (machineName.Length>0) - { - pcc = new PerformanceCounterCategory(categoryName, machineName); - } - else - { - pcc = new PerformanceCounterCategory(categoryName); - } + PerformanceCounterCategory pcc = machineName.Length > 0 + ? new(categoryName, machineName) + : new(categoryName); // Get the instances associated with this category. - instances = pcc.GetInstanceNames(); - } - catch(Exception ex) - { - Console.WriteLine("Unable to get instance information for " + - "category \"{0}\" on " + - (machineName.Length>0? "computer \"{1}\":": "this computer:"), - categoryName, machineName); - Console.WriteLine(ex.Message); - return; - } + string[] instances = pcc.GetInstanceNames(); + + // If an empty array is returned, the category has a single instance. + if (instances.Length == 0) + { + string location = machineName.Length > 0 ? $"computer \"{pcc.MachineName}\"" : "this computer"; + Console.WriteLine($"Category \"{pcc.CategoryName}\" on {location} is single-instance."); + return; + } - //If an empty array is returned, the category has a single instance. - if (instances.Length==0) - { - Console.WriteLine("Category \"{0}\" on " + - (machineName.Length>0? "computer \"{1}\"": "this computer") + - " is single-instance.", pcc.CategoryName, pcc.MachineName); - } - else - { // Otherwise, display the instances. - Console.WriteLine("These instances exist in category \"{0}\" on " + - (machineName.Length>0? "computer \"{1}\".": "this computer:"), - pcc.CategoryName, pcc.MachineName); + string registeredLocation = machineName.Length > 0 ? $"computer \"{pcc.MachineName}\"." : "this computer:"; + Console.WriteLine($"These instances exist in category \"{pcc.CategoryName}\" on {registeredLocation}"); Array.Sort(instances); - int objX; - for(objX=0; objX 0 ? $"computer \"{machineName}\":" : "this computer:"; + Console.WriteLine($"Unable to get instance information for category \"{categoryName}\" on {location}"); + Console.WriteLine(ex.Message); + } } - // + // } -// +// diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountergetcat.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountergetcat.cs index e62e53c7539..63471cb9ecc 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountergetcat.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/GetCategories/perfcountergetcat.cs @@ -1,62 +1,55 @@ -// +// using System; using System.Diagnostics; class PerfCounterCatGetCatMod { - - // - public static void Main(string[] args) + // + public static void Run(string[] args) { string machineName = ""; - PerformanceCounterCategory[] categories; // Copy the machine name argument into the local variable. try { - machineName = args[0]=="."? "": args[0]; + machineName = args[0] == "." ? "" : args[0]; } - catch + catch (Exception) { } // Generate a list of categories registered on the specified computer. + PerformanceCounterCategory[] categories; try { - if (machineName.Length > 0) - { - categories = PerformanceCounterCategory.GetCategories(machineName); - } - else - { - categories = PerformanceCounterCategory.GetCategories(); - } + categories = machineName.Length > 0 + ? PerformanceCounterCategory.GetCategories(machineName) + : PerformanceCounterCategory.GetCategories(); } - catch(Exception ex) + catch (Exception ex) { - Console.WriteLine("Unable to get categories on " + - (machineName.Length > 0 ? "computer \"{0}\":": "this computer:"), machineName); + string location = machineName.Length > 0 ? $"computer \"{machineName}\":" : "this computer:"; + Console.WriteLine($"Unable to get categories on {location}"); Console.WriteLine(ex.Message); return; } - Console.WriteLine("These categories are registered on " + - (machineName.Length > 0 ? "computer \"{0}\":": "this computer:"), machineName); + string registeredLocation = machineName.Length > 0 ? $"computer \"{machineName}\":" : "this computer:"; + Console.WriteLine($"These categories are registered on {registeredLocation}"); // Create and sort an array of category names. string[] categoryNames = new string[categories.Length]; - int objX; - for(objX = 0; objX < categories.Length; objX++) + for (int i = 0; i < categories.Length; i++) { - categoryNames[objX] = categories[objX].CategoryName; + categoryNames[i] = categories[i].CategoryName; } Array.Sort(categoryNames); - for(objX = 0; objX < categories.Length; objX++) + for (int i = 0; i < categories.Length; i++) { - Console.WriteLine("{0,4} - {1}", objX + 1, categoryNames[objX]); + Console.WriteLine($"{i + 1,4} - {categoryNames[i]}"); } } - // + // } -// +// From 2e791f77f1382db5f179570a84c59c157700009c Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 25 Aug 2026 10:32:23 -0700 Subject: [PATCH 2/6] Apply suggestions from code review Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .../EventLog/WriteEntry/eventlog_writeentry_4.cs | 2 +- .../EventLog/WriteEntry/eventlog_writeentry_5.cs | 2 +- .../csharp/System.Diagnostics/EventLog/WriteEntry/source.cs | 2 +- .../EventLogEntryCollection/Count/eventlogentry_item.cs | 2 +- .../EventLogEntryCollection/Overview/eventlogentry_copyto.cs | 2 +- .../EventLogEntryType/Overview/eventlogentrytype_6.cs | 2 +- .../EventSourceCreationData/Overview/source.cs | 2 +- .../PerformanceCounterCategory/Create/program.cs | 2 -- 8 files changed, 7 insertions(+), 9 deletions(-) diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_4.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_4.cs index 5ca15b48595..dac8ff67888 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_4.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_4.cs @@ -22,7 +22,7 @@ public static void Run() { // An event log source shouldn't be created and immediately used. // The source takes time to become enabled. - // Create it before executing the application that uses it. + // Create it before executing the application that uses it. // Execute this sample a second time to use the new source. EventLog.CreateEventSource("MySource", "myNewLog"); Console.WriteLine("Creating EventSource"); diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_5.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_5.cs index 9cd8ee6825a..386be01bf87 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_5.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/eventlog_writeentry_5.cs @@ -26,7 +26,7 @@ public static void Run() { // An event log source shouldn't be created and immediately used. // The source takes time to become enabled. - // Create it before executing the application that uses it. + // Create it before executing the application that uses it. // Execute this sample a second time to use the new source. EventLog.CreateEventSource("MySource", myLogName); Console.WriteLine("Created EventSource"); diff --git a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source.cs b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source.cs index 0ebbe774bbb..e208a80ee02 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/WriteEntry/source.cs @@ -11,7 +11,7 @@ public static void Run() { // An event log source shouldn't be created and immediately used. // The source takes time to become enabled. - // Create it before executing the application that uses it. + // Create it before executing the application that uses it. // Execute this sample a second time to use the new source. EventLog.CreateEventSource("MySource", "myNewLog"); Console.WriteLine("CreatingEventSource"); diff --git a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/eventlogentry_item.cs b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/eventlogentry_item.cs index cf7ea5355a8..8e58956406b 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/eventlogentry_item.cs +++ b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Count/eventlogentry_item.cs @@ -22,7 +22,7 @@ the count and messages are displayed. // Create the source. // An event log source shouldn't be created and immediately used. // The source takes time to become enabled. - // Create it before executing the application that uses it. + // Create it before executing the application that uses it. // Execute this sample a second time to use the new source. EventLog.CreateEventSource("MySource", myLogName); Console.WriteLine("Creating EventSource"); diff --git a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/eventlogentry_copyto.cs b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/eventlogentry_copyto.cs index 1df0d523d2f..972ca9231da 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/eventlogentry_copyto.cs +++ b/snippets/csharp/System.Diagnostics/EventLogEntryCollection/Overview/eventlogentry_copyto.cs @@ -22,7 +22,7 @@ to an array. // Create the source. // An event log source shouldn't be created and immediately used. // The source takes time to become enabled. - // Create it before executing the application that uses it. + // Create it before executing the application that uses it. // Execute this sample a second time to use the new source. EventLog.CreateEventSource("MySource", myLogName); Console.WriteLine("Creating EventSource"); diff --git a/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/eventlogentrytype_6.cs b/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/eventlogentrytype_6.cs index e4e83b775f7..59a6d7cc9d6 100644 --- a/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/eventlogentrytype_6.cs +++ b/snippets/csharp/System.Diagnostics/EventLogEntryType/Overview/eventlogentrytype_6.cs @@ -28,7 +28,7 @@ // Create a new source in a specified log on a system. // An event log source shouldn't be created and immediately used. // The source takes time to become enabled. - // Create it before executing the application that uses it. + // Create it before executing the application that uses it. // Execute this sample a second time to use the new source. EventLog.CreateEventSource(mySource, myLog); Console.WriteLine("Creating the event source, press the Enter key to exit the application, \n" + diff --git a/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs b/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs index abcb9504969..3a6884e9489 100644 --- a/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs +++ b/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs @@ -78,7 +78,7 @@ static void Main(string[] args) // To set the message and register the source remotely, use system-wide environment variables. // Use variables that are valid on that computer, such as "%SystemRoot%\system32\myresource.dll". Console.WriteLine("Message resource file ignored for remote event log."); - registerSource = false; + mySourceData.MessageResourceFile = string.Empty; } } } diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs index 69e2ea5b1be..cf22d6defbc 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs @@ -251,8 +251,6 @@ public static class Program { public static void Main(string[] args) { - Snippet.Run(); - PerformanceCounterCategory.Delete("Orders"); PerfCounter1.Run(args); } } From 1dcd1dff560ea11245c38f161bd7e97e50ca8bf4 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 25 Aug 2026 10:45:22 -0700 Subject: [PATCH 3/6] Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .../EventSourceCreationData/Overview/source.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs b/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs index 3a6884e9489..abcb9504969 100644 --- a/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs +++ b/snippets/csharp/System.Diagnostics/EventSourceCreationData/Overview/source.cs @@ -78,7 +78,7 @@ static void Main(string[] args) // To set the message and register the source remotely, use system-wide environment variables. // Use variables that are valid on that computer, such as "%SystemRoot%\system32\myresource.dll". Console.WriteLine("Message resource file ignored for remote event log."); - mySourceData.MessageResourceFile = string.Empty; + registerSource = false; } } } From fd8a5c6d6b454d8ad57d53cf57c0675e8529ed0c Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Thu, 27 Aug 2026 11:16:30 -0700 Subject: [PATCH 4/6] respond to feedback --- .../PerformanceCounter/.ctor/perfcounter.cs | 2 +- .../NextValue/elapsedtime.cs | 64 +++++++++---------- .../.ctor/perfCounterCatProps.cs | 2 +- .../Create/program.cs | 42 +++++------- 4 files changed, 49 insertions(+), 61 deletions(-) diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/perfcounter.cs b/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/perfcounter.cs index fc193e2f1d1..0ea8b4f7725 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/perfcounter.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounter/.ctor/perfcounter.cs @@ -2,7 +2,7 @@ using System.Diagnostics; // -using PerformanceCounter performanceCounter = new PerformanceCounter(); +using PerformanceCounter performanceCounter = new(); performanceCounter.CategoryName = "Process"; performanceCounter.CounterName = "Private Bytes"; performanceCounter.InstanceName = "Explorer"; diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/elapsedtime.cs b/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/elapsedtime.cs index 6d157571a2c..f9713124acc 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/elapsedtime.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounter/NextValue/elapsedtime.cs @@ -14,18 +14,18 @@ public class App { private static PerformanceCounter PC; - public static void Main() - { - ArrayList samplesList = new(); + public static void Main() + { + ArrayList samplesList = new(); - SetupCategory(); + SetupCategory(); CreateCounters(); - CollectSamples(samplesList); - } + CollectSamples(samplesList); + } private static bool SetupCategory() { - if ( !PerformanceCounterCategory.Exists("ElapsedTimeSampleCategory") ) + if (!PerformanceCounterCategory.Exists("ElapsedTimeSampleCategory")) { CounterCreationDataCollection CCDC = new(); @@ -33,26 +33,26 @@ private static bool SetupCategory() CounterCreationData ETimeData = new(); ETimeData.CounterType = PerformanceCounterType.ElapsedTime; ETimeData.CounterName = "ElapsedTimeSample"; - CCDC.Add(ETimeData); - + CCDC.Add(ETimeData); + // Create the category. PerformanceCounterCategory.Create("ElapsedTimeSampleCategory", "Demonstrates usage of the ElapsedTime performance counter type.", CCDC); - return(true); + return true; } else { Console.WriteLine("Category exists - ElapsedTimeSampleCategory"); - return(false); + return false; } } private static void CreateCounters() { // Create the counter. - PC = new PerformanceCounter("ElapsedTimeSampleCategory", + PC = new("ElapsedTimeSampleCategory", "ElapsedTimeSample", false); } @@ -76,7 +76,7 @@ private static void CollectSamples(ArrayList samplesList) Console.WriteLine($"NextValue() = {PC.NextValue()}"); Console.WriteLine($"Actual elapsed time = {DateTime.Now.Subtract(Start)}"); OutputSample(PC.NextSample()); - samplesList.Add( PC.NextSample() ); + samplesList.Add(PC.NextSample()); } // Reset the counter on 100th iteration. @@ -91,25 +91,25 @@ private static void CollectSamples(ArrayList samplesList) Console.WriteLine($"Elapsed time = {DateTime.Now.Subtract(Start)}"); } - - private static void OutputSample(CounterSample s) - { - Console.WriteLine("\r\n+++++++++++"); - Console.WriteLine("Sample values - \r\n"); - Console.WriteLine(" BaseValue = " + s.BaseValue); - Console.WriteLine(" CounterFrequency = " + s.CounterFrequency); - Console.WriteLine(" CounterTimeStamp = " + s.CounterTimeStamp); - Console.WriteLine(" CounterType = " + s.CounterType); - Console.WriteLine(" RawValue = " + s.RawValue); - Console.WriteLine(" SystemFrequency = " + s.SystemFrequency); - Console.WriteLine(" TimeStamp = " + s.TimeStamp); - Console.WriteLine(" TimeStamp100nSec = " + s.TimeStamp100nSec); - Console.WriteLine("++++++++++++++++++++++"); - } - - // Reads the counter information to enable setting the RawValue. - [DllImport("Kernel32.dll")] - public static extern bool QueryPerformanceCounter(out long value); + + private static void OutputSample(CounterSample s) + { + Console.WriteLine("\r\n+++++++++++"); + Console.WriteLine("Sample values - \r\n"); + Console.WriteLine($" BaseValue = {s.BaseValue}"); + Console.WriteLine($" CounterFrequency = {s.CounterFrequency}"); + Console.WriteLine($" CounterTimeStamp = {s.CounterTimeStamp}"); + Console.WriteLine($" CounterType = {s.CounterType}"); + Console.WriteLine($" RawValue = {s.RawValue}"); + Console.WriteLine($" SystemFrequency = {s.SystemFrequency}"); + Console.WriteLine($" TimeStamp = {s.TimeStamp}"); + Console.WriteLine($" TimeStamp100nSec = {s.TimeStamp100nSec}"); + Console.WriteLine("++++++++++++++++++++++"); + } + + // Reads the counter information to enable setting the RawValue. + [DllImport("Kernel32.dll")] + public static extern bool QueryPerformanceCounter(out long value); } // diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatProps.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatProps.cs index 6f30093cf0f..b69d7c86790 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatProps.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/.ctor/perfCounterCatProps.cs @@ -9,7 +9,7 @@ public static void Run(string[] args) { string categoryName = ""; string machineName = ""; - PerformanceCounterCategory pcc = new PerformanceCounterCategory(); + PerformanceCounterCategory pcc = new(); // Prompt for fields and set the corresponding properties. while (categoryName.Length == 0) diff --git a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs index cf22d6defbc..4f0e94c3ba7 100644 --- a/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs +++ b/snippets/csharp/System.Diagnostics/PerformanceCounterCategory/Create/program.cs @@ -95,23 +95,19 @@ public void StartCounters() { Console.WriteLine( "Instantiating Custom Counter Orders, Trucks, United States"); - counter1 = new PerformanceCounter( - "Orders", "Trucks", "United States", false); + counter1 = new("Orders", "Trucks", "United States", false); counter1.RawValue = 5; Console.WriteLine( "Instantiating Custom Counter Orders, Trucks, Europe"); - counter2 = new PerformanceCounter( - "Orders", "Trucks", "Europe", false); + counter2 = new("Orders", "Trucks", "Europe", false); counter2.RawValue = 10; Console.WriteLine( "Instantiating Custom Counter Orders, Rate of Sales, Total"); - counter3 = new PerformanceCounter( - "Orders", "Rate of Sales", "Total", false); + counter3 = new("Orders", "Rate of Sales", "Total", false); counter3.RawValue = 10; Console.WriteLine( "Instantiating Custom Counter Inventory, Trucks"); - counter4 = new PerformanceCounter( - "Inventory", "Trucks", false); + counter4 = new("Inventory", "Trucks", false); counter4.RawValue = 15; timer1.Start(); @@ -145,7 +141,7 @@ private void OnTimer1(object sender, ElapsedEventArgs args) counter2.Decrement(); counter3.IncrementBy(1); counter4.IncrementBy(150); - ++finalCount; + finalCount++; } catch (Exception e) { @@ -189,28 +185,24 @@ private void OnTimer1(object sender, ElapsedEventArgs args) return; float value1 = counter1.NextValue(); - Console.WriteLine( - "Custom Counter Orders, Trucks, United States: {0}", value1); + Console.WriteLine($"Custom Counter Orders, Trucks, United States: {value1}"); float value2 = counter2.NextValue(); - Console.WriteLine( - "Custom Counter Orders, Trucks, Europe: {0}", value2); + Console.WriteLine($"Custom Counter Orders, Trucks, Europe: {value2}"); float value3 = counter3.NextValue(); - Console.WriteLine( - "Custom Counter Orders, Rate of sales, United Total: {0}", value3); + Console.WriteLine($"Custom Counter Orders, Rate of sales, United Total: {value3}"); float value4 = counter4.NextValue(); - Console.WriteLine( - "Custom Counter Inventory, Trucks, United States: {0}", value4); + Console.WriteLine($"Custom Counter Inventory, Trucks, United States: {value4}"); if (finalCount < 5) { - ++finalCount; + finalCount++; } else { - ++finalCount; + finalCount++; signal.Set(); } } @@ -227,20 +219,16 @@ public void StartCounters() Console.WriteLine( "Instantiating Custom Counter Orders, Trucks, United States"); // Instantiate a counter with category "Orders", counter name "Trucks", and instance "United States". - counter1 = new PerformanceCounter( - "Orders", "Trucks", "United States"); + counter1 = new("Orders", "Trucks", "United States"); Console.WriteLine("Instantiating Custom Counter Orders, Trucks, Europe"); // Instantiate a counter with category "Orders", counter name "Trucks", and instance "Europe". - counter2 = new PerformanceCounter( - "Orders", "Trucks", "Europe"); + counter2 = new("Orders", "Trucks", "Europe"); Console.WriteLine("Instantiating Custom Counter Orders, Rate of Sales."); // Instantiate a counter with category "Orders", counter name "Rate of Sales", and a single instance. - counter3 = new PerformanceCounter( - "Orders", "Rate of Sales", "Total"); + counter3 = new("Orders", "Rate of Sales", "Total"); Console.WriteLine("Instantiating Custom Counter Inventory, Trucks, Only instance."); // Instantiate a single instance counter, category "Inventory", counter name "Trucks". - counter4 = new PerformanceCounter( - "Inventory", "Trucks", false); + counter4 = new("Inventory", "Trucks", false); timer1.Start(); } From fd93b50f5697771ce65da8693923744a2f358025 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Thu, 27 Aug 2026 11:23:16 -0700 Subject: [PATCH 5/6] Refactor string formatting to use interpolated strings --- .../Overview/instdatakeysvalues.cs | 20 ++++++------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs index f2e548f55ff..62aa7fdb2b2 100644 --- a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs +++ b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs @@ -5,7 +5,6 @@ class InstDataKeysValuesMod { - // private static string categoryName; // @@ -35,15 +34,13 @@ public static void Main() categoryNum = int.Parse(catNumStr); if (categoryNum < 1 || categoryNum > categories.Length) { - throw new Exception(string.Format("The category number must be in the " + - "range 1..{0}.", categories.Length)); + throw new Exception($"The category number must be in the range 1..{categories.Length}."); } categoryName = categories[(categoryNum - 1)].CategoryName; } catch (Exception ex) { - Console.WriteLine("\"{0}\" is not a valid category number." + - "\r\n{1}", catNumStr, ex.Message); + Console.WriteLine($"'{catNumStr}' is not a valid category number.\r\n{ex.Message}"); return; } // @@ -60,16 +57,14 @@ public static void Main() InstanceDataCollection[] idCCValuesArray = new InstanceDataCollection[idColColValues.Count]; idColColValues.CopyTo(idCCValuesArray, 0); - Console.WriteLine("InstanceDataCollectionCollection for \"{0}\" " + - "has {1} elements.", categoryName, idColCol.Count); + Console.WriteLine($"InstanceDataCollectionCollection for '{0categoryName}' has {1idColCol.Count} elements."); // Display the InstanceDataCollectionCollection Keys and Values. // The Keys and Values collections have the same number of elements. int index; for (index = 0; index < idCCKeysArray.Length; index++) { - Console.WriteLine(" Next InstanceDataCollectionCollection " + - "Key is \"{0}\"", idCCKeysArray[index]); + Console.WriteLine($" Next InstanceDataCollectionCollection key is '{idCCKeysArray[index]}'"); ProcessInstanceDataCollection(idCCValuesArray[index]); } // @@ -81,7 +76,6 @@ public static void Main() public static void ProcessInstanceDataCollection(InstanceDataCollection idCol) { // - ICollection idColKeys = idCol.Keys; string[] idColKeysArray = new string[idColKeys.Count]; idColKeys.CopyTo(idColKeysArray, 0); @@ -91,8 +85,7 @@ public static void ProcessInstanceDataCollection(InstanceDataCollection idCol) idColValues.CopyTo(idColValuesArray, 0); // - Console.WriteLine(" InstanceDataCollection for \"{0}\" " + - "has {1} elements.", idCol.CounterName, idCol.Count); + Console.WriteLine($" InstanceDataCollection for '{idCol.CounterName}' has {idCol.Count} elements."); // // Display the InstanceDataCollection Keys and Values. @@ -100,8 +93,7 @@ public static void ProcessInstanceDataCollection(InstanceDataCollection idCol) int index; for (index = 0; index < idColKeysArray.Length; index++) { - Console.WriteLine(" Next InstanceDataCollection " + - "Key is \"{0}\"", idColKeysArray[index]); + Console.WriteLine($" Next InstanceDataCollection key is '{idColKeysArray[index]}'"); ProcessInstanceDataObject(idColValuesArray[index]); } // From 9e1aa013b11c2e59465f201d80645c00b0f342cf Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Thu, 27 Aug 2026 11:58:18 -0700 Subject: [PATCH 6/6] fix compile errors --- .../InstanceDataCollection/Overview/instdatakeysvalues.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs index 62aa7fdb2b2..8927de178c8 100644 --- a/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs +++ b/snippets/csharp/System.Diagnostics/InstanceDataCollection/Overview/instdatakeysvalues.cs @@ -57,7 +57,7 @@ public static void Main() InstanceDataCollection[] idCCValuesArray = new InstanceDataCollection[idColColValues.Count]; idColColValues.CopyTo(idCCValuesArray, 0); - Console.WriteLine($"InstanceDataCollectionCollection for '{0categoryName}' has {1idColCol.Count} elements."); + Console.WriteLine($"InstanceDataCollectionCollection for '{categoryName}' has {idColCol.Count} elements."); // Display the InstanceDataCollectionCollection Keys and Values. // The Keys and Values collections have the same number of elements.