Advertisement
Guest User

Client

a guest
Sep 13th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.81 KB | None | 0 0
  1. // // // // // // // // //
  2. // RecTypeDeconst.CSProj:
  3. // // // // // // // // //
  4. //
  5. <Project Sdk="Microsoft.NET.Sdk">
  6.   <PropertyGroup>
  7.     <OutputType>Exe</OutputType>
  8.     <TargetFramework>net8.0</TargetFramework>
  9.     <ImplicitUsings>enable</ImplicitUsings>
  10.     <Nullable>enable</Nullable>
  11.     <IsPackable>false</IsPackable>
  12.     <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
  13.     <StartupObject>RecTypeDeconst.Program</StartupObject>
  14.   </PropertyGroup>
  15.  
  16.   <ItemGroup>
  17.     <ProjectReference Include="..\Attributes\Attributes.csproj" />
  18.     <!-- <ProjectReference Include="..\DebuggingSourceGenerator\DebuggingSourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false"> -->
  19.   </ItemGroup>
  20.   <ItemGroup>
  21.     <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4">
  22.       <PrivateAssets>all</PrivateAssets>
  23.       <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
  24.     </PackageReference>
  25.     <PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
  26.   </ItemGroup>
  27.   <ItemGroup>
  28.     <PackageReference Update="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
  29.     <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" PrivateAssets="all" />
  30.   </ItemGroup>
  31.   <ItemGroup>
  32.     <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
  33.     <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
  34.     <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
  35.     <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
  36.     <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
  37.   </ItemGroup>
  38.  
  39.   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
  40.     <IsPublishable>False</IsPublishable>
  41.   </PropertyGroup>
  42.  
  43.   <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
  44.     <IsPublishable>False</IsPublishable>
  45.   </PropertyGroup>
  46. //
  47. // <!--END-->
  48.  
  49.  
  50. // // // // // // // // // // // // //
  51. // File 'Program.cs'
  52. // // // // //
  53.  
  54. using System;
  55. using System.Net.Sockets;
  56. using Attributes;
  57.  
  58.  
  59. namespace RecTypeDeconst;
  60.  
  61. public class Program
  62. {
  63.  
  64.     public static void Main(string[] args)
  65.     {
  66.         try
  67.         {
  68.             MsgSender.SendLogMessage($"Started.").Wait();
  69.             MsgSender.SendLogMessage($"Started2.").Wait();
  70.             Console.WriteLine($"Started.");
  71.             Console.ReadKey();
  72.         }
  73.         catch (SocketException ex)
  74.         {
  75.             D.W("SocketException ---> "+ ex.ToString() + $"{ex.ErrorCode} SocketErrorCode: {ex.SocketErrorCode} Inner:{ex.InnerException} ");
  76.  
  77.         }
  78.         catch(Exception ex ) {
  79.             D.W($"{ex}");
  80.         }
  81.     }
  82.  
  83.  
  84. // // // // // // // // //
  85. // Attributes .CSProj:
  86. // // // // // // // // //
  87. //
  88. //   <Project Sdk="Microsoft.NET.Sdk">
  89. //     <PropertyGroup>
  90. //       <TargetFramework>netstandard2.0</TargetFramework>
  91. //     </PropertyGroup>
  92. //   </Project>
  93. //
  94. // <!--END-->
  95.  
  96.  
  97. // // // // // // // // // // // // //
  98. // File 'MsgSender.cs'
  99. // // // // //
  100.  
  101. using System;
  102. using System.IO;
  103. using System.IO.Pipes;
  104. using System.Net.Sockets;
  105. using System.Text;
  106. using System.Threading.Tasks;
  107.  
  108.  
  109. namespace Attributes
  110. {
  111.     public enum MsgMode
  112.     {
  113.  
  114.         Event,
  115.         NamedPipe,
  116.         TCP,
  117.         NetworkMappedFile,
  118.  
  119.     }
  120.  
  121.  
  122.     public class MsgSender
  123.     {
  124.  
  125.         public static MsgMode Mode = MsgMode.TCP;
  126.         public static int     Port = 7334;
  127.  
  128.  
  129.         [NoDebug]
  130.         public static async Task SendLogMessage(string msg)
  131.         {
  132.             await Task.Delay(500);
  133.             switch (Mode)
  134.             {
  135.                 case MsgMode.TCP:
  136.                 {
  137.                     try
  138.                     {
  139.  
  140.                         await SendTcpMsg(msg).ConfigureAwait(false);
  141.                     }
  142.                     catch (SocketException ex)
  143.                     {
  144.                         // this should now catch any socket-related exceptions
  145.                         Console.WriteLine($"SocketException: {ex.Message} SocketError: {ex.SocketErrorCode} Msg:{ex.Message} ErrCode:{ex.ErrorCode} NativeErrCode:{ex.NativeErrorCode} ");
  146.                         D.W($"SocketException: {ex.Message}");
  147.                     }
  148.                     catch (Exception ex)
  149.                     {
  150.                         Console.WriteLine(".." +ex);
  151.                     }
  152.  
  153.                     break;
  154.                 }
  155.                 case MsgMode.NamedPipe:
  156.                 {
  157.                     SendNamedPipeMsg(msg);
  158.  
  159.                     break;
  160.                 }
  161.             }
  162.         }
  163.  
  164.  
  165.         [NoDebug]
  166.         private async static Task SendTcpMsg(string msg)
  167.         {
  168.             await Task.Delay(100);
  169.             try
  170.             {
  171.                 // Ensure all connection and stream activities are inside the try-catch
  172.                 using (TcpClient client = new TcpClient("localhost", Port))
  173.                 {
  174.                     D.W($"Sending Message: {msg}");
  175.                     Console.WriteLine($"Sending Message: {msg}");
  176.  
  177.                     client.NoDelay = true;
  178.  
  179.                     byte[] data = Encoding.UTF8.GetBytes(msg);
  180.                     using (NetworkStream stream = client.GetStream())
  181.                     {
  182.                        
  183.                         stream.Write(data, 0, data.Length);
  184.                         //stream.Close(); // Close the stream explicitly
  185.                     }
  186.  
  187.  
  188.                     D.W("Message sent successfully.");
  189.                     await Task.Delay(10);
  190.                 }
  191.             }
  192.             catch (SocketException ex)
  193.             {
  194.                 // this should now catch any socket-related exceptions
  195.                 Console.WriteLine($"SocketException: {ex.Message} SocketError: {ex.SocketErrorCode} Msg:{ex.Message} ErrCode:{ex.ErrorCode} NativeErrCode:{ex.NativeErrorCode} ");
  196.                 D.W($"SocketException: {ex.Message}");
  197.             }
  198.             catch (IOException ex)
  199.             {
  200.                 // catch any IO exceptions, e.g., from stream handling issues
  201.                 Console.WriteLine($"IOException: {ex.Message}");
  202.                 D.W($"IOException: {ex.Message}");
  203.             }
  204.             catch (Exception ex)
  205.             {
  206.                 // catch any other exceptions
  207.                 Console.WriteLine($"Error: {ex.Message}");
  208.                 D.W($"Error: {ex.Message}");
  209.             }
  210.         }
  211.  
  212.  
  213.         [NoDebug]
  214.         private static void SendNamedPipeMsg(string msg)
  215.         {
  216.             try
  217.             {
  218.                 using (var pipeClient = new NamedPipeClientStream("LogPipe"))
  219.                 {
  220.                     pipeClient.Connect(1000); // Timeout after 1 second
  221.                     using (var writer = new StreamWriter(pipeClient))
  222.                     {
  223.                         writer.Write($"Msg: {msg}");
  224.                     }
  225.                 }
  226.             }
  227.             catch (Exception ex)
  228.             {
  229.                 D.W(ex.ToString());
  230.                 // handle cases where pipe connection fails
  231.                 // optionally, you can ignore or add in-memory logging here
  232.             }
  233.         }
  234.  
  235.     }
  236. }
  237.  
  238. // // // // // // // // // // // // //
  239. // File 'D.cs'
  240. // // // // //
  241. using System;
  242. using System.Diagnostics;
  243. using System.IO;
  244. using System.Linq;
  245.  
  246.  
  247. namespace Attributes
  248.     // ReSharper disable once ArrangeNamespaceBody
  249. {
  250.     public class D // #Debug:  Logging, Console=, Debug-Output Messages,
  251.     {
  252.  
  253.         public static void W(string s)
  254.         {
  255.             Debug.WriteLine($"DBG> {s}");
  256.             Console.WriteLine($"DBG> {s}");
  257.         }
  258.  
  259.  
  260.         // exception logging method
  261.         public static void E<TException>(TException ex) where TException : Exception { LogException(ex); }
  262.  
  263.  
  264.         private static void LogException(Exception ex, int level = 0)
  265.         {
  266.             if (ex == null) return;
  267.  
  268.             string indent = new string(' ', level * 2); // indent nested
  269.  
  270.             W($"{indent}Exception Type: {ex.GetType()}");
  271.             W($"{indent}Message: {ex.Message}");
  272.             W($"{indent}Source: {ex.Source}");
  273.             W($"{indent}StackTrace: {ex.StackTrace}");
  274.  
  275.             if (ex.TargetSite != null)
  276.             {
  277.                 W($"{indent}TargetSite: {ex.TargetSite}");
  278.             }
  279.  
  280.  
  281.             if (ex.Data != null && ex.Data.Count > 0)
  282.             {
  283.                 W($"{indent}Data:");
  284.                 foreach (var key in ex.Data.Keys)
  285.                 {
  286.                     W($"{indent}  {key}: {ex.Data[key]}");
  287.                 }
  288.             }
  289.  
  290.  
  291.             // recursively log inner exceptions if exist
  292.             if (ex.InnerException != null)
  293.             {
  294.                 W($"{indent}Inner Exception:");
  295.                 LogException(ex.InnerException, ++level);
  296.             }
  297.         }
  298.  
  299.     }
  300.  
  301.  
  302.     public static class ExceptionInspector
  303.     {
  304.  
  305.         public static void DiscoverExceptionProperties(Exception ex)
  306.         {
  307.             Type exceptionType = ex.GetType();
  308.             D.W($"Exception Type: {exceptionType.FullName}");
  309.  
  310.             // get all the properties of the exception, including those from derived types
  311.             var properties = exceptionType.GetProperties();
  312.  
  313.             foreach (var prop in properties)
  314.             {
  315.                 try
  316.                 {
  317.                     var value = prop.GetValue(ex);
  318.                     D.W($"{prop.Name}: {value}");
  319.                 }
  320.                 catch (Exception reflectionEx)
  321.                 {
  322.                     D.W($"{prop.Name}: Could not retrieve ({reflectionEx.Message})");
  323.                 }
  324.             }
  325.         }
  326.  
  327.  
  328.         public static void DiscoverExceptionPropertiesRecursive(Exception ex, int level = 0)
  329.         {
  330.             Type   exceptionType = ex.GetType();
  331.             string indent        = new string(' ', level * 2);
  332.             Console.WriteLine($"{indent}Exception Type: {exceptionType.FullName}");
  333.  
  334.             var properties = exceptionType.GetProperties();
  335.  
  336.             foreach (var prop in properties)
  337.             {
  338.                 try
  339.                 {
  340.                     var value = prop.GetValue(ex);
  341.                     Console.WriteLine($"{indent}{prop.Name}: {value}");
  342.                 }
  343.                 catch (Exception reflectionEx)
  344.                 {
  345.                     Console.WriteLine($"{indent}{prop.Name}: Could not retrieve ({reflectionEx.Message})");
  346.                 }
  347.             }
  348.  
  349.  
  350.             if (ex.InnerException != null)
  351.             {
  352.                 Console.WriteLine($"{indent}Inner Exception:");
  353.                 DiscoverExceptionPropertiesRecursive(ex.InnerException, level + 1);
  354.             }
  355.         }
  356.  
  357.     }
  358.  
  359.  
  360.     public static class FileSaver
  361.     {
  362.         public static void SaveStringToFile(string content, string fileName, string ext, bool append)
  363.         {
  364.             string directory = "D:/repo/input";  // Base directory
  365.             string fullPath  = Path.Combine(directory, $"{fileName}.{ext}");
  366.  
  367.             // if not appending, ensure unique filename
  368.             if (!append)
  369.             {
  370.                 fullPath = EnsureUniqueFileName(directory, fileName, ext);
  371.             }
  372.  
  373.             // append or write based on the append flag
  374.             if (append)
  375.             {
  376.                 File.AppendAllText(fullPath, content);
  377.             }
  378.             else
  379.             {
  380.                 File.WriteAllText(fullPath, content);
  381.             }
  382.         }
  383.  
  384.         private static string EnsureUniqueFileName(string directory, string fileName, string ext)
  385.         {
  386.             string fullPath = Path.Combine(directory, $"{fileName}.{ext}");
  387.             if (!File.Exists(fullPath))
  388.             {
  389.                 return fullPath;
  390.             }
  391.  
  392.             // if filename does not end with a number, start with 1
  393.             int    fileNumber   = 1;
  394.             string baseFileName = fileName;
  395.             if (char.IsDigit(fileName.LastOrDefault()))
  396.             {
  397.                 // Strip the trailing digits if they exist
  398.                 int lastIndex = fileName.Length - 1;
  399.                 while (lastIndex >= 0 && char.IsDigit(fileName[lastIndex]))
  400.                 {
  401.                     lastIndex--;
  402.                 }
  403.                 baseFileName = fileName.Substring(0, lastIndex + 1);
  404.                 fileNumber   = int.Parse(fileName.Substring(lastIndex + 1)) + 1;
  405.             }
  406.  
  407.             // increment number until a unique filename is found
  408.             do
  409.             {
  410.                 fullPath = Path.Combine(directory, $"{baseFileName}{fileNumber}.{ext}");
  411.                 fileNumber++;
  412.             } while (File.Exists(fullPath));
  413.  
  414.             return fullPath;
  415.         }
  416.     }
  417. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement