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..98566c90b68 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.ToString()} 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}"); } //