Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // // // // // // // // //
- // RecTypeDeconst.CSProj:
- // // // // // // // // //
- //
- <Project Sdk="Microsoft.NET.Sdk">
- <PropertyGroup>
- <OutputType>Exe</OutputType>
- <TargetFramework>net8.0</TargetFramework>
- <ImplicitUsings>enable</ImplicitUsings>
- <Nullable>enable</Nullable>
- <IsPackable>false</IsPackable>
- <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
- <StartupObject>RecTypeDeconst.Program</StartupObject>
- </PropertyGroup>
- <ItemGroup>
- <ProjectReference Include="..\Attributes\Attributes.csproj" />
- <!-- <ProjectReference Include="..\DebuggingSourceGenerator\DebuggingSourceGenerator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false"> -->
- </ItemGroup>
- <ItemGroup>
- <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4">
- <PrivateAssets>all</PrivateAssets>
- <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
- </PackageReference>
- <PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
- </ItemGroup>
- <ItemGroup>
- <PackageReference Update="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
- <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" PrivateAssets="all" />
- </ItemGroup>
- <ItemGroup>
- <PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
- <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
- <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
- <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
- <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="8.0.0" />
- </ItemGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
- <IsPublishable>False</IsPublishable>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
- <IsPublishable>False</IsPublishable>
- </PropertyGroup>
- //
- // <!--END-->
- // // // // // // // // // // // // //
- // File 'Program.cs'
- // // // // //
- using System;
- using System.Net.Sockets;
- using Attributes;
- namespace RecTypeDeconst;
- public class Program
- {
- public static void Main(string[] args)
- {
- try
- {
- MsgSender.SendLogMessage($"Started.").Wait();
- MsgSender.SendLogMessage($"Started2.").Wait();
- Console.WriteLine($"Started.");
- Console.ReadKey();
- }
- catch (SocketException ex)
- {
- D.W("SocketException ---> "+ ex.ToString() + $"{ex.ErrorCode} SocketErrorCode: {ex.SocketErrorCode} Inner:{ex.InnerException} ");
- }
- catch(Exception ex ) {
- D.W($"{ex}");
- }
- }
- // // // // // // // // //
- // Attributes .CSProj:
- // // // // // // // // //
- //
- // <Project Sdk="Microsoft.NET.Sdk">
- // <PropertyGroup>
- // <TargetFramework>netstandard2.0</TargetFramework>
- // </PropertyGroup>
- // </Project>
- //
- // <!--END-->
- // // // // // // // // // // // // //
- // File 'MsgSender.cs'
- // // // // //
- using System;
- using System.IO;
- using System.IO.Pipes;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading.Tasks;
- namespace Attributes
- {
- public enum MsgMode
- {
- Event,
- NamedPipe,
- TCP,
- NetworkMappedFile,
- }
- public class MsgSender
- {
- public static MsgMode Mode = MsgMode.TCP;
- public static int Port = 7334;
- [NoDebug]
- public static async Task SendLogMessage(string msg)
- {
- await Task.Delay(500);
- switch (Mode)
- {
- case MsgMode.TCP:
- {
- try
- {
- await SendTcpMsg(msg).ConfigureAwait(false);
- }
- catch (SocketException ex)
- {
- // this should now catch any socket-related exceptions
- Console.WriteLine($"SocketException: {ex.Message} SocketError: {ex.SocketErrorCode} Msg:{ex.Message} ErrCode:{ex.ErrorCode} NativeErrCode:{ex.NativeErrorCode} ");
- D.W($"SocketException: {ex.Message}");
- }
- catch (Exception ex)
- {
- Console.WriteLine(".." +ex);
- }
- break;
- }
- case MsgMode.NamedPipe:
- {
- SendNamedPipeMsg(msg);
- break;
- }
- }
- }
- [NoDebug]
- private async static Task SendTcpMsg(string msg)
- {
- await Task.Delay(100);
- try
- {
- // Ensure all connection and stream activities are inside the try-catch
- using (TcpClient client = new TcpClient("localhost", Port))
- {
- D.W($"Sending Message: {msg}");
- Console.WriteLine($"Sending Message: {msg}");
- client.NoDelay = true;
- byte[] data = Encoding.UTF8.GetBytes(msg);
- using (NetworkStream stream = client.GetStream())
- {
- stream.Write(data, 0, data.Length);
- //stream.Close(); // Close the stream explicitly
- }
- D.W("Message sent successfully.");
- await Task.Delay(10);
- }
- }
- catch (SocketException ex)
- {
- // this should now catch any socket-related exceptions
- Console.WriteLine($"SocketException: {ex.Message} SocketError: {ex.SocketErrorCode} Msg:{ex.Message} ErrCode:{ex.ErrorCode} NativeErrCode:{ex.NativeErrorCode} ");
- D.W($"SocketException: {ex.Message}");
- }
- catch (IOException ex)
- {
- // catch any IO exceptions, e.g., from stream handling issues
- Console.WriteLine($"IOException: {ex.Message}");
- D.W($"IOException: {ex.Message}");
- }
- catch (Exception ex)
- {
- // catch any other exceptions
- Console.WriteLine($"Error: {ex.Message}");
- D.W($"Error: {ex.Message}");
- }
- }
- [NoDebug]
- private static void SendNamedPipeMsg(string msg)
- {
- try
- {
- using (var pipeClient = new NamedPipeClientStream("LogPipe"))
- {
- pipeClient.Connect(1000); // Timeout after 1 second
- using (var writer = new StreamWriter(pipeClient))
- {
- writer.Write($"Msg: {msg}");
- }
- }
- }
- catch (Exception ex)
- {
- D.W(ex.ToString());
- // handle cases where pipe connection fails
- // optionally, you can ignore or add in-memory logging here
- }
- }
- }
- }
- // // // // // // // // // // // // //
- // File 'D.cs'
- // // // // //
- using System;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- namespace Attributes
- // ReSharper disable once ArrangeNamespaceBody
- {
- public class D // #Debug: Logging, Console=, Debug-Output Messages,
- {
- public static void W(string s)
- {
- Debug.WriteLine($"DBG> {s}");
- Console.WriteLine($"DBG> {s}");
- }
- // exception logging method
- public static void E<TException>(TException ex) where TException : Exception { LogException(ex); }
- private static void LogException(Exception ex, int level = 0)
- {
- if (ex == null) return;
- string indent = new string(' ', level * 2); // indent nested
- W($"{indent}Exception Type: {ex.GetType()}");
- W($"{indent}Message: {ex.Message}");
- W($"{indent}Source: {ex.Source}");
- W($"{indent}StackTrace: {ex.StackTrace}");
- if (ex.TargetSite != null)
- {
- W($"{indent}TargetSite: {ex.TargetSite}");
- }
- if (ex.Data != null && ex.Data.Count > 0)
- {
- W($"{indent}Data:");
- foreach (var key in ex.Data.Keys)
- {
- W($"{indent} {key}: {ex.Data[key]}");
- }
- }
- // recursively log inner exceptions if exist
- if (ex.InnerException != null)
- {
- W($"{indent}Inner Exception:");
- LogException(ex.InnerException, ++level);
- }
- }
- }
- public static class ExceptionInspector
- {
- public static void DiscoverExceptionProperties(Exception ex)
- {
- Type exceptionType = ex.GetType();
- D.W($"Exception Type: {exceptionType.FullName}");
- // get all the properties of the exception, including those from derived types
- var properties = exceptionType.GetProperties();
- foreach (var prop in properties)
- {
- try
- {
- var value = prop.GetValue(ex);
- D.W($"{prop.Name}: {value}");
- }
- catch (Exception reflectionEx)
- {
- D.W($"{prop.Name}: Could not retrieve ({reflectionEx.Message})");
- }
- }
- }
- public static void DiscoverExceptionPropertiesRecursive(Exception ex, int level = 0)
- {
- Type exceptionType = ex.GetType();
- string indent = new string(' ', level * 2);
- Console.WriteLine($"{indent}Exception Type: {exceptionType.FullName}");
- var properties = exceptionType.GetProperties();
- foreach (var prop in properties)
- {
- try
- {
- var value = prop.GetValue(ex);
- Console.WriteLine($"{indent}{prop.Name}: {value}");
- }
- catch (Exception reflectionEx)
- {
- Console.WriteLine($"{indent}{prop.Name}: Could not retrieve ({reflectionEx.Message})");
- }
- }
- if (ex.InnerException != null)
- {
- Console.WriteLine($"{indent}Inner Exception:");
- DiscoverExceptionPropertiesRecursive(ex.InnerException, level + 1);
- }
- }
- }
- public static class FileSaver
- {
- public static void SaveStringToFile(string content, string fileName, string ext, bool append)
- {
- string directory = "D:/repo/input"; // Base directory
- string fullPath = Path.Combine(directory, $"{fileName}.{ext}");
- // if not appending, ensure unique filename
- if (!append)
- {
- fullPath = EnsureUniqueFileName(directory, fileName, ext);
- }
- // append or write based on the append flag
- if (append)
- {
- File.AppendAllText(fullPath, content);
- }
- else
- {
- File.WriteAllText(fullPath, content);
- }
- }
- private static string EnsureUniqueFileName(string directory, string fileName, string ext)
- {
- string fullPath = Path.Combine(directory, $"{fileName}.{ext}");
- if (!File.Exists(fullPath))
- {
- return fullPath;
- }
- // if filename does not end with a number, start with 1
- int fileNumber = 1;
- string baseFileName = fileName;
- if (char.IsDigit(fileName.LastOrDefault()))
- {
- // Strip the trailing digits if they exist
- int lastIndex = fileName.Length - 1;
- while (lastIndex >= 0 && char.IsDigit(fileName[lastIndex]))
- {
- lastIndex--;
- }
- baseFileName = fileName.Substring(0, lastIndex + 1);
- fileNumber = int.Parse(fileName.Substring(lastIndex + 1)) + 1;
- }
- // increment number until a unique filename is found
- do
- {
- fullPath = Path.Combine(directory, $"{baseFileName}{fileNumber}.{ext}");
- fileNumber++;
- } while (File.Exists(fullPath));
- return fullPath;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement