From 832a1a15c50ad3a7772530e95486ef9b7a4b5cd7 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Mon, 14 Sep 2026 11:18:14 -0700 Subject: [PATCH 1/5] Modernize System.Diagnostics C# snippets (#13028) --- .../Overview/Project.csproj | 8 ++ .../Overview/modulebuilder_definedocument.cs | 64 +++-------- .../BooleanSwitch/Enabled/Project.csproj | 3 +- .../BooleanSwitch/Enabled/source.cs | 27 ++--- .../BooleanSwitch/Overview/Program.cs | 2 + .../BooleanSwitch/Overview/Project.csproj | 4 +- .../BooleanSwitch/Overview/remarks.cs | 9 +- .../BooleanSwitch/Overview/source.cs | 27 ++--- .../Overview/Project.csproj | 6 + .../ConditionalAttribute/Overview/cas.cs | 14 ++- .../Overview/Project.csproj | 2 +- .../ConsoleTraceListener/Overview/program.cs | 34 +++--- .../Overview/Project.csproj | 2 +- .../CorrelationManager/Overview/program.cs | 2 +- .../CounterCreationData/.ctor/Project.csproj | 5 +- .../.ctor/diagnostics_countercreationdata.cs | 26 +++-- .../Overview/Project.csproj | 5 +- .../Overview/averagecount32.cs | 62 +++++----- .../.ctor/Program.cs | 2 + .../.ctor/Project.csproj | 10 ++ .../countercreationdatacollection_ctor.cs | 10 +- ...tion_ctor_countercreationdatacollection.cs | 12 +- .../AddRange/Project.csproj | 5 +- .../countercreationdatacollection_addrange.cs | 8 +- .../Contains/Project.csproj | 5 +- .../countercreationdatacollection_contains.cs | 17 +-- .../IndexOf/Project.csproj | 5 +- ...ercreationdatacollection_insert_indexof.cs | 20 ++-- .../CounterSample/.ctor/Project.csproj | 5 +- .../.ctor/countersample_ctor_2.cs | 106 +++++++++--------- .../DataReceivedEventArgs/Overview/Program.cs | 4 + .../Overview/Project.csproj | 2 +- .../Overview/datareceivedevent.cs | 4 +- .../Overview/net_async.cs | 14 +-- .../Overview/nmake_async.cs | 18 ++- .../Overview/sort_async.cs | 4 +- .../System.Diagnostics/Debug/Assert/source.cs | 4 +- .../Debug/Assert/source1.cs | 3 +- .../Debug/Assert/source2.cs | 5 +- .../System.Diagnostics/Debug/Close/source.cs | 2 +- .../Debug/Fail/Project.csproj | 6 + .../System.Diagnostics/Debug/Fail/source.cs | 24 ++-- .../System.Diagnostics/Debug/Fail/source1.cs | 28 +++-- .../System.Diagnostics/Debug/Indent/source.cs | 4 +- .../Debug/Overview/source.cs | 21 ++-- .../System.Diagnostics/Debug/Write/source.cs | 20 ++-- .../Debug/WriteIf/Project.csproj | 6 + .../Debug/WriteIf/source.cs | 8 +- .../Debug/WriteIf/source1.cs | 12 +- .../Debug/WriteIf/source2.cs | 14 +-- .../Debug/WriteIf/source3.cs | 12 +- .../Debug/WriteLine/Project.csproj | 6 + .../Debug/WriteLine/source.cs | 12 +- .../Debug/WriteLine/source1.cs | 16 +-- .../Debug/WriteLine/source2.cs | 16 +-- .../Debug/WriteLine/source3.cs | 16 +-- .../Debug/WriteLineIf/Project.csproj | 6 + .../Debug/WriteLineIf/source.cs | 8 +- .../Debug/WriteLineIf/source1.cs | 12 +- .../Debug/WriteLineIf/source2.cs | 12 +- .../Debug/WriteLineIf/source3.cs | 12 +- .../.ctor/Project.csproj | 2 +- .../.ctor/program.cs | 19 ++-- .../Overview/Project.csproj | 2 +- .../DefaultTraceListener/Overview/binomial.cs | 50 ++++----- .../DefaultTraceListener/Write/Project.csproj | 2 +- .../Write/defaulttracelistener.cs | 57 +++++----- .../.ctor/Project.csproj | 7 +- .../.ctor/entrywritteneventargs_ctor2.cs | 18 +-- .../Overview/Project.csproj | 7 +- .../Overview/entrywritteneventargs_ctor1.cs | 19 ++-- .../EventInstance/Overview/Project.csproj | 7 +- .../EventInstance/Overview/source.cs | 82 ++++++-------- .../EventLog/.ctor/Program.cs | 3 + .../EventLog/.ctor/Project.csproj | 1 - .../EventLog/.ctor/source.cs | 4 +- .../EventLog/.ctor/source1.cs | 4 +- .../EventLog/.ctor/source2.cs | 4 +- .../EventLog/Clear/source.cs | 18 +-- .../EventLog/CreateEventSource/Project.csproj | 10 ++ .../EventLog/CreateEventSource/source.cs | 47 ++++---- .../EventLog/Delete/Program.cs | 2 + .../EventLog/Delete/Project.csproj | 1 - .../EventLog/Delete/source.cs | 4 +- .../EventLog/Delete/source1.cs | 4 +- .../EventLog/EnableRaisingEvents/source.cs | 33 +++--- .../EventLog/Entries/source.cs | 18 ++- .../EventLog/EntryWritten/source.cs | 29 ++--- .../EventLog/Exists/Project.csproj | 7 +- .../EventLog/Exists/eventlog_exists_1.cs | 39 +++---- .../EventLog/GetEventLogs/Program.cs | 2 + .../EventLog/GetEventLogs/Project.csproj | 1 - .../EventLog/GetEventLogs/source.cs | 6 +- .../EventLog/GetEventLogs/source1.cs | 57 +++++----- .../System.Diagnostics/EventLog/Log/source.cs | 18 ++- .../EventLog/MachineName/source.cs | 18 ++- 96 files changed, 707 insertions(+), 733 deletions(-) create mode 100644 snippets/csharp/System.Diagnostics.SymbolStore/ISymbolDocumentWriter/Overview/Project.csproj create mode 100644 snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/Program.cs create mode 100644 snippets/csharp/System.Diagnostics/ConditionalAttribute/Overview/Project.csproj create mode 100644 snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/Program.cs create mode 100644 snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/Project.csproj create mode 100644 snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/Program.cs create mode 100644 snippets/csharp/System.Diagnostics/Debug/Fail/Project.csproj create mode 100644 snippets/csharp/System.Diagnostics/Debug/WriteIf/Project.csproj create mode 100644 snippets/csharp/System.Diagnostics/Debug/WriteLine/Project.csproj create mode 100644 snippets/csharp/System.Diagnostics/Debug/WriteLineIf/Project.csproj create mode 100644 snippets/csharp/System.Diagnostics/EventLog/.ctor/Program.cs create mode 100644 snippets/csharp/System.Diagnostics/EventLog/CreateEventSource/Project.csproj create mode 100644 snippets/csharp/System.Diagnostics/EventLog/Delete/Program.cs create mode 100644 snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/Program.cs diff --git a/snippets/csharp/System.Diagnostics.SymbolStore/ISymbolDocumentWriter/Overview/Project.csproj b/snippets/csharp/System.Diagnostics.SymbolStore/ISymbolDocumentWriter/Overview/Project.csproj new file mode 100644 index 00000000000..a15a29bf12c --- /dev/null +++ b/snippets/csharp/System.Diagnostics.SymbolStore/ISymbolDocumentWriter/Overview/Project.csproj @@ -0,0 +1,8 @@ + + + + Exe + net10.0 + + + diff --git a/snippets/csharp/System.Diagnostics.SymbolStore/ISymbolDocumentWriter/Overview/modulebuilder_definedocument.cs b/snippets/csharp/System.Diagnostics.SymbolStore/ISymbolDocumentWriter/Overview/modulebuilder_definedocument.cs index d65c258bc10..90c8b2c8df1 100644 --- a/snippets/csharp/System.Diagnostics.SymbolStore/ISymbolDocumentWriter/Overview/modulebuilder_definedocument.cs +++ b/snippets/csharp/System.Diagnostics.SymbolStore/ISymbolDocumentWriter/Overview/modulebuilder_definedocument.cs @@ -1,56 +1,18 @@ -// System.Reflection.Emit.ModuleBuilder.DefineDocument - -/* -The following example demonstrates the 'DefineDocument' method -of 'ModuleBuilder' class. -A dynamic assembly with a module in it is created in 'CodeGenerator' class. -It gets the object representing the defined document using the method -'DefineDocument'. -*/ -// -using System; +using System; +using System.Diagnostics.SymbolStore; using System.Reflection; using System.Reflection.Emit; -using System.Resources; -using System.Diagnostics.SymbolStore; -namespace ILGenServer -{ - public class CodeGenerator - { - ModuleBuilder myModuleBuilder ; - AssemblyBuilder myAssemblyBuilder ; - - public CodeGenerator() - { - - // Get the current application domain for the current thread. - AppDomain currentDomain = AppDomain.CurrentDomain; - AssemblyName myAssemblyName = new AssemblyName(); - myAssemblyName.Name = "TempAssembly"; - - // Define a dynamic assembly in the current domain. - myAssemblyBuilder = - currentDomain.DefineDynamicAssembly - (myAssemblyName, AssemblyBuilderAccess.RunAndSave); - // Define a dynamic module in "TempAssembly" assembly. - myModuleBuilder = - myAssemblyBuilder.DefineDynamicModule("TempModule","Resource.mod",true); +// +AssemblyName assemblyName = new("TempAssembly"); +PersistedAssemblyBuilder assemblyBuilder = new(assemblyName, typeof(object).Assembly); +ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("TempModule"); - // Define a document for source.on 'TempModule' module. - ISymbolDocumentWriter myDocument = - myModuleBuilder.DefineDocument("RTAsm.il", SymDocumentType.Text, - SymLanguageType.ILAssembly,SymLanguageVendor.Microsoft); +ISymbolDocumentWriter document = moduleBuilder.DefineDocument( + "RTAsm.il", + SymLanguageType.ILAssembly, + SymLanguageVendor.Microsoft, + SymDocumentType.Text); - Console.WriteLine("The object representing the defined document is:"+myDocument); - } - } - public class CallerClass - { - public static void Main() - { - CodeGenerator myGenerator = new CodeGenerator(); - } - } -} -// \ No newline at end of file +Console.WriteLine($"The object representing the defined document is:{document}"); +// diff --git a/snippets/csharp/System.Diagnostics/BooleanSwitch/Enabled/Project.csproj b/snippets/csharp/System.Diagnostics/BooleanSwitch/Enabled/Project.csproj index d3169dd8324..ffb97e9872d 100644 --- a/snippets/csharp/System.Diagnostics/BooleanSwitch/Enabled/Project.csproj +++ b/snippets/csharp/System.Diagnostics/BooleanSwitch/Enabled/Project.csproj @@ -2,8 +2,7 @@ Exe - net10.0-windows - true + net10.0 \ No newline at end of file diff --git a/snippets/csharp/System.Diagnostics/BooleanSwitch/Enabled/source.cs b/snippets/csharp/System.Diagnostics/BooleanSwitch/Enabled/source.cs index a44bbb27676..823f8e74c61 100644 --- a/snippets/csharp/System.Diagnostics/BooleanSwitch/Enabled/source.cs +++ b/snippets/csharp/System.Diagnostics/BooleanSwitch/Enabled/source.cs @@ -1,27 +1,24 @@ using System; using System.Diagnostics; -using System.Windows.Forms; -public class Form1 : Form +public class Form1 { - protected TextBox textBox1; // - //Class level declaration. - /* Create a BooleanSwitch for data.*/ - static BooleanSwitch dataSwitch = new BooleanSwitch("Data", "DataAccess module"); + // Class-level declaration. + // Create a BooleanSwitch for data. + private static readonly BooleanSwitch s_dataSwitch = new("Data", "DataAccess module"); - static public void MyMethod(string location) + public static void MyMethod(string location) { - //Insert code here to handle processing. - if (dataSwitch.Enabled) - Console.WriteLine("Error happened at " + location); + // Insert code here to handle processing. + if (s_dataSwitch.Enabled) + { + Console.WriteLine($"Error happened at {location}"); + } } - public static void Main(string[] args) - { - //Run the method that writes an error message specifying the location of the error. - MyMethod("in Main"); - } + // Run the method that writes an error message specifying the location of the error. + public static void Main() => MyMethod("in Main"); // } diff --git a/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/Program.cs b/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/Program.cs new file mode 100644 index 00000000000..92c1ddba0d5 --- /dev/null +++ b/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/Program.cs @@ -0,0 +1,2 @@ +SomeClass.Run(); +Form1.Run(args); diff --git a/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/Project.csproj index 999b9306092..ffb97e9872d 100644 --- a/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/Project.csproj @@ -2,9 +2,7 @@ Exe - net10.0-windows - true - SomeClass + net10.0 \ No newline at end of file diff --git a/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/remarks.cs b/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/remarks.cs index 49ee5417c44..abfc5e8a68b 100644 --- a/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/remarks.cs +++ b/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/remarks.cs @@ -4,15 +4,14 @@ public class SomeClass { // - private static BooleanSwitch boolSwitch = new BooleanSwitch("mySwitch", + private static readonly BooleanSwitch s_boolSwitch = new("mySwitch", "Switch in config file"); - public static void Main() + public static void Run() { //... - Console.WriteLine("Boolean switch {0} configured as {1}", - boolSwitch.DisplayName, boolSwitch.Enabled.ToString()); - if (boolSwitch.Enabled) + Console.WriteLine($"Boolean switch {s_boolSwitch.DisplayName} configured as {s_boolSwitch.Enabled}"); + if (s_boolSwitch.Enabled) { //... } diff --git a/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/source.cs b/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/source.cs index 8333507d3c4..04d5e31f80b 100644 --- a/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/source.cs +++ b/snippets/csharp/System.Diagnostics/BooleanSwitch/Overview/source.cs @@ -1,27 +1,24 @@ using System; using System.Diagnostics; -using System.Windows.Forms; -public class Form1 : Form +public class Form1 { - protected TextBox textBox1; // - // Class level declaration. - /* Create a BooleanSwitch for data.*/ - static BooleanSwitch dataSwitch = new BooleanSwitch("Data", "DataAccess module"); + // Class-level declaration. + // Create a BooleanSwitch for data. + private static readonly BooleanSwitch s_dataSwitch = new("Data", "DataAccess module"); - static public void MyMethod(string location) + public static void MyMethod(string location) { - //Insert code here to handle processing. - if (dataSwitch.Enabled) - Console.WriteLine("Error happened at " + location); + // Insert code here to handle processing. + if (s_dataSwitch.Enabled) + { + Console.WriteLine($"Error happened at {location}"); + } } - public static void Main(string[] args) - { - //Run the method which writes an error message specifying the location of the error. - MyMethod("in Main"); - } + // Run the method, which writes an error message specifying the location of the error. + public static void Run(string[] args) => MyMethod("in Main"); // } diff --git a/snippets/csharp/System.Diagnostics/ConditionalAttribute/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/ConditionalAttribute/Overview/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Diagnostics/ConditionalAttribute/Overview/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Diagnostics/ConditionalAttribute/Overview/cas.cs b/snippets/csharp/System.Diagnostics/ConditionalAttribute/Overview/cas.cs index 8c89b713983..dba19d6f5f1 100644 --- a/snippets/csharp/System.Diagnostics/ConditionalAttribute/Overview/cas.cs +++ b/snippets/csharp/System.Diagnostics/ConditionalAttribute/Overview/cas.cs @@ -14,8 +14,18 @@ static void Main() Method2(); Console.WriteLine("Using the Debug class"); - Debug.Listeners.Add(new ConsoleTraceListener()); - Debug.WriteLine("DEBUG is defined"); +#if DEBUG + ConsoleTraceListener listener = new(); + Trace.Listeners.Add(listener); + try + { + Debug.WriteLine("DEBUG is defined"); + } + finally + { + Trace.Listeners.Remove(listener); + } +#endif } // diff --git a/snippets/csharp/System.Diagnostics/ConsoleTraceListener/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/ConsoleTraceListener/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Diagnostics/ConsoleTraceListener/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/ConsoleTraceListener/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Diagnostics/ConsoleTraceListener/Overview/program.cs b/snippets/csharp/System.Diagnostics/ConsoleTraceListener/Overview/program.cs index 2f98a91874c..37ac39adad8 100644 --- a/snippets/csharp/System.Diagnostics/ConsoleTraceListener/Overview/program.cs +++ b/snippets/csharp/System.Diagnostics/ConsoleTraceListener/Overview/program.cs @@ -17,28 +17,28 @@ public static void WriteEnvironmentInfoToTrace() string methodName = "WriteEnvironmentInfoToTrace"; Trace.Indent(); - Trace.WriteLine(DateTime.Now.ToString() + " - Start of " + methodName); + Trace.WriteLine($"{DateTime.Now} - Start of {methodName}"); Trace.Indent(); // Write details on the executing environment to the trace output. - Trace.WriteLine("Operating system: " + System.Environment.OSVersion.ToString()); - Trace.WriteLine("Computer name: " + System.Environment.MachineName); - Trace.WriteLine("User name: " + System.Environment.UserName); - Trace.WriteLine("CLR runtime version: " + System.Environment.Version.ToString()); - Trace.WriteLine("Command line: " + System.Environment.CommandLine); + Trace.WriteLine($"Operating system: {Environment.OSVersion}"); + Trace.WriteLine($"Computer name: {Environment.MachineName}"); + Trace.WriteLine($"User name: {Environment.UserName}"); + Trace.WriteLine($"CLR runtime version: {Environment.Version}"); + Trace.WriteLine($"Command line: {Environment.CommandLine}"); // Enumerate the trace listener collection and // display details about each configured trace listener. - Trace.WriteLine("Number of configured trace listeners = " + Trace.Listeners.Count.ToString()); + Trace.WriteLine($"Number of configured trace listeners = {Trace.Listeners.Count}"); foreach (TraceListener tl in Trace.Listeners) { - Trace.WriteLine("Trace listener name = " + tl.Name); - Trace.WriteLine(" type = " + tl.GetType().ToString()); + Trace.WriteLine($"Trace listener name = {tl.Name}"); + Trace.WriteLine($" type = {tl.GetType()}"); } Trace.Unindent(); - Trace.WriteLine(DateTime.Now.ToString() + " - End of " + methodName); + Trace.WriteLine($"{DateTime.Now} - End of {methodName}"); Trace.Unindent(); } @@ -50,7 +50,7 @@ public static void Main(string[] CmdArgs) { // Write a trace message to all configured trace listeners. - Trace.WriteLine(DateTime.Now.ToString()+" - Start of Main"); + Trace.WriteLine($"{DateTime.Now} - Start of Main"); // // Define a trace listener to direct trace output from this method @@ -59,9 +59,9 @@ public static void Main(string[] CmdArgs) // Check the command line arguments to determine which // console stream should be used for trace output. - if ((CmdArgs.Length>0)&&(CmdArgs[0].ToString().ToLower().Equals("/stderr"))) - // Initialize the console trace listener to write - // trace output to the standard error stream. + if (CmdArgs.Length > 0 && CmdArgs[0].ToLower().Equals("/stderr")) + // Initialize the console trace listener to write + // trace output to the standard error stream. { consoleTracer = new ConsoleTraceListener(true); } @@ -76,7 +76,7 @@ public static void Main(string[] CmdArgs) consoleTracer.Name = "mainConsoleTracer"; // Write the initial trace message to the console trace listener. - consoleTracer.WriteLine(DateTime.Now.ToString()+" ["+consoleTracer.Name+"] - Starting output to trace listener."); + consoleTracer.WriteLine($"{DateTime.Now} [{consoleTracer.Name}] - Starting output to trace listener."); // Add the new console trace listener to // the collection of trace listeners. @@ -88,7 +88,7 @@ public static void Main(string[] CmdArgs) WriteEnvironmentInfoToTrace(); // Write the final trace message to the console trace listener. - consoleTracer.WriteLine(DateTime.Now.ToString()+" ["+consoleTracer.Name+"] - Ending output to trace listener."); + consoleTracer.WriteLine($"{DateTime.Now} [{consoleTracer.Name}] - Ending output to trace listener."); // Flush any pending trace messages, remove the // console trace listener from the collection, @@ -98,7 +98,7 @@ public static void Main(string[] CmdArgs) consoleTracer.Close(); // Write a final trace message to all trace listeners. - Trace.WriteLine(DateTime.Now.ToString()+" - End of Main"); + Trace.WriteLine($"{DateTime.Now} - End of Main"); // Close all other configured trace listeners. Trace.Close(); diff --git a/snippets/csharp/System.Diagnostics/CorrelationManager/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/CorrelationManager/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Diagnostics/CorrelationManager/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/CorrelationManager/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Diagnostics/CorrelationManager/Overview/program.cs b/snippets/csharp/System.Diagnostics/CorrelationManager/Overview/program.cs index f5eee2e8d9e..71160dc79c5 100644 --- a/snippets/csharp/System.Diagnostics/CorrelationManager/Overview/program.cs +++ b/snippets/csharp/System.Diagnostics/CorrelationManager/Overview/program.cs @@ -1,8 +1,8 @@ // using System; using System.Collections.Generic; -using System.Text; using System.Diagnostics; +using System.Text; using System.Threading; namespace CorrlationManager diff --git a/snippets/csharp/System.Diagnostics/CounterCreationData/.ctor/Project.csproj b/snippets/csharp/System.Diagnostics/CounterCreationData/.ctor/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationData/.ctor/Project.csproj +++ b/snippets/csharp/System.Diagnostics/CounterCreationData/.ctor/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/CounterCreationData/.ctor/diagnostics_countercreationdata.cs b/snippets/csharp/System.Diagnostics/CounterCreationData/.ctor/diagnostics_countercreationdata.cs index 40eabf262d4..ce45b5ebfa1 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationData/.ctor/diagnostics_countercreationdata.cs +++ b/snippets/csharp/System.Diagnostics/CounterCreationData/.ctor/diagnostics_countercreationdata.cs @@ -27,26 +27,28 @@ class MyCounterCreationData { static void Main() { - CounterCreationDataCollection myCol = - new CounterCreationDataCollection(); + CounterCreationDataCollection myCol = new(); // Create two custom counter objects. CounterCreationData myCounter1 = new CounterCreationData("Counter1", "First custom counter", PerformanceCounterType.CounterDelta32); - CounterCreationData myCounter2 = new CounterCreationData(); - - // Set the properties of the 'CounterCreationData' object. - myCounter2.CounterName = "Counter2"; - myCounter2.CounterHelp = "Second custom counter"; - myCounter2.CounterType = PerformanceCounterType.NumberOfItemsHEX32; + CounterCreationData myCounter2 = new() + { + // Set the properties of the 'CounterCreationData' object. + CounterName = "Counter2", + CounterHelp = "Second custom counter", + CounterType = PerformanceCounterType.NumberOfItemsHEX32 + }; // Add custom counter objects to CounterCreationDataCollection. myCol.Add(myCounter1); myCol.Add(myCounter2); if (PerformanceCounterCategory.Exists("New Counter Category")) + { PerformanceCounterCategory.Delete("New Counter Category"); + } // Bind the counters to a PerformanceCounterCategory. PerformanceCounterCategory myCategory = @@ -54,13 +56,13 @@ static void Main() PerformanceCounterCategoryType.SingleInstance, myCol); Console.WriteLine("Counter Information:"); - Console.WriteLine("Category Name: " + myCategory.CategoryName); + Console.WriteLine($"Category Name: {myCategory.CategoryName}"); for (int i = 0; i < myCol.Count; i++) { // Display the properties of the CounterCreationData objects. - Console.WriteLine("CounterName : " + myCol[i].CounterName); - Console.WriteLine("CounterHelp : " + myCol[i].CounterHelp); - Console.WriteLine("CounterType : " + myCol[i].CounterType); + Console.WriteLine($"CounterName : {myCol[i].CounterName}"); + Console.WriteLine($"CounterHelp : {myCol[i].CounterHelp}"); + Console.WriteLine($"CounterType : {myCol[i].CounterType}"); } } } diff --git a/snippets/csharp/System.Diagnostics/CounterCreationData/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/CounterCreationData/Overview/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationData/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/CounterCreationData/Overview/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/CounterCreationData/Overview/averagecount32.cs b/snippets/csharp/System.Diagnostics/CounterCreationData/Overview/averagecount32.cs index 11dc1223b87..f342065c002 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationData/Overview/averagecount32.cs +++ b/snippets/csharp/System.Diagnostics/CounterCreationData/Overview/averagecount32.cs @@ -19,7 +19,9 @@ public static void Main() // prior to executing the application that uses the counters. // Execute this sample a second time to use the category. if (SetupCategory()) + { return; + } CreateCounters(); CollectSamples(samplesList); CalculateResults(samplesList); @@ -27,7 +29,7 @@ public static void Main() private static bool SetupCategory() { - if ( !PerformanceCounterCategory.Exists("AverageCounter64SampleCategory") ) + if (!PerformanceCounterCategory.Exists("AverageCounter64SampleCategory")) { CounterCreationDataCollection counterDataCollection = new CounterCreationDataCollection(); @@ -49,12 +51,12 @@ private static bool SetupCategory() "Demonstrates usage of the AverageCounter64 performance counter type.", PerformanceCounterCategoryType.SingleInstance, counterDataCollection); - return(true); + return (true); } else { Console.WriteLine("Category exists - AverageCounter64SampleCategory"); - return(false); + return (false); } } @@ -73,21 +75,21 @@ private static void CreateCounters() "AverageCounter64SampleBase", false); - avgCounter64Sample.RawValue=0; - avgCounter64SampleBase.RawValue=0; + avgCounter64Sample.RawValue = 0; + avgCounter64SampleBase.RawValue = 0; } -// + // private static void CollectSamples(ArrayList samplesList) { - Random r = new Random( DateTime.Now.Millisecond ); + Random r = new Random(DateTime.Now.Millisecond); // Loop for the samples. for (int j = 0; j < 100; j++) { int value = r.Next(1, 10); - Console.Write(j + " = " + value); + Console.Write($"{j} = {value}"); avgCounter64Sample.IncrementBy(value); @@ -96,7 +98,7 @@ private static void CollectSamples(ArrayList samplesList) if ((j % 10) == 9) { OutputSample(avgCounter64Sample.NextSample()); - samplesList.Add( avgCounter64Sample.NextSample() ); + samplesList.Add(avgCounter64Sample.NextSample()); } else { @@ -110,21 +112,19 @@ private static void CollectSamples(ArrayList samplesList) private static void CalculateResults(ArrayList samplesList) { - for(int i = 0; i < (samplesList.Count - 1); i++) + for (int i = 0; i < (samplesList.Count - 1); i++) { // Output the sample. - OutputSample( (CounterSample)samplesList[i] ); - OutputSample( (CounterSample)samplesList[i+1] ); + OutputSample((CounterSample)samplesList[i]); + OutputSample((CounterSample)samplesList[i + 1]); // Use .NET to calculate the counter value. - Console.WriteLine(".NET computed counter value = " + - CounterSampleCalculator.ComputeCounterValue((CounterSample)samplesList[i], - (CounterSample)samplesList[i+1]) ); + Console.WriteLine($".NET computed counter value = {CounterSampleCalculator.ComputeCounterValue( + (CounterSample)samplesList[i], (CounterSample)samplesList[i + 1])}"); // Calculate the counter value manually. - Console.WriteLine("My computed counter value = " + - MyComputeCounterValue((CounterSample)samplesList[i], - (CounterSample)samplesList[i+1]) ); + Console.WriteLine($"My computed counter value = {MyComputeCounterValue( + (CounterSample)samplesList[i], (CounterSample)samplesList[i + 1])}"); } } @@ -142,12 +142,12 @@ private static void CalculateResults(ArrayList samplesList) // Average (Nx - N0) / (Dx - D0) // Example PhysicalDisk\ Avg. Disk Bytes/Transfer //++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++//++++++++ - private static Single MyComputeCounterValue(CounterSample s0, CounterSample s1) + private static float MyComputeCounterValue(CounterSample s0, CounterSample s1) { - Single numerator = (Single)s1.RawValue - (Single)s0.RawValue; - Single denomenator = (Single)s1.BaseValue - (Single)s0.BaseValue; - Single counterValue = numerator / denomenator; - return(counterValue); + float numerator = (float)s1.RawValue - (float)s0.RawValue; + float denomenator = (float)s1.BaseValue - (float)s0.BaseValue; + float counterValue = numerator / denomenator; + return counterValue; } // Output information about the counter sample. @@ -155,14 +155,14 @@ 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($" 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("++++++++++++++++++++++"); } } diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/Program.cs b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/Program.cs new file mode 100644 index 00000000000..0e27a867996 --- /dev/null +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/Program.cs @@ -0,0 +1,2 @@ +CounterCreationCollectionCopyExample.Run(); +CounterCreationArrayExample.Run(); diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/Project.csproj b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/Project.csproj new file mode 100644 index 00000000000..a9b3939dd0f --- /dev/null +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/Project.csproj @@ -0,0 +1,10 @@ + + + Exe + net10.0 + + + + + + diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/countercreationdatacollection_ctor.cs b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/countercreationdatacollection_ctor.cs index 452fd5244b2..6d7c1576d3d 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/countercreationdatacollection_ctor.cs +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/countercreationdatacollection_ctor.cs @@ -11,9 +11,9 @@ are displayed to the console. using System; using System.Diagnostics; -public class CounterCreationExample +public class CounterCreationArrayExample { - public static void Main() + public static void Run() { try { @@ -32,7 +32,7 @@ public static void Main() for (int i = 0; i < numberOfCounters; i++) { - Console.Write("Enter the counter name for {0} counter : ", i); + Console.Write($"Enter the counter name for {i} counter : "); myCounterCreationData[i] = new CounterCreationData(); myCounterCreationData[i].CounterName = Console.ReadLine(); } @@ -45,7 +45,7 @@ public static void Main() Console.WriteLine("The list of counters in 'CounterCollection' are :"); for (int i = 0; i < myCounterCollection.Count; i++) - Console.WriteLine("Counter {0} is '{1}'", i, myCounterCollection[i].CounterName); + Console.WriteLine($"Counter {i} is '{myCounterCollection[i].CounterName}'"); } else { @@ -55,7 +55,7 @@ public static void Main() } catch (Exception e) { - Console.WriteLine("Exception: {0}.", e.Message); + Console.WriteLine($"Exception: {e.Message}."); return; } } diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/countercreationdatacollection_ctor_countercreationdatacollection.cs b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/countercreationdatacollection_ctor_countercreationdatacollection.cs index 5c377485d70..b676cf12f68 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/countercreationdatacollection_ctor_countercreationdatacollection.cs +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/.ctor/countercreationdatacollection_ctor_countercreationdatacollection.cs @@ -9,10 +9,10 @@ are displayed to the console. using System; using System.Diagnostics; -public class CounterCreationExample +public class CounterCreationCollectionCopyExample { - public static void Main() + public static void Run() { try { @@ -25,7 +25,7 @@ public static void Main() new CounterCreationData[numberOfCounters]; for (int i = 0; i < numberOfCounters; i++) { - Console.Write("Enter the counter name for {0} counter : ", i); + Console.Write($"Enter the counter name for {i} counter : "); myCounterCreationData[i] = new CounterCreationData(); myCounterCreationData[i].CounterName = Console.ReadLine(); } @@ -43,7 +43,7 @@ public static void Main() Console.WriteLine("The list of counters in 'CounterCollection' are : "); for (int i = 0; i < myNewCounterCollection.Count; i++) - Console.WriteLine("Counter {0} is '{1}'", i, myNewCounterCollection[i].CounterName); + Console.WriteLine($"Counter {i} is '{myNewCounterCollection[i].CounterName}'"); } else { @@ -53,8 +53,8 @@ public static void Main() } catch (Exception e) { - Console.WriteLine("Exception: {0}.", e.Message); + Console.WriteLine($"Exception: {e.Message}."); return; } } -} \ No newline at end of file +} diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/AddRange/Project.csproj b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/AddRange/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/AddRange/Project.csproj +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/AddRange/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/AddRange/countercreationdatacollection_addrange.cs b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/AddRange/countercreationdatacollection_addrange.cs index 9821672ef8e..629916c14f5 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/AddRange/countercreationdatacollection_addrange.cs +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/AddRange/countercreationdatacollection_addrange.cs @@ -26,7 +26,7 @@ public static void Main() new CounterCreationData[numberOfCounters]; for (int i = 0; i < numberOfCounters; i++) { - Console.Write("Enter the counter name for {0} counter : ", i); + Console.Write($"Enter the counter name for {i} counter : "); myCounterCreationData[i] = new CounterCreationData(); myCounterCreationData[i].CounterName = Console.ReadLine(); } @@ -47,7 +47,7 @@ public static void Main() Console.WriteLine("The list of counters in CounterCollection are: "); for (int i = 0; i < myNewCounterCollection.Count; i++) - Console.WriteLine("Counter {0} is '{1}'", i + 1, myNewCounterCollection[i].CounterName); + Console.WriteLine($"Counter {i + 1} is '{myNewCounterCollection[i].CounterName}'"); } else { @@ -56,10 +56,10 @@ public static void Main() } catch (Exception e) { - Console.WriteLine("Exception: {0}.", e.Message); + Console.WriteLine($"Exception: {e.Message}."); return; } } } // -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/Contains/Project.csproj b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/Contains/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/Contains/Project.csproj +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/Contains/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/Contains/countercreationdatacollection_contains.cs b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/Contains/countercreationdatacollection_contains.cs index 5f5d91cf35d..d87490a1d8e 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/Contains/countercreationdatacollection_contains.cs +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/Contains/countercreationdatacollection_contains.cs @@ -30,12 +30,13 @@ public static void Main() new CounterCreationData[numberOfCounters]; for (int i = 0; i < numberOfCounters; i++) { - Console.Write("Enter the counter name for {0} counter : ", i); - myCounterCreationData[i] = new CounterCreationData(); - myCounterCreationData[i].CounterName = Console.ReadLine(); + Console.Write($"Enter the counter name for {i} counter : "); + myCounterCreationData[i] = new CounterCreationData + { + CounterName = Console.ReadLine() + }; } - CounterCreationDataCollection myCounterCollection = - new CounterCreationDataCollection(); + CounterCreationDataCollection myCounterCollection = new(); // Add the 'CounterCreationData[]' to 'CounterCollection'. myCounterCollection.AddRange(myCounterCreationData); @@ -48,8 +49,8 @@ public static void Main() if (myCounterCollection.Contains(myCounterCreationData[0])) { myCounterCollection.Remove(myCounterCreationData[0]); - Console.WriteLine("'{0}' counter is removed from the " + - "CounterCreationDataCollection", myCounterCreationData[0].CounterName); + Console.WriteLine( + $"'{myCounterCreationData[0].CounterName}' counter is removed from the CounterCreationDataCollection"); } } else @@ -66,7 +67,7 @@ public static void Main() } catch (Exception e) { - Console.WriteLine("Exception: {0}.", e.Message); + Console.WriteLine($"Exception: {e.Message}."); return; } } diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/IndexOf/Project.csproj b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/IndexOf/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/IndexOf/Project.csproj +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/IndexOf/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/IndexOf/countercreationdatacollection_insert_indexof.cs b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/IndexOf/countercreationdatacollection_insert_indexof.cs index 92f9e42a8b5..dc60da080e0 100644 --- a/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/IndexOf/countercreationdatacollection_insert_indexof.cs +++ b/snippets/csharp/System.Diagnostics/CounterCreationDataCollection/IndexOf/countercreationdatacollection_insert_indexof.cs @@ -35,19 +35,21 @@ public static void Main() for (int i = 0; i < numberOfCounters; i++) { - Console.Write("Enter the counter name for {0} counter ", i); - myCounterCreationData[i] = new CounterCreationData(); - myCounterCreationData[i].CounterName = Console.ReadLine(); + Console.Write($"Enter the counter name for {i} counter "); + myCounterCreationData[i] = new CounterCreationData + { + CounterName = Console.ReadLine() + }; } CounterCreationDataCollection myCounterCollection = new CounterCreationDataCollection(myCounterCreationData); - CounterCreationData myInsertCounterCreationData = new CounterCreationData( + CounterCreationData myInsertCounterCreationData = new( "CounterInsert", "", PerformanceCounterType.NumberOfItems32); // Insert an instance of 'CounterCreationData' in the 'CounterCreationDataCollection'. myCounterCollection.Insert(myCounterCollection.Count - 1, myInsertCounterCreationData); - Console.WriteLine("'{0}' counter is inserted into 'CounterCreationDataCollection'", - myInsertCounterCreationData.CounterName); + Console.WriteLine( + $"'{myInsertCounterCreationData.CounterName}' counter is inserted into 'CounterCreationDataCollection'"); // Create the category. PerformanceCounterCategory.Create(myCategoryName, "Sample Category", PerformanceCounterCategoryType.SingleInstance, myCounterCollection); @@ -57,8 +59,8 @@ public static void Main() myCounter = new PerformanceCounter(myCategoryName, myCounterCreationData[i].CounterName, "", false); } - Console.WriteLine("The index of '{0}' counter is {1}", - myInsertCounterCreationData.CounterName, myCounterCollection.IndexOf(myInsertCounterCreationData)); + Console.WriteLine( + $"The index of '{myInsertCounterCreationData.CounterName}' counter is {myCounterCollection.IndexOf(myInsertCounterCreationData)}"); } else { @@ -69,7 +71,7 @@ public static void Main() } catch (Exception e) { - Console.WriteLine("Exception: {0}.", e.Message); + Console.WriteLine($"Exception: {e.Message}."); return; } } diff --git a/snippets/csharp/System.Diagnostics/CounterSample/.ctor/Project.csproj b/snippets/csharp/System.Diagnostics/CounterSample/.ctor/Project.csproj index e17ba622dbc..3febdac17a4 100644 --- a/snippets/csharp/System.Diagnostics/CounterSample/.ctor/Project.csproj +++ b/snippets/csharp/System.Diagnostics/CounterSample/.ctor/Project.csproj @@ -1,9 +1,8 @@ - Library - net10.0-windows - true + Exe + net10.0 diff --git a/snippets/csharp/System.Diagnostics/CounterSample/.ctor/countersample_ctor_2.cs b/snippets/csharp/System.Diagnostics/CounterSample/.ctor/countersample_ctor_2.cs index 17b8b49bc48..70bd36bb938 100644 --- a/snippets/csharp/System.Diagnostics/CounterSample/.ctor/countersample_ctor_2.cs +++ b/snippets/csharp/System.Diagnostics/CounterSample/.ctor/countersample_ctor_2.cs @@ -13,58 +13,58 @@ the corresponding fields. class MyCounterSampleClass { - public static void Main() - { -// - PerformanceCounter myPerformanceCounter1 = new PerformanceCounter - ("Processor","% Processor Time", "0"); - CounterSample myCounterSample1 = new CounterSample(10L, 20L, 30L, 40L, 50L, 60L, - PerformanceCounterType.AverageCount64); - Console.WriteLine("CounterTimeStamp = "+myCounterSample1.CounterTimeStamp); + public static void Main() + { + // + PerformanceCounter myPerformanceCounter1 = new PerformanceCounter + ("Processor", "% Processor Time", "0"); + CounterSample myCounterSample1 = new CounterSample(10L, 20L, 30L, 40L, 50L, 60L, + PerformanceCounterType.AverageCount64); + Console.WriteLine($"CounterTimeStamp = {myCounterSample1.CounterTimeStamp}"); - Console.WriteLine("BaseValue = "+myCounterSample1.BaseValue); - Console.WriteLine("RawValue = "+myCounterSample1.RawValue); - Console.WriteLine("CounterFrequency = "+myCounterSample1.CounterFrequency); - Console.WriteLine("SystemFrequency = "+myCounterSample1.SystemFrequency); - Console.WriteLine("TimeStamp = "+myCounterSample1.TimeStamp); - Console.WriteLine("TimeStamp100nSec = "+myCounterSample1.TimeStamp100nSec); - Console.WriteLine("CounterType = "+myCounterSample1.CounterType); - // Hold the results of sample. - myCounterSample1 = myPerformanceCounter1.NextSample(); - Console.WriteLine("BaseValue = "+myCounterSample1.BaseValue); - Console.WriteLine("RawValue = "+myCounterSample1.RawValue); - Console.WriteLine("CounterFrequency = "+myCounterSample1.CounterFrequency); - Console.WriteLine("SystemFrequency = "+myCounterSample1.SystemFrequency); - Console.WriteLine("TimeStamp = "+myCounterSample1.TimeStamp); - Console.WriteLine("TimeStamp100nSec = "+myCounterSample1.TimeStamp100nSec); - Console.WriteLine("CounterType = "+myCounterSample1.CounterType); -// - Console.WriteLine(""); - Console.WriteLine(""); -// - PerformanceCounter myPerformanceCounter2 = new PerformanceCounter - ("Processor","% Processor Time", "0"); - CounterSample myCounterSample2 = new CounterSample(10L, 20L, 30L, 40L, 50L, 60L, - PerformanceCounterType.AverageCount64, 300); - Console.WriteLine("CounterTimeStamp = "+myCounterSample2.CounterTimeStamp); - Console.WriteLine("BaseValue = "+myCounterSample2.BaseValue); - Console.WriteLine("RawValue = "+myCounterSample2.RawValue); - Console.WriteLine("CounterFrequency = "+myCounterSample2.CounterFrequency); - Console.WriteLine("SystemFrequency = "+myCounterSample2.SystemFrequency); - Console.WriteLine("TimeStamp = "+myCounterSample2.TimeStamp); - Console.WriteLine("TimeStamp100nSec = "+myCounterSample2.TimeStamp100nSec); - Console.WriteLine("CounterType = "+myCounterSample2.CounterType); - Console.WriteLine("CounterTimeStamp = "+myCounterSample2.CounterTimeStamp); - // Hold the results of sample. - myCounterSample2 = myPerformanceCounter2.NextSample(); - Console.WriteLine("BaseValue = "+myCounterSample2.BaseValue); - Console.WriteLine("RawValue = "+myCounterSample2.RawValue); - Console.WriteLine("CounterFrequency = "+myCounterSample2.CounterFrequency); - Console.WriteLine("SystemFrequency = "+myCounterSample2.SystemFrequency); - Console.WriteLine("TimeStamp = "+myCounterSample2.TimeStamp); - Console.WriteLine("TimeStamp100nSec = "+myCounterSample2.TimeStamp100nSec); - Console.WriteLine("CounterType = "+myCounterSample2.CounterType); - Console.WriteLine("CounterTimeStamp = "+myCounterSample2.CounterTimeStamp); -// - } + Console.WriteLine($"BaseValue = {myCounterSample1.BaseValue}"); + Console.WriteLine($"RawValue = {myCounterSample1.RawValue}"); + Console.WriteLine($"CounterFrequency = {myCounterSample1.CounterFrequency}"); + Console.WriteLine($"SystemFrequency = {myCounterSample1.SystemFrequency}"); + Console.WriteLine($"TimeStamp = {myCounterSample1.TimeStamp}"); + Console.WriteLine($"TimeStamp100nSec = {myCounterSample1.TimeStamp100nSec}"); + Console.WriteLine($"CounterType = {myCounterSample1.CounterType}"); + // Hold the results of sample. + myCounterSample1 = myPerformanceCounter1.NextSample(); + Console.WriteLine($"BaseValue = {myCounterSample1.BaseValue}"); + Console.WriteLine($"RawValue = {myCounterSample1.RawValue}"); + Console.WriteLine($"CounterFrequency = {myCounterSample1.CounterFrequency}"); + Console.WriteLine($"SystemFrequency = {myCounterSample1.SystemFrequency}"); + Console.WriteLine($"TimeStamp = {myCounterSample1.TimeStamp}"); + Console.WriteLine($"TimeStamp100nSec = {myCounterSample1.TimeStamp100nSec}"); + Console.WriteLine($"CounterType = {myCounterSample1.CounterType}"); + // + Console.WriteLine(""); + Console.WriteLine(""); + // + PerformanceCounter myPerformanceCounter2 = new PerformanceCounter + ("Processor", "% Processor Time", "0"); + CounterSample myCounterSample2 = new CounterSample(10L, 20L, 30L, 40L, 50L, 60L, + PerformanceCounterType.AverageCount64, 300); + Console.WriteLine($"CounterTimeStamp = {myCounterSample2.CounterTimeStamp}"); + Console.WriteLine($"BaseValue = {myCounterSample2.BaseValue}"); + Console.WriteLine($"RawValue = {myCounterSample2.RawValue}"); + Console.WriteLine($"CounterFrequency = {myCounterSample2.CounterFrequency}"); + Console.WriteLine($"SystemFrequency = {myCounterSample2.SystemFrequency}"); + Console.WriteLine($"TimeStamp = {myCounterSample2.TimeStamp}"); + Console.WriteLine($"TimeStamp100nSec = {myCounterSample2.TimeStamp100nSec}"); + Console.WriteLine($"CounterType = {myCounterSample2.CounterType}"); + Console.WriteLine($"CounterTimeStamp = {myCounterSample2.CounterTimeStamp}"); + // Hold the results of sample. + myCounterSample2 = myPerformanceCounter2.NextSample(); + Console.WriteLine($"BaseValue = {myCounterSample2.BaseValue}"); + Console.WriteLine($"RawValue = {myCounterSample2.RawValue}"); + Console.WriteLine($"CounterFrequency = {myCounterSample2.CounterFrequency}"); + Console.WriteLine($"SystemFrequency = {myCounterSample2.SystemFrequency}"); + Console.WriteLine($"TimeStamp = {myCounterSample2.TimeStamp}"); + Console.WriteLine($"TimeStamp100nSec = {myCounterSample2.TimeStamp100nSec}"); + Console.WriteLine($"CounterType = {myCounterSample2.CounterType}"); + Console.WriteLine($"CounterTimeStamp = {myCounterSample2.CounterTimeStamp}"); + // + } } diff --git a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/Program.cs b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/Program.cs new file mode 100644 index 00000000000..14e97ea792d --- /dev/null +++ b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/Program.cs @@ -0,0 +1,4 @@ +StandardAsyncOutputExample.Run(); +ProcessAsyncStreamSamples.ProcessAsyncSample.Run(); +ProcessAsyncStreamSamples.ProcessSample.Run(); +ProcessAsyncStreamSamples.ProcessSortSample.Run(); diff --git a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/Project.csproj index 2810605dfc8..dfb40caafcf 100644 --- a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/Project.csproj @@ -1,7 +1,7 @@ - library + Exe net10.0 enable enable diff --git a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/datareceivedevent.cs b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/datareceivedevent.cs index 44261250ba5..9711ddf44ad 100644 --- a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/datareceivedevent.cs +++ b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/datareceivedevent.cs @@ -7,7 +7,7 @@ class StandardAsyncOutputExample private static int s_lineCount = 0; private static readonly StringBuilder s_output = new(); - public static void Main() + public static void Run() { Process process = new(); process.StartInfo.FileName = "ipconfig.exe"; @@ -19,7 +19,7 @@ public static void Main() if (!string.IsNullOrEmpty(e.Data)) { s_lineCount++; - s_output.Append("\n[" + s_lineCount + "]: " + e.Data); + s_output.Append($"\n[{s_lineCount}]: {e.Data}"); } }); diff --git a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/net_async.cs b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/net_async.cs index feb1727e783..4b063cb1f62 100644 --- a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/net_async.cs +++ b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/net_async.cs @@ -121,7 +121,7 @@ public static void RedirectNetCommandStreams() { // Signal that the error file had something // written to it. - string[] errorOutput = File.ReadAllLines(s_netErrorFile); + string[] errorOutput = File.ReadAllLines(s_netErrorFile!); if (errorOutput.Length > 0) { Console.WriteLine($"\nThe following error output was appended to {s_netErrorFile}:"); @@ -143,7 +143,7 @@ private static void NetOutputDataHandler(object sendingProcess, if (!string.IsNullOrEmpty(outLine.Data)) { // Add the text to the collected output. - s_netOutput.Append(Environment.NewLine + " " + outLine.Data); + s_netOutput!.Append($"{Environment.NewLine} {outLine.Data}"); } } @@ -162,12 +162,12 @@ private static void NetErrorDataHandler(object sendingProcess, // Open the file. try { - s_streamError = new StreamWriter(s_netErrorFile, true); + s_streamError = new StreamWriter(s_netErrorFile!, true); } catch (Exception e) { Console.WriteLine("Could not open error file!"); - Console.WriteLine(e.Message.ToString()); + Console.WriteLine(e.Message); } } @@ -176,7 +176,7 @@ private static void NetErrorDataHandler(object sendingProcess, // Write a header to the file if this is the first // call to the error output handler. s_streamError.WriteLine(); - s_streamError.WriteLine(DateTime.Now.ToString()); + s_streamError.WriteLine(DateTime.Now); s_streamError.WriteLine("Net View error output:"); } s_errorsWritten = true; @@ -199,7 +199,7 @@ namespace ProcessAsyncStreamSamples class ProcessAsyncSample { /// The main entry point for the application. - static void Run() + public static void Run() { try { @@ -208,7 +208,7 @@ static void Run() catch (InvalidOperationException e) { Console.WriteLine("Exception:"); - Console.WriteLine(e.ToString()); + Console.WriteLine(e); } } } diff --git a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/nmake_async.cs b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/nmake_async.cs index a06b5e7e0a8..65101dce49e 100644 --- a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/nmake_async.cs +++ b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/nmake_async.cs @@ -82,11 +82,10 @@ public static void RedirectNMakeCommandStreams() Console.WriteLine($"Nmake output logged to {buildLogFile}"); s_buildLogStream.WriteLine(); - s_buildLogStream.WriteLine(DateTime.Now.ToString()); + s_buildLogStream.WriteLine(DateTime.Now); if (!string.IsNullOrEmpty(nmakeArguments)) { - s_buildLogStream.Write("Command line = NMake {0}", - nmakeArguments); + s_buildLogStream.Write($"Command line = NMake {nmakeArguments}"); } else { @@ -180,7 +179,7 @@ private static void NMakeErrorDataHandler(object sendingProcess, LogToFile("StdErr", "", true); - // Stop reading the output streams + // Stop reading the output streams. if (sendingProcess is Process p) { p.CancelErrorRead(); @@ -205,7 +204,7 @@ private static void LogToFile(string logPrefix, if (!string.IsNullOrEmpty(logPrefix)) { - logString.AppendFormat("{0}> ", logPrefix); + logString.Append($"{logPrefix}> "); } if (!string.IsNullOrEmpty(logText)) @@ -215,14 +214,13 @@ private static void LogToFile(string logPrefix, if (s_buildLogStream != null) { - s_buildLogStream.WriteLine("[{0}] {1}", - DateTime.Now.ToString(), logString.ToString()); + s_buildLogStream.WriteLine($"[{DateTime.Now}] {logString}"); s_buildLogStream.Flush(); } if (echoToConsole) { - Console.WriteLine(logString.ToString()); + Console.WriteLine(logString); } } } @@ -234,7 +232,7 @@ namespace ProcessAsyncStreamSamples class ProcessSample { /// The main entry point for the application. - static void Run() + public static void Run() { try { @@ -243,7 +241,7 @@ static void Run() catch (InvalidOperationException e) { Console.WriteLine("Exception:"); - Console.WriteLine(e.ToString()); + Console.WriteLine(e); } } } diff --git a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/sort_async.cs b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/sort_async.cs index 3ddaea0bef2..933939b116d 100644 --- a/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/sort_async.cs +++ b/snippets/csharp/System.Diagnostics/DataReceivedEventArgs/Overview/sort_async.cs @@ -98,7 +98,7 @@ private static void SortOutputHandler(object sendingProcess, s_numOutputLines++; // Add the text to the collected output. - s_sortOutput.Append($"{Environment.NewLine}[{s_numOutputLines}] - {outLine.Data}"); + s_sortOutput!.Append($"{Environment.NewLine}[{s_numOutputLines}] - {outLine.Data}"); } } } @@ -108,7 +108,7 @@ namespace ProcessAsyncStreamSamples { class ProcessSortSample { - static void Run() + public static void Run() { try { diff --git a/snippets/csharp/System.Diagnostics/Debug/Assert/source.cs b/snippets/csharp/System.Diagnostics/Debug/Assert/source.cs index 2c08a99eaf4..c1aa48d3cac 100644 --- a/snippets/csharp/System.Diagnostics/Debug/Assert/source.cs +++ b/snippets/csharp/System.Diagnostics/Debug/Assert/source.cs @@ -1,6 +1,4 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; // // Create an index for an array. diff --git a/snippets/csharp/System.Diagnostics/Debug/Assert/source1.cs b/snippets/csharp/System.Diagnostics/Debug/Assert/source1.cs index fcf777ab31f..faaf2ad9c4c 100644 --- a/snippets/csharp/System.Diagnostics/Debug/Assert/source1.cs +++ b/snippets/csharp/System.Diagnostics/Debug/Assert/source1.cs @@ -1,5 +1,4 @@ using System; -using System.Data; using System.Diagnostics; public class Form2 @@ -7,7 +6,7 @@ public class Form2 // public static void MyMethod(Type type, Type baseType) { - Debug.Assert(type != null, "Type parameter is null"); + Debug.Assert(type is not null, "Type parameter is null"); // Perform some processing. } diff --git a/snippets/csharp/System.Diagnostics/Debug/Assert/source2.cs b/snippets/csharp/System.Diagnostics/Debug/Assert/source2.cs index 71b956b465d..5c3acbb806f 100644 --- a/snippets/csharp/System.Diagnostics/Debug/Assert/source2.cs +++ b/snippets/csharp/System.Diagnostics/Debug/Assert/source2.cs @@ -1,5 +1,4 @@ using System; -using System.Data; using System.Diagnostics; public class Form3 @@ -7,8 +6,8 @@ public class Form3 // public static void MyMethod(Type type, Type baseType) { - Debug.Assert(type != null, "Type parameter is null", - "Can't get object for null type"); + Debug.Assert(type is not null, "Type parameter is null", + "Can't get object for null type"); // Perform some processing. } diff --git a/snippets/csharp/System.Diagnostics/Debug/Close/source.cs b/snippets/csharp/System.Diagnostics/Debug/Close/source.cs index 20cc3fc0f8b..28451f7d191 100644 --- a/snippets/csharp/System.Diagnostics/Debug/Close/source.cs +++ b/snippets/csharp/System.Diagnostics/Debug/Close/source.cs @@ -2,8 +2,8 @@ // Specify /d:DEBUG when compiling. using System; -using System.IO; using System.Diagnostics; +using System.IO; class Test { diff --git a/snippets/csharp/System.Diagnostics/Debug/Fail/Project.csproj b/snippets/csharp/System.Diagnostics/Debug/Fail/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Diagnostics/Debug/Fail/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Diagnostics/Debug/Fail/source.cs b/snippets/csharp/System.Diagnostics/Debug/Fail/source.cs index 7d13b6970c6..9ace1acf260 100644 --- a/snippets/csharp/System.Diagnostics/Debug/Fail/source.cs +++ b/snippets/csharp/System.Diagnostics/Debug/Fail/source.cs @@ -1,38 +1,42 @@ using System; -using System.Data; using System.Diagnostics; public class Form1 { - protected enum Option { First, Second }; + protected enum Option + { + First, + Second + } - protected Option option; + private static Option SelectedOption { get; set; } - protected double result; + private static double Result { get; set; } public static void Main() { try - { } + { + } // catch (Exception) { - Debug.Fail("Unknown Option " + option + ", using the default."); + Debug.Fail($"Unknown Option {SelectedOption}, using the default."); } // // - switch (option) + switch (SelectedOption) { case Option.First: - result = 1.0; + Result = 1.0; break; // Insert additional cases. default: - Debug.Fail("Unknown Option " + option); - result = 1.0; + Debug.Fail($"Unknown Option {SelectedOption}"); + Result = 1.0; break; } // diff --git a/snippets/csharp/System.Diagnostics/Debug/Fail/source1.cs b/snippets/csharp/System.Diagnostics/Debug/Fail/source1.cs index 1d4b070e3e3..820fd52effb 100644 --- a/snippets/csharp/System.Diagnostics/Debug/Fail/source1.cs +++ b/snippets/csharp/System.Diagnostics/Debug/Fail/source1.cs @@ -1,14 +1,18 @@ using System; -using System.Data; using System.Diagnostics; public class Form2 { - protected enum MyOption { First, Second }; - protected MyOption option1; - protected double result; - protected double value; - protected double newValue; + protected enum MyOption + { + First, + Second + } + + private MyOption SelectedOption { get; set; } + private double Result { get; set; } + private double Value { get; set; } + private double NewValue { get; set; } protected void Method() { try @@ -17,24 +21,24 @@ protected void Method() // catch (Exception) { - Debug.Fail("Invalid value: " + value.ToString(), + Debug.Fail($"Invalid value: {Value}", "Resetting value to newValue."); - value = newValue; + Value = NewValue; } // // - switch (option1) + switch (SelectedOption) { case MyOption.First: - result = 1.0; + Result = 1.0; break; // Insert additional cases. default: - Debug.Fail("Unknown Option " + option1, "Result set to 1.0"); - result = 1.0; + Debug.Fail($"Unknown Option {SelectedOption}", "Result set to 1.0"); + Result = 1.0; break; } // diff --git a/snippets/csharp/System.Diagnostics/Debug/Indent/source.cs b/snippets/csharp/System.Diagnostics/Debug/Indent/source.cs index 30c82698a48..6449e743445 100644 --- a/snippets/csharp/System.Diagnostics/Debug/Indent/source.cs +++ b/snippets/csharp/System.Diagnostics/Debug/Indent/source.cs @@ -1,6 +1,4 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; // Debug.WriteLine("List of errors:"); diff --git a/snippets/csharp/System.Diagnostics/Debug/Overview/source.cs b/snippets/csharp/System.Diagnostics/Debug/Overview/source.cs index 2bc469bab02..aa061f43c8b 100644 --- a/snippets/csharp/System.Diagnostics/Debug/Overview/source.cs +++ b/snippets/csharp/System.Diagnostics/Debug/Overview/source.cs @@ -2,20 +2,13 @@ // Specify /d:DEBUG when compiling. using System; -using System.Data; using System.Diagnostics; -class Test -{ - static void Main() - { - Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); - Debug.AutoFlush = true; - Debug.Indent(); - Debug.WriteLine("Entering Main"); - Console.WriteLine("Hello World."); - Debug.WriteLine("Exiting Main"); - Debug.Unindent(); - } -} +Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); +Debug.AutoFlush = true; +Debug.Indent(); +Debug.WriteLine("Entering Main"); +Console.WriteLine("Hello World."); +Debug.WriteLine("Exiting Main"); +Debug.Unindent(); // diff --git a/snippets/csharp/System.Diagnostics/Debug/Write/source.cs b/snippets/csharp/System.Diagnostics/Debug/Write/source.cs index 2636b6f4e3f..daf7d9bbd6d 100644 --- a/snippets/csharp/System.Diagnostics/Debug/Write/source.cs +++ b/snippets/csharp/System.Diagnostics/Debug/Write/source.cs @@ -1,25 +1,29 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; class Class1 { - public static void Main() { } + public static void Main() + { + } // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(Object myObject, string category) + public static void MyErrorMethod(object myObject, string category) { // Write the message if the TraceSwitch level is set to Error or higher. - if (generalSwitch.TraceError) + if (s_generalSwitch.TraceError) + { Debug.Write(myObject, category); + } // Write a second message if the TraceSwitch level is set to Verbose. - if (generalSwitch.TraceVerbose) + if (s_generalSwitch.TraceVerbose) + { Debug.WriteLine(" Object is not valid for this category."); + } } // } diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteIf/Project.csproj b/snippets/csharp/System.Diagnostics/Debug/WriteIf/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Diagnostics/Debug/WriteIf/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteIf/source.cs b/snippets/csharp/System.Diagnostics/Debug/WriteIf/source.cs index 3be79299d96..6087007d368 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteIf/source.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteIf/source.cs @@ -1,13 +1,11 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; // // Class-level declaration. // Create a TraceSwitch. -TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); +TraceSwitch generalSwitch = new("General", "Entire Application"); -static void MyErrorMethod() +void MyErrorMethod() { // Write the message if the TraceSwitch level is set to Error or higher. Debug.WriteIf(generalSwitch.TraceError, "My error message. "); diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteIf/source1.cs b/snippets/csharp/System.Diagnostics/Debug/WriteIf/source1.cs index 655c8c2eb35..71f4879d027 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteIf/source1.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteIf/source1.cs @@ -1,6 +1,4 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; public class Form2 @@ -8,15 +6,15 @@ public class Form2 // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(Object myObject) + public static void MyErrorMethod(object myObject) { // Write the message if the TraceSwitch level is set to Error or higher. - Debug.WriteIf(generalSwitch.TraceError, myObject); + Debug.WriteIf(s_generalSwitch.TraceError, myObject); // Write a second message if the TraceSwitch level is set to Verbose. - Debug.WriteLineIf(generalSwitch.TraceVerbose, " is not a valid value for this method."); + Debug.WriteLineIf(s_generalSwitch.TraceVerbose, " is not a valid value for this method."); } // } diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteIf/source2.cs b/snippets/csharp/System.Diagnostics/Debug/WriteIf/source2.cs index c2be75d1b8f..7d75a40f346 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteIf/source2.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteIf/source2.cs @@ -1,6 +1,4 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; public class Form3 @@ -8,16 +6,16 @@ public class Form3 // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(Object myObject, string category) + public static void MyErrorMethod(object myObject, string category) { // Write the message if the TraceSwitch level is set to Verbose. - Debug.WriteIf(generalSwitch.TraceVerbose, myObject.ToString() + - " is not a valid object for category: ", category); + Debug.WriteIf(s_generalSwitch.TraceVerbose, + $"{myObject} is not a valid object for category: ", category); // Write a second message if the TraceSwitch level is set to Error or higher. - Debug.WriteLineIf(generalSwitch.TraceError, " Please use a different category."); + Debug.WriteLineIf(s_generalSwitch.TraceError, " Please use a different category."); } // } diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteIf/source3.cs b/snippets/csharp/System.Diagnostics/Debug/WriteIf/source3.cs index dc75105a7aa..8f47cb282f6 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteIf/source3.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteIf/source3.cs @@ -1,6 +1,4 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; public class Form4 @@ -8,15 +6,15 @@ public class Form4 // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(Object myObject, string category) + public static void MyErrorMethod(object myObject, string category) { // Write the message if the TraceSwitch level is set to Verbose. - Debug.WriteIf(generalSwitch.TraceVerbose, myObject, category); + Debug.WriteIf(s_generalSwitch.TraceVerbose, myObject, category); // Write a second message if the TraceSwitch level is set to Error or higher. - Debug.WriteLineIf(generalSwitch.TraceError, " Object is not valid for this category."); + Debug.WriteLineIf(s_generalSwitch.TraceError, " Object is not valid for this category."); } // } diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLine/Project.csproj b/snippets/csharp/System.Diagnostics/Debug/WriteLine/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLine/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLine/source.cs b/snippets/csharp/System.Diagnostics/Debug/WriteLine/source.cs index daad9a5aca2..e3095baa706 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteLine/source.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLine/source.cs @@ -1,20 +1,22 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; // // Class-level declaration. // Create a TraceSwitch. -TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); +TraceSwitch generalSwitch = new("General", "Entire Application"); -static void MyErrorMethod() +void MyErrorMethod() { // Write the message if the TraceSwitch level is set to Error or higher. if (generalSwitch.TraceError) + { Debug.Write("My error message. "); + } // Write a second message if the TraceSwitch level is set to Verbose. if (generalSwitch.TraceVerbose) + { Debug.WriteLine("My second error message."); + } } // diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLine/source1.cs b/snippets/csharp/System.Diagnostics/Debug/WriteLine/source1.cs index 055c3a9b987..7851bce85e4 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteLine/source1.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLine/source1.cs @@ -1,6 +1,4 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; public class Form2 @@ -8,17 +6,21 @@ public class Form2 // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(Object myObject) + public static void MyErrorMethod(object myObject) { // Write the message if the TraceSwitch level is set to Error or higher. - if (generalSwitch.TraceError) + if (s_generalSwitch.TraceError) + { Debug.Write("Invalid object. "); + } // Write a second message if the TraceSwitch level is set to Verbose. - if (generalSwitch.TraceVerbose) + if (s_generalSwitch.TraceVerbose) + { Debug.WriteLine(myObject); + } } // } diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLine/source2.cs b/snippets/csharp/System.Diagnostics/Debug/WriteLine/source2.cs index 218e372d72a..2eaeb2cb931 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteLine/source2.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLine/source2.cs @@ -1,6 +1,4 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; public class Form3 @@ -8,17 +6,21 @@ public class Form3 // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(string category) + public static void MyErrorMethod(string category) { // Write the message if the TraceSwitch level is set to Error or higher. - if (generalSwitch.TraceError) + if (s_generalSwitch.TraceError) + { Debug.Write("My error message. "); + } // Write a second message if the TraceSwitch level is set to Verbose. - if (generalSwitch.TraceVerbose) + if (s_generalSwitch.TraceVerbose) + { Debug.WriteLine("My second error message.", category); + } } // } diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLine/source3.cs b/snippets/csharp/System.Diagnostics/Debug/WriteLine/source3.cs index 4230613b8a6..a308cba0d93 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteLine/source3.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLine/source3.cs @@ -1,6 +1,4 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; public class Form4 @@ -8,17 +6,21 @@ public class Form4 // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(Object myObject, string category) + public static void MyErrorMethod(object myObject, string category) { // Write the message if the TraceSwitch level is set to Error or higher. - if (generalSwitch.TraceError) + if (s_generalSwitch.TraceError) + { Debug.Write("Invalid object for category. "); + } // Write a second message if the TraceSwitch level is set to Verbose. - if (generalSwitch.TraceVerbose) + if (s_generalSwitch.TraceVerbose) + { Debug.WriteLine(myObject, category); + } } // } diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/Project.csproj b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/Project.csproj new file mode 100644 index 00000000000..36a29620edb --- /dev/null +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/Project.csproj @@ -0,0 +1,6 @@ + + + Exe + net10.0 + + diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source.cs b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source.cs index d2d4f4974e1..7e10f8885bb 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source.cs @@ -1,13 +1,11 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; // // Class-level declaration. // Create a TraceSwitch. -TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); +TraceSwitch generalSwitch = new("General", "Entire Application"); -static void MyErrorMethod() +void MyErrorMethod() { // Write the message if the TraceSwitch level is set to Error or higher. Debug.WriteIf(generalSwitch.TraceError, "My error message. "); diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source1.cs b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source1.cs index 58e02eb218b..88d03b24f29 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source1.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source1.cs @@ -1,21 +1,19 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; public class Form2 { // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(Object myObject) + public static void MyErrorMethod(object myObject) { // Write the message if the TraceSwitch level is set to Error or higher. - Debug.WriteIf(generalSwitch.TraceError, "Invalid object. "); + Debug.WriteIf(s_generalSwitch.TraceError, "Invalid object. "); // Write a second message if the TraceSwitch level is set to Verbose. - Debug.WriteLineIf(generalSwitch.TraceVerbose, myObject); + Debug.WriteLineIf(s_generalSwitch.TraceVerbose, myObject); } // } diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source2.cs b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source2.cs index 4c3be2175de..86f9bd3105f 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source2.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source2.cs @@ -1,21 +1,19 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; public class Form3 { // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(string category) + public static void MyErrorMethod(string category) { // Write the message if the TraceSwitch level is set to Error or higher. - Debug.WriteIf(generalSwitch.TraceError, "My error message. "); + Debug.WriteIf(s_generalSwitch.TraceError, "My error message. "); // Write a second message if the TraceSwitch level is set to Verbose. - Debug.WriteLineIf(generalSwitch.TraceVerbose, "My second error message.", category); + Debug.WriteLineIf(s_generalSwitch.TraceVerbose, "My second error message.", category); } // } diff --git a/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source3.cs b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source3.cs index 0c4576a1249..6546ca1a345 100644 --- a/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source3.cs +++ b/snippets/csharp/System.Diagnostics/Debug/WriteLineIf/source3.cs @@ -1,21 +1,19 @@ -using System; -using System.Data; -using System.Diagnostics; +using System.Diagnostics; public class Form4 { // // Class-level declaration. // Create a TraceSwitch. - static TraceSwitch generalSwitch = new TraceSwitch("General", "Entire Application"); + private static readonly TraceSwitch s_generalSwitch = new("General", "Entire Application"); - static public void MyErrorMethod(Object myObject, string category) + public static void MyErrorMethod(object myObject, string category) { // Write the message if the TraceSwitch level is set to Error or higher. - Debug.WriteIf(generalSwitch.TraceError, "Invalid object for category. "); + Debug.WriteIf(s_generalSwitch.TraceError, "Invalid object for category. "); // Write a second message if the TraceSwitch level is set to Verbose. - Debug.WriteLineIf(generalSwitch.TraceVerbose, myObject, category); + Debug.WriteLineIf(s_generalSwitch.TraceVerbose, myObject, category); } // } diff --git a/snippets/csharp/System.Diagnostics/DebuggerBrowsableAttribute/.ctor/Project.csproj b/snippets/csharp/System.Diagnostics/DebuggerBrowsableAttribute/.ctor/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Diagnostics/DebuggerBrowsableAttribute/.ctor/Project.csproj +++ b/snippets/csharp/System.Diagnostics/DebuggerBrowsableAttribute/.ctor/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Diagnostics/DebuggerBrowsableAttribute/.ctor/program.cs b/snippets/csharp/System.Diagnostics/DebuggerBrowsableAttribute/.ctor/program.cs index e695f9e28a6..3a98633ffe7 100644 --- a/snippets/csharp/System.Diagnostics/DebuggerBrowsableAttribute/.ctor/program.cs +++ b/snippets/csharp/System.Diagnostics/DebuggerBrowsableAttribute/.ctor/program.cs @@ -2,7 +2,6 @@ using System; using System.Collections; using System.Diagnostics; -using System.Reflection; class DebugViewTest { @@ -17,10 +16,10 @@ class DebugViewTest static void Main() { - MyHashtable myHashTable = new MyHashtable(); + MyHashtable myHashTable = new(); myHashTable.Add("one", 1); myHashTable.Add("two", 2); - Console.WriteLine(myHashTable.ToString()); + Console.WriteLine(myHashTable); Console.WriteLine("In Main."); } } @@ -28,9 +27,9 @@ static void Main() [DebuggerDisplay("{value}", Name = "{key}")] internal class KeyValuePairs { - private IDictionary dictionary; - private object key; - private object value; + private readonly IDictionary dictionary; + private readonly object key; + private readonly object value; public KeyValuePairs(IDictionary dictionary, object key, object value) { @@ -51,7 +50,7 @@ class MyHashtable : Hashtable internal class HashtableDebugView { - private Hashtable hashtable; + private readonly Hashtable hashtable; public const string TestString = "This should appear in the debug window."; public HashtableDebugView(Hashtable hashtable) { @@ -67,15 +66,15 @@ public KeyValuePairs[] Keys KeyValuePairs[] keys = new KeyValuePairs[hashtable.Count]; int i = 0; - foreach(object key in hashtable.Keys) + foreach (object key in hashtable.Keys) { - keys[i] = new KeyValuePairs(hashtable, key, hashtable[key]); + keys[i] = new(hashtable, key, hashtable[key]); i++; } return keys; } } - // + // } } // diff --git a/snippets/csharp/System.Diagnostics/DefaultTraceListener/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/DefaultTraceListener/Overview/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Diagnostics/DefaultTraceListener/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/DefaultTraceListener/Overview/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Diagnostics/DefaultTraceListener/Overview/binomial.cs b/snippets/csharp/System.Diagnostics/DefaultTraceListener/Overview/binomial.cs index 5fdfc09a81c..b44fde7aa20 100644 --- a/snippets/csharp/System.Diagnostics/DefaultTraceListener/Overview/binomial.cs +++ b/snippets/csharp/System.Diagnostics/DefaultTraceListener/Overview/binomial.cs @@ -2,7 +2,6 @@ // using System; using System.Diagnostics; -using Microsoft.VisualBasic; class Binomial { @@ -14,7 +13,7 @@ public static void Main(string[] args) // decimal possibilities; - decimal iter; + decimal i; // // @@ -30,7 +29,7 @@ public static void Main(string[] args) Trace.Listeners.Add(defaultListener); // Assign the log file specification from the command line, if entered. - if (args.Length>=2) + if (args.Length >= 2) { defaultListener.LogFileName = args[1]; } @@ -38,28 +37,27 @@ public static void Main(string[] args) // // Validate the number of possibilities argument. - if (args.Length>=1) + if (args.Length >= 1) - // Verify that the argument is a number within the correct range. + // Verify that the argument is a number within the correct range. { try { - const decimal MAX_POSSIBILITIES = 99; + const decimal MaxPossibilities = 99; possibilities = Decimal.Parse(args[0]); - if (possibilities<0||possibilities>MAX_POSSIBILITIES) + if (possibilities < 0 || possibilities > MaxPossibilities) { - throw new Exception(String.Format("The number of possibilities must " + - "be in the range 0..{0}.", MAX_POSSIBILITIES)); + throw new Exception( + $"The number of possibilities must be in the range 0..{MaxPossibilities}."); } } - catch(Exception ex) + catch (Exception ex) { - string failMessage = String.Format("\"{0}\" " + - "is not a valid number of possibilities.", args[0]); + string failMessage = $"\"{args[0]}\" is not a valid number of possibilities."; defaultListener.Fail(failMessage, ex.Message); if (!defaultListener.AssertUiEnabled) { - Console.WriteLine(failMessage+ "\n" +ex.Message); + Console.WriteLine($"{failMessage}\n{ex.Message}"); } return; } @@ -79,7 +77,7 @@ public static void Main(string[] args) return; } - for(iter=0; iter<=possibilities; iter++) + for (i = 0; i <= possibilities; i++) { // decimal result; @@ -91,17 +89,17 @@ public static void Main(string[] args) try { // - result = CalcBinomial(possibilities, iter); + result = CalcBinomial(possibilities, i); // } - catch(Exception ex) + catch (Exception ex) { - string failMessage = String.Format("An exception was raised when " + - "calculating Binomial( {0}, {1} ).", possibilities, iter); + string failMessage = + $"An exception was raised when calculating Binomial( {possibilities}, {i} )."; defaultListener.Fail(failMessage, ex.Message); if (!defaultListener.AssertUiEnabled) { - Console.WriteLine(failMessage+ "\n" +ex.Message); + Console.WriteLine($"{failMessage}\n{ex.Message}"); } return; } @@ -109,10 +107,10 @@ public static void Main(string[] args) // // Format the trace and console output. - binomial = String.Format("Binomial( {0}, {1} ) = ", possibilities, iter); + binomial = $"Binomial( {possibilities}, {i} ) = "; defaultListener.Write(binomial); - defaultListener.WriteLine(result.ToString()); - Console.WriteLine("{0} {1}", binomial, result); + defaultListener.WriteLine(result); + Console.WriteLine($"{binomial} {result}"); // } } @@ -122,11 +120,11 @@ public static decimal CalcBinomial(decimal possibilities, decimal outcomes) // Calculate a binomial coefficient, and minimize the chance of overflow. decimal result = 1; - decimal iter; - for(iter=1; iter<=possibilities-outcomes; iter++) + decimal i; + for (i = 1; i <= possibilities - outcomes; i++) { - result *= outcomes+iter; - result /= iter; + result *= outcomes + i; + result /= i; } return result; } diff --git a/snippets/csharp/System.Diagnostics/DefaultTraceListener/Write/Project.csproj b/snippets/csharp/System.Diagnostics/DefaultTraceListener/Write/Project.csproj index a369cfa8a80..ffb97e9872d 100644 --- a/snippets/csharp/System.Diagnostics/DefaultTraceListener/Write/Project.csproj +++ b/snippets/csharp/System.Diagnostics/DefaultTraceListener/Write/Project.csproj @@ -1,7 +1,7 @@ - Library + Exe net10.0 diff --git a/snippets/csharp/System.Diagnostics/DefaultTraceListener/Write/defaulttracelistener.cs b/snippets/csharp/System.Diagnostics/DefaultTraceListener/Write/defaulttracelistener.cs index 802286c5604..e4404bcb838 100644 --- a/snippets/csharp/System.Diagnostics/DefaultTraceListener/Write/defaulttracelistener.cs +++ b/snippets/csharp/System.Diagnostics/DefaultTraceListener/Write/defaulttracelistener.cs @@ -1,7 +1,6 @@ // using System; using System.Diagnostics; -using Microsoft.VisualBasic; class DefaultTraceListenerMod { @@ -26,35 +25,34 @@ public static void Main(string[] args) // // Assign the log file specification from the command line, if entered. - if (args.Length>=2) + if (args.Length >= 2) { defaultListener.LogFileName = args[1]; } // Validate the number of possibilities argument. - if (args.Length>=1) + if (args.Length >= 1) - // - // Verify that the argument is a number within the correct range. + // + // Verify that the argument is a number within the correct range. { try { - const decimal MAX_POSSIBILITIES = 99; + const decimal MaxPossibilities = 99; possibilities = Decimal.Parse(args[0]); - if (possibilities<0||possibilities>MAX_POSSIBILITIES) + if (possibilities < 0 || possibilities > MaxPossibilities) { - throw new Exception(String.Format("The number of possibilities must " + - "be in the range 0..{0}.", MAX_POSSIBILITIES)); + throw new Exception( + $"The number of possibilities must be in the range 0..{MaxPossibilities}."); } } - catch(Exception ex) + catch (Exception ex) { - string failMessage = String.Format("\"{0}\" " + - "is not a valid number of possibilities.", args[0]); + string failMessage = $"\"{args[0]}\" is not a valid number of possibilities."; defaultListener.Fail(failMessage, ex.Message); if (!defaultListener.AssertUiEnabled) { - Console.WriteLine(failMessage+ "\n" + ex.Message); + Console.WriteLine($"{failMessage}\n{ex.Message}"); } return; } @@ -76,21 +74,24 @@ public static void Main(string[] args) return; } - decimal iter; - for(iter=0; iter<=possibilities; iter++) + decimal i; + for (i = 0; i <= possibilities; i++) { // // Compute the next binomial coefficient. // If an exception is thrown, quit. - decimal result = CalcBinomial(possibilities, iter); - if (result==0) {return;} + decimal result = CalcBinomial(possibilities, i); + if (result == 0) + { + return; + } // Format the trace and console output. - string binomial = String.Format("Binomial( {0}, {1} ) = ", possibilities, iter); + string binomial = $"Binomial( {possibilities}, {i} ) = "; defaultListener.Write(binomial); - defaultListener.WriteLine(result.ToString()); - Console.WriteLine("{0} {1}", binomial, result); + defaultListener.WriteLine(result); + Console.WriteLine($"{binomial} {result}"); // } } @@ -105,22 +106,22 @@ public static decimal CalcBinomial(decimal possibilities, decimal outcomes) { // Calculate a binomial coefficient, and minimize the chance // of overflow. - decimal iter; - for(iter=1; iter<=possibilities-outcomes; iter++) + decimal i; + for (i = 1; i <= possibilities - outcomes; i++) { - result *= outcomes+iter; - result /= iter; + result *= outcomes + i; + result /= i; } return result; } - catch(Exception ex) + catch (Exception ex) { - string failMessage = String.Format("An exception was raised when " + - "calculating Binomial( {0}, {1} ).", possibilities, outcomes); + string failMessage = + $"An exception was raised when calculating Binomial( {possibilities}, {outcomes} )."; defaultListener.Fail(failMessage, ex.Message); if (!defaultListener.AssertUiEnabled) { - Console.WriteLine(failMessage + "\n" + ex.Message); + Console.WriteLine($"{failMessage}\n{ex.Message}"); } return 0; } diff --git a/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/.ctor/Project.csproj b/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/.ctor/Project.csproj index e17ba622dbc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/.ctor/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/.ctor/Project.csproj @@ -1,13 +1,12 @@ - Library - net10.0-windows - true + Exe + net10.0 - + diff --git a/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/.ctor/entrywritteneventargs_ctor2.cs b/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/.ctor/entrywritteneventargs_ctor2.cs index d2803655e38..e4b6fc59cd2 100644 --- a/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/.ctor/entrywritteneventargs_ctor2.cs +++ b/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/.ctor/entrywritteneventargs_ctor2.cs @@ -18,9 +18,11 @@ public static void Main() { try { - EventLog myNewLog = new EventLog(); - myNewLog.Log = "MyNewLog"; - myNewLog.Source = "MySource"; + using EventLog myNewLog = new() + { + Log = "MyNewLog", + Source = "MySource" + }; // Create the source if it does not exist already. if (!EventLog.SourceExists("MySource")) { @@ -38,23 +40,21 @@ public static void Main() myNewLog.WriteEntry("The Latest entry in the Event Log"); int myEntries = myNewLog.Entries.Count; EventLogEntry entry = myNewLog.Entries[myEntries - 1]; - EntryWrittenEventArgs myEntryEventArgs = - new EntryWrittenEventArgs(entry); + EntryWrittenEventArgs myEntryEventArgs = new(entry); MyOnEntry(myNewLog, myEntryEventArgs); } catch (Exception e) { - Console.WriteLine("Exception Raised" + e.Message); + Console.WriteLine($"Exception Raised{e.Message}"); } } // - protected static void MyOnEntry(Object source, EntryWrittenEventArgs e) + protected static void MyOnEntry(object source, EntryWrittenEventArgs e) { EventLogEntry myEventLogEntry = e.Entry; if (myEventLogEntry != null) { - Console.WriteLine("Current message entry is: '" - + myEventLogEntry.Message + "'"); + Console.WriteLine($"Current message entry is: '{myEventLogEntry.Message}'"); } else { diff --git a/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/Overview/Project.csproj index e17ba622dbc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/Overview/Project.csproj @@ -1,13 +1,12 @@ - Library - net10.0-windows - true + Exe + net10.0 - + diff --git a/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/Overview/entrywritteneventargs_ctor1.cs b/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/Overview/entrywritteneventargs_ctor1.cs index 1e58c2a117e..0fa00d1f9d2 100644 --- a/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/Overview/entrywritteneventargs_ctor1.cs +++ b/snippets/csharp/System.Diagnostics/EntryWrittenEventArgs/Overview/entrywritteneventargs_ctor1.cs @@ -17,9 +17,11 @@ public static void Main() { try { - EventLog myNewLog = new EventLog(); - myNewLog.Log = "MyNewLog"; - myNewLog.Source = "MySource"; + using EventLog myNewLog = new() + { + Log = "MyNewLog", + Source = "MySource" + }; // Create the source if it does not exist already. if (!EventLog.SourceExists("MySource")) { @@ -37,19 +39,20 @@ public static void Main() myNewLog.WriteEntry("The Latest entry in the Event Log"); int myEntries = myNewLog.Entries.Count; EventLogEntry entry = myNewLog.Entries[myEntries - 1]; - EntryWrittenEventArgs myEntryEventArgs = - new EntryWrittenEventArgs(); + EntryWrittenEventArgs myEntryEventArgs = new(); MyOnEntry(myNewLog, myEntryEventArgs); } catch (Exception e) { - Console.WriteLine("Exception Raised" + e.Message); + Console.WriteLine($"Exception Raised{e.Message}"); } } - protected static void MyOnEntry(Object source, EntryWrittenEventArgs e) + protected static void MyOnEntry(object source, EntryWrittenEventArgs e) { - if (e.Entry == null) + if (e.Entry is null) + { Console.WriteLine("A new entry is written in MyNewLog."); + } } } // diff --git a/snippets/csharp/System.Diagnostics/EventInstance/Overview/Project.csproj b/snippets/csharp/System.Diagnostics/EventInstance/Overview/Project.csproj index e17ba622dbc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventInstance/Overview/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventInstance/Overview/Project.csproj @@ -1,13 +1,12 @@ - Library - net10.0-windows - true + Exe + net10.0 - + diff --git a/snippets/csharp/System.Diagnostics/EventInstance/Overview/source.cs b/snippets/csharp/System.Diagnostics/EventInstance/Overview/source.cs index 6e629d82442..9866b803950 100644 --- a/snippets/csharp/System.Diagnostics/EventInstance/Overview/source.cs +++ b/snippets/csharp/System.Diagnostics/EventInstance/Overview/source.cs @@ -4,8 +4,8 @@ namespace EventLogSamples { - class WriteEvent - { + class WriteEvent + { // // The following constants match the message definitions @@ -52,13 +52,12 @@ static void Main(string[] args) // Use the input argument as the message resource file. messageFile = args[0]; } - else { + else + { // Use the default message dll. - messageFile = String.Format("{0}\\{1}", - System.Environment.CurrentDirectory, - "EventLogMsgs.dll"); + messageFile = $"{Environment.CurrentDirectory}\\EventLogMsgs.dll"; } CleanUp(); @@ -78,9 +77,9 @@ static void CleanUp() // Delete the event source in order to re-register // the source with the latest configuration properties. - if(EventLog.SourceExists(sourceName)) + if (EventLog.SourceExists(sourceName)) { - Console.WriteLine("Deleting event source {0}.", sourceName); + Console.WriteLine($"Deleting event source {sourceName}."); EventLog.DeleteEventSource(sourceName); } } @@ -91,20 +90,19 @@ static void CreateEventSourceSample1(string messageFile) string sourceName = "SampleApplicationSource"; // Create the event source if it does not exist. - if(!EventLog.SourceExists(sourceName)) + if (!EventLog.SourceExists(sourceName)) { // Create a new event source for the custom event log // named "myNewLog." myLogName = "myNewLog"; - EventSourceCreationData mySourceData = new EventSourceCreationData(sourceName, myLogName); + EventSourceCreationData mySourceData = new(sourceName, myLogName); // Set the message resource file that the event source references. // All event resource identifiers correspond to text in this file. if (!System.IO.File.Exists(messageFile)) { - Console.WriteLine("Input message resource file does not exist - {0}", - messageFile); + Console.WriteLine($"Input message resource file does not exist - {messageFile}"); messageFile = ""; } else @@ -118,8 +116,7 @@ static void CreateEventSourceSample1(string messageFile) mySourceData.CategoryCount = CategoryCount; mySourceData.ParameterResourceFile = messageFile; - Console.WriteLine("Event source message resource file set to {0}", - messageFile); + Console.WriteLine($"Event source message resource file set to {messageFile}"); } Console.WriteLine("Registering new source for event log."); @@ -128,7 +125,7 @@ static void CreateEventSourceSample1(string messageFile) else { // Get the event log corresponding to the existing source. - myLogName = EventLog.LogNameFromSourceName(sourceName,"."); + myLogName = EventLog.LogNameFromSourceName(sourceName, "."); } // Register the localized name of the event log. @@ -136,7 +133,7 @@ static void CreateEventSourceSample1(string messageFile) // the event log name displayed in the Event Viewer might be // "Sample Application Log" or some other application-specific // text. - EventLog myEventLog = new EventLog(myLogName, ".", sourceName); + using EventLog myEventLog = new(myLogName, ".", sourceName); if (messageFile.Length > 0) { @@ -151,23 +148,21 @@ static void WriteEventSample1() // Create the event source if it does not exist. string sourceName = "SampleApplicationSource"; - if(!EventLog.SourceExists(sourceName)) + if (!EventLog.SourceExists(sourceName)) { // Call a local method to register the event log source // for the event log "myNewLog." Use the resource file // EventLogMsgs.dll in the current directory for message text. - string messageFile = String.Format("{0}\\{1}", - System.Environment.CurrentDirectory, - "EventLogMsgs.dll"); + string messageFile = $"{Environment.CurrentDirectory}\\EventLogMsgs.dll"; CreateEventSourceSample1(messageFile); } // Get the event log corresponding to the existing source. - string myLogName = EventLog.LogNameFromSourceName(sourceName,"."); + string myLogName = EventLog.LogNameFromSourceName(sourceName, "."); - EventLog myEventLog = new EventLog(myLogName, ".", sourceName); + using EventLog myEventLog = new(myLogName, ".", sourceName); // Define two audit events. @@ -177,14 +172,14 @@ static void WriteEventSample1() EventInstance myAuditFailEvent = new EventInstance(AuditFailedMsgId, 0, EventLogEntryType.FailureAudit); // Insert the method name into the event log message. - string [] insertStrings = {"EventLogSamples.WriteEventSample1"}; + string[] insertStrings = ["EventLogSamples.WriteEventSample1"]; // Write the events to the event log. myEventLog.WriteEvent(myAuditSuccessEvent, insertStrings); // Append binary data to the audit failure event entry. - byte [] binaryData = { 3, 4, 5, 6 }; + byte[] binaryData = [3, 4, 5, 6]; myEventLog.WriteEvent(myAuditFailEvent, binaryData, insertStrings); // @@ -195,7 +190,7 @@ static void WriteEventSample2() // string sourceName = "SampleApplicationSource"; - if(EventLog.SourceExists(sourceName)) + if (EventLog.SourceExists(sourceName)) { // Define an informational event and a warning event. @@ -206,20 +201,19 @@ static void WriteEventSample2() EventInstance myWarningEvent = new EventInstance(WarningMsgId, 0, EventLogEntryType.Warning); // Insert the method name into the event log message. - string [] insertStrings = {"EventLogSamples.WriteEventSample2"}; + string[] insertStrings = ["EventLogSamples.WriteEventSample2"]; // Write the events to the event log. EventLog.WriteEvent(sourceName, myInfoEvent); // Append binary data to the warning event entry. - byte [] binaryData = { 7, 8, 9, 10 }; + byte[] binaryData = [7, 8, 9, 10]; EventLog.WriteEvent(sourceName, myWarningEvent, binaryData, insertStrings); } else { - Console.WriteLine("Warning - event source {0} not registered", - sourceName); + Console.WriteLine($"Warning - event source {sourceName} not registered"); } // } @@ -232,7 +226,7 @@ static void EventInstanceSamples() // EventLogInstaller or EventLog.CreateEventSource. string sourceName = "SampleApplicationSource"; - if(EventLog.SourceExists(sourceName)) + if (EventLog.SourceExists(sourceName)) { // Define an informational event with no category. // The message identifier corresponds to the message text in the @@ -257,47 +251,43 @@ static void EventInstanceSamples() } else { - Console.WriteLine("Warning - event source {0} not registered", - sourceName); + Console.WriteLine($"Warning - event source {sourceName} not registered"); } // // // Get the event log corresponding to the existing source. - string myLogName = EventLog.LogNameFromSourceName(sourceName,"."); + string myLogName = EventLog.LogNameFromSourceName(sourceName, "."); // Find each instance of a specific event log entry in a // particular event log. - EventLog myEventLog = new EventLog(myLogName, "."); + using EventLog myEventLog = new(myLogName, "."); int count = 0; - Console.WriteLine("Searching event log entries for the event ID {0}...", - ServerConnectionDownMsgId.ToString()); + Console.WriteLine($"Searching event log entries for the event ID {ServerConnectionDownMsgId}..."); // Search for the resource ID, display the event text, // and display the number of matching entries. - foreach(EventLogEntry entry in myEventLog.Entries) + foreach (EventLogEntry entry in myEventLog.Entries) { if (entry.InstanceId == ServerConnectionDownMsgId) { - count ++; + count++; Console.WriteLine(); - Console.WriteLine("Entry ID = {0}", - entry.InstanceId.ToString()); - Console.WriteLine("Reported at {0}", - entry.TimeWritten.ToString()); + Console.WriteLine($"Entry ID = {entry.InstanceId}"); + Console.WriteLine($"Reported at {entry.TimeWritten}"); Console.WriteLine("Message text:"); - Console.WriteLine("\t{0}", entry.Message); + Console.WriteLine($"\t{entry.Message}"); } } Console.WriteLine(); - Console.WriteLine("Found {0} events with ID {1} in event log {2}.", - count.ToString(), ServerConnectionDownMsgId.ToString(), myLogName); + Console.WriteLine( + $"Found {count} events with ID {ServerConnectionDownMsgId} in event log {myLogName}."); // } } } -// \ No newline at end of file +// diff --git a/snippets/csharp/System.Diagnostics/EventLog/.ctor/Program.cs b/snippets/csharp/System.Diagnostics/EventLog/.ctor/Program.cs new file mode 100644 index 00000000000..92725bd09c8 --- /dev/null +++ b/snippets/csharp/System.Diagnostics/EventLog/.ctor/Program.cs @@ -0,0 +1,3 @@ +MySample.Run(); +MySample1.Run(); +MySample2.Run(); diff --git a/snippets/csharp/System.Diagnostics/EventLog/.ctor/Project.csproj b/snippets/csharp/System.Diagnostics/EventLog/.ctor/Project.csproj index f5f7d74ac47..ea2d5c6b0fc 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/.ctor/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLog/.ctor/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - MySample diff --git a/snippets/csharp/System.Diagnostics/EventLog/.ctor/source.cs b/snippets/csharp/System.Diagnostics/EventLog/.ctor/source.cs index d0d514c7170..874f509632a 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/.ctor/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/.ctor/source.cs @@ -5,7 +5,7 @@ class MySample { - public static void Main() + public static void Run() { // Create the source, if it does not already exist. if (!EventLog.SourceExists("MySource")) @@ -27,7 +27,7 @@ public static void Main() // Read the event log entries. foreach (EventLogEntry entry in myLog.Entries) { - Console.WriteLine("\tEntry: " + entry.Message); + Console.WriteLine($"\tEntry: {entry.Message}"); } } } diff --git a/snippets/csharp/System.Diagnostics/EventLog/.ctor/source1.cs b/snippets/csharp/System.Diagnostics/EventLog/.ctor/source1.cs index c38a365e628..101dc51e5a8 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/.ctor/source1.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/.ctor/source1.cs @@ -5,7 +5,7 @@ class MySample1 { - public static void Main() + public static void Run() { // Create the source, if it does not already exist. if (!EventLog.SourceExists("MySource")) @@ -26,7 +26,7 @@ public static void Main() // Read the event log entries. foreach (EventLogEntry entry in myLog.Entries) { - Console.WriteLine("\tEntry: " + entry.Message); + Console.WriteLine($"\tEntry: {entry.Message}"); } } } diff --git a/snippets/csharp/System.Diagnostics/EventLog/.ctor/source2.cs b/snippets/csharp/System.Diagnostics/EventLog/.ctor/source2.cs index 9118b1a509a..4d48c789db7 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/.ctor/source2.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/.ctor/source2.cs @@ -5,7 +5,7 @@ class MySample2 { - public static void Main() + public static void Run() { // Create the source, if it does not already exist. if (!EventLog.SourceExists("MySource")) @@ -24,7 +24,7 @@ public static void Main() EventLog myLog = new EventLog("myNewLog", ".", "MySource"); // Write an entry to the log. - myLog.WriteEntry("Writing to event log on " + myLog.MachineName); + myLog.WriteEntry($"Writing to event log on {myLog.MachineName}"); } } diff --git a/snippets/csharp/System.Diagnostics/EventLog/Clear/source.cs b/snippets/csharp/System.Diagnostics/EventLog/Clear/source.cs index b038babd9f0..461a2fc0cc0 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Clear/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/Clear/source.cs @@ -1,18 +1,12 @@ // -using System; using System.Diagnostics; -using System.Threading; -class MySample{ +// Create an EventLog instance and assign its log name. +using EventLog myLog = new() +{ + Log = "myNewLog" +}; - public static void Main(){ - - // Create an EventLog instance and assign its log name. - EventLog myLog = new EventLog(); - myLog.Log = "myNewLog"; - - myLog.Clear(); - } -} +myLog.Clear(); // diff --git a/snippets/csharp/System.Diagnostics/EventLog/CreateEventSource/Project.csproj b/snippets/csharp/System.Diagnostics/EventLog/CreateEventSource/Project.csproj new file mode 100644 index 00000000000..048ac323565 --- /dev/null +++ b/snippets/csharp/System.Diagnostics/EventLog/CreateEventSource/Project.csproj @@ -0,0 +1,10 @@ + + + Exe + net10.0 + + + + + + diff --git a/snippets/csharp/System.Diagnostics/EventLog/CreateEventSource/source.cs b/snippets/csharp/System.Diagnostics/EventLog/CreateEventSource/source.cs index 3383fccbd76..fbb3e224a08 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/CreateEventSource/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/CreateEventSource/source.cs @@ -1,35 +1,30 @@ // 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", "MyServer")) - { - // 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", "MyServer"); - 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 the source, if it doesn't already exist. +if (!EventLog.SourceExists("MySource", "MyServer")) +{ + // An event log source shouldn't be created and immediately used. + // There is a latency time to enable the source, so it should be created + // before the application that uses the source runs. + // Execute this sample a second time to use the new source. + EventLog.CreateEventSource("MySource", "MyNewLog", "MyServer"); + 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"; +// Create an EventLog instance and assign its source. +using EventLog myLog = new() +{ + Source = "MySource" +}; - // Write an informational entry to the event log. - myLog.WriteEntry("Writing to event log."); +// Write an informational entry to the event log. +myLog.WriteEntry("Writing to event log."); - Console.WriteLine("Message written to event log."); - } -} +Console.WriteLine("Message written to event log."); // diff --git a/snippets/csharp/System.Diagnostics/EventLog/Delete/Program.cs b/snippets/csharp/System.Diagnostics/EventLog/Delete/Program.cs new file mode 100644 index 00000000000..df52e51238d --- /dev/null +++ b/snippets/csharp/System.Diagnostics/EventLog/Delete/Program.cs @@ -0,0 +1,2 @@ +MySample.Run(); +MySample1.Run(); diff --git a/snippets/csharp/System.Diagnostics/EventLog/Delete/Project.csproj b/snippets/csharp/System.Diagnostics/EventLog/Delete/Project.csproj index 2684d9cb806..7d669796595 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Delete/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLog/Delete/Project.csproj @@ -3,7 +3,6 @@ Exe net10.0 - MySample diff --git a/snippets/csharp/System.Diagnostics/EventLog/Delete/source.cs b/snippets/csharp/System.Diagnostics/EventLog/Delete/source.cs index 0a7f3fc0758..4f5f156dbce 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Delete/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/Delete/source.cs @@ -5,7 +5,7 @@ class MySample { - public static void Main() + public static void Run() { string logName; @@ -20,7 +20,7 @@ public static void Main() EventLog.DeleteEventSource("MySource", "MyMachine"); EventLog.Delete(logName, "MyMachine"); - Console.WriteLine(logName + " deleted."); + Console.WriteLine($"{logName} deleted."); } else { diff --git a/snippets/csharp/System.Diagnostics/EventLog/Delete/source1.cs b/snippets/csharp/System.Diagnostics/EventLog/Delete/source1.cs index fa20b3d6996..f8b84ac31f3 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Delete/source1.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/Delete/source1.cs @@ -5,7 +5,7 @@ class MySample1 { - public static void Main() + public static void Run() { string logName; @@ -20,7 +20,7 @@ public static void Main() EventLog.DeleteEventSource("MySource"); EventLog.Delete(logName); - Console.WriteLine(logName + " deleted."); + Console.WriteLine($"{logName} deleted."); } else { diff --git a/snippets/csharp/System.Diagnostics/EventLog/EnableRaisingEvents/source.cs b/snippets/csharp/System.Diagnostics/EventLog/EnableRaisingEvents/source.cs index 7beec93e7e3..51707d5e777 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/EnableRaisingEvents/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/EnableRaisingEvents/source.cs @@ -1,28 +1,25 @@ // using System; using System.Diagnostics; -using System.Threading; -class MySample{ +using EventLog myNewLog = new() +{ + Log = "MyCustomLog" +}; - public static void Main(){ +myNewLog.EntryWritten += MyOnEntryWritten; +myNewLog.EnableRaisingEvents = true; - EventLog myNewLog = new EventLog(); - myNewLog.Log = "MyCustomLog"; - - myNewLog.EntryWritten += new EntryWrittenEventHandler(MyOnEntryWritten); - myNewLog.EnableRaisingEvents = true; - - Console.WriteLine("Press \'q\' to quit."); - // Wait for the EntryWrittenEvent or a quit command. - while(Console.Read() != 'q'){ - // Wait. - } - } +Console.WriteLine("Press 'q' to quit."); +// Wait for the EntryWrittenEvent or a quit command. +while (Console.Read() != 'q') +{ + // Wait. +} - public static void MyOnEntryWritten(Object source, EntryWrittenEventArgs e){ - Console.WriteLine("Written: " + e.Entry.Message); - } +void MyOnEntryWritten(object source, EntryWrittenEventArgs e) +{ + Console.WriteLine($"Written: {e.Entry.Message}"); } // diff --git a/snippets/csharp/System.Diagnostics/EventLog/Entries/source.cs b/snippets/csharp/System.Diagnostics/EventLog/Entries/source.cs index 219eece5e51..952f0b68b43 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Entries/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/Entries/source.cs @@ -2,16 +2,14 @@ using System; using System.Diagnostics; -class MySample{ - - public static void Main(){ - - EventLog myLog = new EventLog(); - myLog.Log = "MyNewLog"; - foreach(EventLogEntry entry in myLog.Entries){ - Console.WriteLine("\tEntry: " + entry.Message); - } - } +using EventLog myLog = new() +{ + Log = "MyNewLog" +}; + +foreach (EventLogEntry entry in myLog.Entries) +{ + Console.WriteLine($"\tEntry: {entry.Message}"); } // diff --git a/snippets/csharp/System.Diagnostics/EventLog/EntryWritten/source.cs b/snippets/csharp/System.Diagnostics/EventLog/EntryWritten/source.cs index 8b2680245d4..777f060b005 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/EntryWritten/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/EntryWritten/source.cs @@ -3,26 +3,19 @@ using System.Diagnostics; using System.Threading; -class MySample{ +// This object is used to wait for events. +using AutoResetEvent signal = new(false); +using EventLog myNewLog = new("Application", ".", "testEventLogEvent"); - // This member is used to wait for events. - static AutoResetEvent signal; +myNewLog.EntryWritten += MyOnEntryWritten; +myNewLog.EnableRaisingEvents = true; +myNewLog.WriteEntry("Test message", EventLogEntryType.Information); +signal.WaitOne(); - public static void Main(){ - - signal = new AutoResetEvent(false); - EventLog myNewLog = new EventLog("Application", ".", "testEventLogEvent"); - - myNewLog.EntryWritten += new EntryWrittenEventHandler(MyOnEntryWritten); - myNewLog.EnableRaisingEvents = true; - myNewLog.WriteEntry("Test message", EventLogEntryType.Information); - signal.WaitOne(); - } - - public static void MyOnEntryWritten(object source, EntryWrittenEventArgs e){ - Console.WriteLine("In event handler"); - signal.Set(); - } +void MyOnEntryWritten(object source, EntryWrittenEventArgs e) +{ + Console.WriteLine("In event handler"); + signal.Set(); } // diff --git a/snippets/csharp/System.Diagnostics/EventLog/Exists/Project.csproj b/snippets/csharp/System.Diagnostics/EventLog/Exists/Project.csproj index e17ba622dbc..543f1390dc5 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Exists/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLog/Exists/Project.csproj @@ -1,13 +1,12 @@ - Library - net10.0-windows - true + Exe + net10.0 - + diff --git a/snippets/csharp/System.Diagnostics/EventLog/Exists/eventlog_exists_1.cs b/snippets/csharp/System.Diagnostics/EventLog/Exists/eventlog_exists_1.cs index ec61eb7fa70..f118761fa4b 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Exists/eventlog_exists_1.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/Exists/eventlog_exists_1.cs @@ -8,27 +8,22 @@ the result accordingly. using System; using System.Diagnostics; -class EventLog_Exists_1 + +try +{ + // + string myLog = "myNewLog"; + if (EventLog.Exists(myLog)) + { + Console.WriteLine($"Log '{myLog}' exists."); + } + else + { + Console.WriteLine($"Log '{myLog}' does not exist."); + } + // +} +catch (Exception e) { - public static void Main() - { - try - { -// - string myLog = "myNewLog"; - if (EventLog.Exists(myLog)) - { - Console.WriteLine("Log '"+myLog+"' exists."); - } - else - { - Console.WriteLine("Log '"+myLog+"' does not exist."); - } -// - } - catch(Exception e) - { - Console.WriteLine("Exception:"+ e.Message); - } - } + Console.WriteLine($"Exception:{e.Message}"); } diff --git a/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/Program.cs b/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/Program.cs new file mode 100644 index 00000000000..f020bcb208a --- /dev/null +++ b/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/Program.cs @@ -0,0 +1,2 @@ +MySample.Run(); +EventLogSamples.EventLogProperties.Run(args); diff --git a/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/Project.csproj b/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/Project.csproj index 1583e192f85..7d669796595 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/Project.csproj +++ b/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/Project.csproj @@ -2,7 +2,6 @@ Exe - MySample net10.0 diff --git a/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/source.cs b/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/source.cs index 40f425518a0..37cfa5bd4fc 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/source.cs @@ -4,17 +4,17 @@ class MySample { - public static void Main() + public static void Run() { EventLog[] remoteEventLogs; remoteEventLogs = EventLog.GetEventLogs("myServer"); - Console.WriteLine("Number of logs on computer: " + remoteEventLogs.Length); + Console.WriteLine($"Number of logs on computer: {remoteEventLogs.Length}"); foreach (EventLog log in remoteEventLogs) { - Console.WriteLine("Log: " + log.Log); + Console.WriteLine($"Log: {log.Log}"); } } } diff --git a/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/source1.cs b/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/source1.cs index 09d084e1d4a..b55763e0cc6 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/source1.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/GetEventLogs/source1.cs @@ -11,16 +11,16 @@ class EventLogProperties { /// The main entry point for the sample application. [STAThread] - static void Main(string[] args) + public static void Run(string[] args) { DisplayEventLogProperties(); Console.WriteLine(); Console.WriteLine("Enter the name of an event log to change the"); Console.WriteLine("overflow policy (or press Enter to exit): "); - String input = Console.ReadLine(); + string input = Console.ReadLine(); - if (!String.IsNullOrEmpty(input)) + if (!string.IsNullOrEmpty(input)) { ChangeEventLogOverflowAction(input); } @@ -28,7 +28,7 @@ static void Main(string[] args) // Prompt the user for the overflow policy setting. static void GetNewOverflowSetting(ref OverflowAction newOverflow, - ref Int32 numDays) + ref int numDays) { Console.Write("Enter the new overflow policy setting ["); @@ -37,9 +37,9 @@ static void GetNewOverflowSetting(ref OverflowAction newOverflow, Console.Write(" OverwriteAsNeeded"); Console.WriteLine("] : "); - String input = Console.ReadLine(); + string input = Console.ReadLine(); - if (!String.IsNullOrEmpty(input)) + if (!string.IsNullOrEmpty(input)) { switch (input.Trim().ToUpper(CultureInfo.InvariantCulture)) { @@ -47,7 +47,7 @@ static void GetNewOverflowSetting(ref OverflowAction newOverflow, newOverflow = OverflowAction.OverwriteOlder; Console.WriteLine("Enter the number of days to retain events: "); input = Console.ReadLine(); - if ((!Int32.TryParse(input, out numDays)) || + if ((!int.TryParse(input, out numDays)) || (numDays == 0)) { Console.WriteLine(" Invalid input, defaulting to 7 days."); @@ -77,23 +77,25 @@ static void DisplayEventLogProperties() EventLog[] eventLogs = EventLog.GetEventLogs(); foreach (EventLog e in eventLogs) { - Int64 sizeKB = 0; + long sizeKB = 0; Console.WriteLine(); - Console.WriteLine("{0}:", e.LogDisplayName); - Console.WriteLine(" Log name = \t\t {0}", e.Log); + Console.WriteLine($"{e.LogDisplayName}:"); + Console.WriteLine($" Log name = \t\t {e.Log}"); - Console.WriteLine(" Number of event log entries = {0}", e.Entries.Count.ToString()); + Console.WriteLine($" Number of event log entries = {e.Entries.Count}"); // Determine if there is an event log file for this event log. - RegistryKey regEventLog = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\EventLog\\" + e.Log); + using RegistryKey regEventLog = + Registry.LocalMachine.OpenSubKey( + $"System\\CurrentControlSet\\Services\\EventLog\\{e.Log}"); if (regEventLog != null) { - Object temp = regEventLog.GetValue("File"); + object temp = regEventLog.GetValue("File"); if (temp != null) { - Console.WriteLine(" Log file path = \t {0}", temp.ToString()); - FileInfo file = new FileInfo(temp.ToString()); + Console.WriteLine($" Log file path = \t {temp}"); + FileInfo file = new(temp.ToString()); // Get the current size of the event log file. if (file.Exists) @@ -103,7 +105,7 @@ static void DisplayEventLogProperties() { sizeKB++; } - Console.WriteLine(" Current size = \t {0} kilobytes", sizeKB.ToString()); + Console.WriteLine($" Current size = \t {sizeKB} kilobytes"); } } else @@ -115,14 +117,13 @@ static void DisplayEventLogProperties() // Display the maximum size and overflow settings. sizeKB = e.MaximumKilobytes; - Console.WriteLine(" Maximum size = \t {0} kilobytes", sizeKB.ToString()); - Console.WriteLine(" Overflow setting = \t {0}", e.OverflowAction.ToString()); + Console.WriteLine($" Maximum size = \t {sizeKB} kilobytes"); + Console.WriteLine($" Overflow setting = \t {e.OverflowAction}"); switch (e.OverflowAction) { case OverflowAction.OverwriteOlder: - Console.WriteLine("\t Entries are retained a minimum of {0} days.", - e.MinimumRetentionDays); + Console.WriteLine($"\t Entries are retained a minimum of {e.MinimumRetentionDays} days."); break; case OverflowAction.DoNotOverwrite: Console.WriteLine("\t Older entries are not overwritten."); @@ -140,24 +141,22 @@ static void DisplayEventLogProperties() // // Display the current event log overflow settings, and // prompt the user to input a new overflow setting. - public static void ChangeEventLogOverflowAction(String logName) + public static void ChangeEventLogOverflowAction(string logName) { if (EventLog.Exists(logName)) { // Display the current overflow setting of the // specified event log. - EventLog inputLog = new EventLog(logName); - Console.WriteLine(" Event log {0}", inputLog.Log); + using EventLog inputLog = new(logName); + Console.WriteLine($" Event log {inputLog.Log}"); OverflowAction logOverflow = inputLog.OverflowAction; - Int32 numDays = inputLog.MinimumRetentionDays; + int numDays = inputLog.MinimumRetentionDays; - Console.WriteLine(" Current overflow setting = {0}", - logOverflow.ToString()); + Console.WriteLine($" Current overflow setting = {logOverflow}"); if (logOverflow == OverflowAction.OverwriteOlder) { - Console.WriteLine("\t Entries are retained a minimum of {0} days.", - numDays.ToString()); + Console.WriteLine($"\t Entries are retained a minimum of {numDays} days."); } // Prompt user for a new overflow setting. @@ -176,7 +175,7 @@ public static void ChangeEventLogOverflowAction(String logName) } else { - Console.WriteLine("Event log {0} was not found.", logName); + Console.WriteLine($"Event log {logName} was not found."); } } // diff --git a/snippets/csharp/System.Diagnostics/EventLog/Log/source.cs b/snippets/csharp/System.Diagnostics/EventLog/Log/source.cs index c284970cdca..b783e30ea50 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/Log/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/Log/source.cs @@ -2,16 +2,14 @@ using System; using System.Diagnostics; -class MySample{ - - public static void Main(){ - - EventLog myNewLog = new EventLog(); - myNewLog.Log = "NewEventLog"; - foreach(EventLogEntry entry in myNewLog.Entries){ - Console.WriteLine("\tEntry: " + entry.Message); - } - } +using EventLog myNewLog = new() +{ + Log = "NewEventLog" +}; + +foreach (EventLogEntry entry in myNewLog.Entries) +{ + Console.WriteLine($"\tEntry: {entry.Message}"); } // diff --git a/snippets/csharp/System.Diagnostics/EventLog/MachineName/source.cs b/snippets/csharp/System.Diagnostics/EventLog/MachineName/source.cs index 933337d63fc..cf4d76c540a 100644 --- a/snippets/csharp/System.Diagnostics/EventLog/MachineName/source.cs +++ b/snippets/csharp/System.Diagnostics/EventLog/MachineName/source.cs @@ -2,17 +2,15 @@ using System; using System.Diagnostics; -class MySample{ +using EventLog myNewLog = new() +{ + Log = "NewEventLog", + MachineName = "MyServer" +}; - public static void Main(){ - - EventLog myNewLog = new EventLog(); - myNewLog.Log = "NewEventLog"; - myNewLog.MachineName = "MyServer"; - foreach(EventLogEntry entry in myNewLog.Entries){ - Console.WriteLine("\tEntry: " + entry.Message); - } - } +foreach (EventLogEntry entry in myNewLog.Entries) +{ + Console.WriteLine($"\tEntry: {entry.Message}"); } // From 5ffdd33d0b388397badaa36c7cac79544524ac63 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 15 Sep 2026 20:06:35 -0700 Subject: [PATCH 2/5] update GH action SHAs with dependabot (#13067) --- .github/dependabot.yml | 20 ++++++++++++++----- .../workflows/check-for-build-warnings.yml | 2 +- .github/workflows/ops-build-reporter.yml | 2 +- .github/workflows/quest-bulk.yml | 6 +++--- .github/workflows/quest.yml | 8 ++++---- .github/workflows/version-sweep.yml | 6 +++--- 6 files changed, 27 insertions(+), 17 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index badefb9b7a9..93fb70af4e5 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,28 +1,38 @@ # generated by dependadotnet # https://github.com/dotnet/core/tree/master/samples/dependadotnet version: 2 -updates: +updates: + # GitHub Actions + - package-ecosystem: "github-actions" + directory: "/" + groups: + github-actions: + patterns: ["*"] + schedule: + interval: "weekly" + cooldown: + default-days: 7 - package-ecosystem: "nuget" directory: "/samples/snippets/fsharp/VS_Snippets_CLR_System/system.console.class/fs" #fontlink1.fsproj schedule: interval: "weekly" day: "wednesday" - open-pull-requests-limit: 5 + open-pull-requests-limit: 5 - package-ecosystem: "nuget" directory: "/samples/snippets/csharp/api/system.reflection.metadata/metadatareader" #MetadataReaderSnippets.csproj schedule: interval: "weekly" day: "wednesday" - open-pull-requests-limit: 5 + open-pull-requests-limit: 5 - package-ecosystem: "nuget" directory: "/samples/snippets/csharp/VS_Snippets_CLR_System/system.collections.generic.equalitycomparer.default/cs" #cs.csproj schedule: interval: "weekly" day: "wednesday" - open-pull-requests-limit: 5 + open-pull-requests-limit: 5 - package-ecosystem: "nuget" directory: "/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.collections.generic.equalitycomparer.default/vb" #vb.vbproj schedule: interval: "weekly" day: "wednesday" - open-pull-requests-limit: 5 + open-pull-requests-limit: 5 diff --git a/.github/workflows/check-for-build-warnings.yml b/.github/workflows/check-for-build-warnings.yml index a7f6af8e1e2..e0ed23b79d9 100644 --- a/.github/workflows/check-for-build-warnings.yml +++ b/.github/workflows/check-for-build-warnings.yml @@ -20,6 +20,6 @@ jobs: with: egress-policy: audit - - uses: dotnet/docs-tools/actions/status-checker@main + - uses: dotnet/docs-tools/actions/status-checker@78c0756b60e5046dd55295c4a9369b20ffad6b34 # main with: repo_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/ops-build-reporter.yml b/.github/workflows/ops-build-reporter.yml index 2f00e75175b..944ec90e7ac 100644 --- a/.github/workflows/ops-build-reporter.yml +++ b/.github/workflows/ops-build-reporter.yml @@ -21,7 +21,7 @@ jobs: with: egress-policy: audit - - uses: dotnet/docs-tools/actions/ops-build-reporter@main + - uses: dotnet/docs-tools/actions/ops-build-reporter@78c0756b60e5046dd55295c4a9369b20ffad6b34 # main with: repo_token: ${{ secrets.GITHUB_TOKEN }} max_wait_time_minutes: 40 diff --git a/.github/workflows/quest-bulk.yml b/.github/workflows/quest-bulk.yml index b9dbb04e2d9..6e3409984e7 100644 --- a/.github/workflows/quest-bulk.yml +++ b/.github/workflows/quest-bulk.yml @@ -33,7 +33,7 @@ jobs: - name: Azure OpenID Connect id: azure-oidc-auth - uses: dotnet/docs-tools/.github/actions/oidc-auth-flow@main + uses: dotnet/docs-tools/.github/actions/oidc-auth-flow@78c0756b60e5046dd55295c4a9369b20ffad6b34 # main with: client-id: ${{ secrets.CLIENT_ID }} tenant-id: ${{ secrets.TENANT_ID }} @@ -41,7 +41,7 @@ jobs: - name: Azure DevOps OpenID Connect id: azure-devops-oidc-auth - uses: dotnet/docs-tools/.github/actions/oidc-auth-flow@main + uses: dotnet/docs-tools/.github/actions/oidc-auth-flow@78c0756b60e5046dd55295c4a9369b20ffad6b34 # main with: client-id: ${{ secrets.CLIENT_ID }} tenant-id: ${{ secrets.TENANT_ID }} @@ -49,7 +49,7 @@ jobs: - name: bulk-sequester id: bulk-sequester - uses: dotnet/docs-tools/actions/sequester@main + uses: dotnet/docs-tools/actions/sequester@78c0756b60e5046dd55295c4a9369b20ffad6b34 # main env: ImportOptions__ApiKeys__GitHubToken: ${{ secrets.GITHUB_TOKEN }} ImportOptions__ApiKeys__QuestAccessToken: ${{ steps.azure-devops-oidc-auth.outputs.access-token }} diff --git a/.github/workflows/quest.yml b/.github/workflows/quest.yml index 6d6350ed5a6..dc1d653e62a 100644 --- a/.github/workflows/quest.yml +++ b/.github/workflows/quest.yml @@ -36,7 +36,7 @@ jobs: - name: Azure OpenID Connect id: azure-oidc-auth - uses: dotnet/docs-tools/.github/actions/oidc-auth-flow@main + uses: dotnet/docs-tools/.github/actions/oidc-auth-flow@78c0756b60e5046dd55295c4a9369b20ffad6b34 # main with: client-id: ${{ secrets.CLIENT_ID }} tenant-id: ${{ secrets.TENANT_ID }} @@ -44,7 +44,7 @@ jobs: - name: Azure DevOps OpenID Connect for manual test runs id: azure-devops-oidc-auth - uses: dotnet/docs-tools/.github/actions/oidc-auth-flow@main + uses: dotnet/docs-tools/.github/actions/oidc-auth-flow@78c0756b60e5046dd55295c4a9369b20ffad6b34 # main with: client-id: ${{ secrets.CLIENT_ID }} tenant-id: ${{ secrets.TENANT_ID }} @@ -54,7 +54,7 @@ jobs: - name: manual-sequester if: ${{ github.event_name == 'workflow_dispatch' }} id: manual-sequester - uses: dotnet/docs-tools/actions/sequester@main + uses: dotnet/docs-tools/actions/sequester@78c0756b60e5046dd55295c4a9369b20ffad6b34 # main env: ImportOptions__ApiKeys__GitHubToken: ${{ secrets.GITHUB_TOKEN }} ImportOptions__ApiKeys__AzureAccessToken: ${{ steps.azure-oidc-auth.outputs.access-token }} @@ -70,7 +70,7 @@ jobs: - name: auto-sequester if: ${{ github.event_name != 'workflow_dispatch' }} id: auto-sequester - uses: dotnet/docs-tools/actions/sequester@main + uses: dotnet/docs-tools/actions/sequester@78c0756b60e5046dd55295c4a9369b20ffad6b34 # main env: ImportOptions__ApiKeys__GitHubToken: ${{ secrets.GITHUB_TOKEN }} ImportOptions__ApiKeys__AzureAccessToken: ${{ steps.azure-oidc-auth.outputs.access-token }} diff --git a/.github/workflows/version-sweep.yml b/.github/workflows/version-sweep.yml index 7a7bb7786cd..f88b78219c3 100644 --- a/.github/workflows/version-sweep.yml +++ b/.github/workflows/version-sweep.yml @@ -2,7 +2,7 @@ name: 'target supported version' -# Controls when the action will run. +# Controls when the action will run. on: # Triggers the workflow on push or pull request events but only for the master branch schedule: @@ -27,7 +27,7 @@ jobs: # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - - uses: actions/checkout@v2 + - uses: actions/checkout@0717577d45739eb3c851188b29f50ed6c0b2194e # v2 # Runs a single command using the runners shell - name: 'Print manual run reason' @@ -39,7 +39,7 @@ jobs: # Start the .NET version sweeper, scan projects/slns for non-LTS (or currrent) versions - name: .NET version sweeper id: dotnet-version-sweeper - uses: dotnet/versionsweeper@main + uses: dotnet/versionsweeper@4db106fb89f4c6191a1e3901f953b1aae05331b5 # main env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: From e818d90b5e6ad0dc01ff77d77f336e64806de0bc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 16 Sep 2026 13:53:31 -0400 Subject: [PATCH 3/5] Bump the github-actions group with 4 updates (#13069) Bumps the github-actions group with 4 updates: [step-security/harden-runner](https://github.com/step-security/harden-runner), [actions/github-script](https://github.com/actions/github-script), [actions/checkout](https://github.com/actions/checkout) and [actions/setup-dotnet](https://github.com/actions/setup-dotnet). Updates `step-security/harden-runner` from 2.10.4 to 2.21.1 - [Release notes](https://github.com/step-security/harden-runner/releases) - [Commits](https://github.com/step-security/harden-runner/compare/v2.10.4...e14015d583714f6e62063499dc959a02595150a1) Updates `actions/github-script` from 7.0.1 to 9.0.0 - [Release notes](https://github.com/actions/github-script/releases) - [Commits](https://github.com/actions/github-script/compare/60a0d83039c74a4aee543508d2ffcb1c3799cdea...3a2844b7e9c422d3c10d287c895573f7108da1b3) Updates `actions/checkout` from 2.8.0 to 7.0.1 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v2.8.0...3d3c42e5aac5ba805825da76410c181273ba90b1) Updates `actions/setup-dotnet` from 5.3.0 to 6.0.0 - [Release notes](https://github.com/actions/setup-dotnet/releases) - [Commits](https://github.com/actions/setup-dotnet/compare/9a946fdbd5fb07b82b2f5a4466058b876ab72bb2...a98b56852c35b8e3190ac28c8c2271da59106c68) --- updated-dependencies: - dependency-name: step-security/harden-runner dependency-version: 2.21.1 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: github-actions - dependency-name: actions/github-script dependency-version: 9.0.0 dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/checkout dependency-version: 7.0.1 dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/setup-dotnet dependency-version: 6.0.0 dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/check-for-build-warnings.yml | 2 +- .github/workflows/live-protection.yml | 4 ++-- .github/workflows/ops-build-reporter.yml | 2 +- .github/workflows/snippets5000.yml | 6 +++--- .github/workflows/version-sweep.yml | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/check-for-build-warnings.yml b/.github/workflows/check-for-build-warnings.yml index e0ed23b79d9..93139811569 100644 --- a/.github/workflows/check-for-build-warnings.yml +++ b/.github/workflows/check-for-build-warnings.yml @@ -16,7 +16,7 @@ jobs: pull-requests: write steps: - name: Harden Runner - uses: step-security/harden-runner@c6295a65d1254861815972266d5933fd6e532bdf # v2.11.1 + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 with: egress-policy: audit diff --git a/.github/workflows/live-protection.yml b/.github/workflows/live-protection.yml index 1aa5631ba4f..205552791d2 100644 --- a/.github/workflows/live-protection.yml +++ b/.github/workflows/live-protection.yml @@ -11,11 +11,11 @@ jobs: steps: - name: Harden Runner - uses: step-security/harden-runner@cb605e52c26070c328afc4562f0b4ada7618a84e # v2.10.4 + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 with: egress-policy: audit - - uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 env: LIVE_BASE: ${{ github.base_ref == 'live' && github.head_ref != 'main' }} with: diff --git a/.github/workflows/ops-build-reporter.yml b/.github/workflows/ops-build-reporter.yml index 944ec90e7ac..0ba7cefbc64 100644 --- a/.github/workflows/ops-build-reporter.yml +++ b/.github/workflows/ops-build-reporter.yml @@ -17,7 +17,7 @@ jobs: pull-requests: write steps: - name: Harden Runner - uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 with: egress-policy: audit diff --git a/.github/workflows/snippets5000.yml b/.github/workflows/snippets5000.yml index 4d286d0eacf..e0e70cc0634 100644 --- a/.github/workflows/snippets5000.yml +++ b/.github/workflows/snippets5000.yml @@ -32,17 +32,17 @@ jobs: steps: # Checkout the repository for the PR - name: Harden Runner - uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4 + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 with: egress-policy: audit - name: Checkout repository - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 #@v7.0.0 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #@v7.0.1 # Get the latest preview SDK (or sdk not installed by the runner) - name: Set up .NET if: ${{ env.DOTNET_DO_INSTALL == 'true' }} - uses: actions/setup-dotnet@9a946fdbd5fb07b82b2f5a4466058b876ab72bb2 #@5.3.0 + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 #@6.0.0 with: dotnet-version: ${{ env.DOTNET_VERSION }} dotnet-quality: ${{ env.DOTNET_QUALITY }} diff --git a/.github/workflows/version-sweep.yml b/.github/workflows/version-sweep.yml index f88b78219c3..7607ba17c3b 100644 --- a/.github/workflows/version-sweep.yml +++ b/.github/workflows/version-sweep.yml @@ -27,7 +27,7 @@ jobs: # Steps represent a sequence of tasks that will be executed as part of the job steps: # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it - - uses: actions/checkout@0717577d45739eb3c851188b29f50ed6c0b2194e # v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 # Runs a single command using the runners shell - name: 'Print manual run reason' From bf5df0be8d61c7ce375912ef56b043da81270d76 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Thu, 17 Sep 2026 19:44:45 +0200 Subject: [PATCH 4/5] employees snippet: parameterize PopulateSales SQL (follow-up to #12524) (#13072) * employees snippet: use parameterized SQL for PopulateSales Follow-up to PR #12524 (review comment on employees.cs). The PopulateSales method concatenated the `EmployeeId` cell value into a `SELECT ... WHERE EmployeeId = ` literal, so an untrusted cell value could produce SQL injection. Use a SqlParameter and a matching `@EmployeeId` placeholder instead. The parameterless `Populate` overload is kept for the existing call sites; a new `params SqlParameter[]` overload backs the parameterized call and forwards to the same connection/adapter path. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ef73ba66-2734-45b8-ab5b-243681f0e519 * Add Project.csproj so CellContentClick snippet builds in CI The employees.cs snippet had no project file, so touching it fails the Snippets 5000 pipeline with CS0234/CS0246 for the System.Windows.Forms and System.Data.SqlClient types it references. Add a net10.0-windows project mirroring the sibling DataGridView\BeginEdit project, plus a System.Data.SqlClient PackageReference. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ef73ba66-2734-45b8-ab5b-243681f0e519 --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: ef73ba66-2734-45b8-ab5b-243681f0e519 --- .../DataGridView/CellContentClick/Project.csproj | 13 +++++++++++++ .../DataGridView/CellContentClick/employees.cs | 10 +++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 snippets/csharp/System.Windows.Forms/DataGridView/CellContentClick/Project.csproj diff --git a/snippets/csharp/System.Windows.Forms/DataGridView/CellContentClick/Project.csproj b/snippets/csharp/System.Windows.Forms/DataGridView/CellContentClick/Project.csproj new file mode 100644 index 00000000000..5ec1d5391af --- /dev/null +++ b/snippets/csharp/System.Windows.Forms/DataGridView/CellContentClick/Project.csproj @@ -0,0 +1,13 @@ + + + + Exe + net10.0-windows + true + + + + + + + diff --git a/snippets/csharp/System.Windows.Forms/DataGridView/CellContentClick/employees.cs b/snippets/csharp/System.Windows.Forms/DataGridView/CellContentClick/employees.cs index 25c63f43ed6..9bc66637032 100644 --- a/snippets/csharp/System.Windows.Forms/DataGridView/CellContentClick/employees.cs +++ b/snippets/csharp/System.Windows.Forms/DataGridView/CellContentClick/employees.cs @@ -191,11 +191,17 @@ private DataTable RetrieveAlternativeTitles() "Initial Catalog=Northwind;Data Source=localhost"; private DataTable Populate(string sqlCommand) + { + return Populate(sqlCommand, Array.Empty()); + } + + private DataTable Populate(string sqlCommand, params SqlParameter[] parameters) { SqlConnection northwindConnection = new SqlConnection(connectionString); northwindConnection.Open(); SqlCommand command = new SqlCommand(sqlCommand, northwindConnection); + command.Parameters.AddRange(parameters); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = command; @@ -276,7 +282,9 @@ private void PopulateSales(DataGridViewCellEventArgs buttonClick) string employeeId = DataGridView1.Rows[buttonClick.RowIndex] .Cells[ColumnName.EmployeeId.ToString()].Value.ToString(); - DataGridView2.DataSource = Populate("SELECT * FROM Orders WHERE EmployeeId = " + employeeId); + DataGridView2.DataSource = Populate( + "SELECT * FROM Orders WHERE EmployeeId = @EmployeeId", + new SqlParameter("@EmployeeId", employeeId)); } #region "SQL Error handling" From b9508e6c55ed230e0cbc8070120ac8d49d9deab3 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Thu, 17 Sep 2026 10:57:13 -0700 Subject: [PATCH 5/5] Correct FileStream(FileOptions) docs for `bufferSize = 0` behavior (#13062) * Initial plan * Fix FileStream bufferSize docs for FileOptions ctor Co-authored-by: adamsitnik <6011991+adamsitnik@users.noreply.github.com> * Clarify FileStream bufferSize=0 version behavior Co-authored-by: adamsitnik <6011991+adamsitnik@users.noreply.github.com> * Clarify bufferSize=1 disables FileStream buffering Co-authored-by: adamsitnik <6011991+adamsitnik@users.noreply.github.com> * Update bufferSize parameter documentation Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * Remove out-of-support version notes from bufferSize docs Co-authored-by: adamsitnik <6011991+adamsitnik@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: adamsitnik <6011991+adamsitnik@users.noreply.github.com> Co-authored-by: Adam Sitnik Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- xml/System.IO/FileStream.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xml/System.IO/FileStream.xml b/xml/System.IO/FileStream.xml index e0da63c8c47..0296e9df1d9 100644 --- a/xml/System.IO/FileStream.xml +++ b/xml/System.IO/FileStream.xml @@ -1218,7 +1218,7 @@ The file was too large (when One of the enumeration values that determines how to open or create the file. A bitwise combination of the enumeration values that determines how the file can be accessed by the object. This also determines the values returned by the and properties of the object. is if specifies a disk file. A bitwise combination of the enumeration values that determines how the file will be shared by processes. - A positive value greater than 0 indicating the buffer size. The default buffer size is 4096. + A non-negative value indicating the buffer size. The default buffer size is 4096. A value of 0 or 1 disables buffering. A bitwise combination of the enumeration values that specifies additional file options. Initializes a new instance of the class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size, and additional file options. @@ -1258,7 +1258,7 @@ The file was too large (when refers to a non-file device, such as "con:", "com1:", or "lpt1:", in a non-NTFS environment. - is negative or zero. + is negative. -or-