2026-04-01 12:46:48 +02:00
using System ;
using System.Diagnostics ;
using System.IO ;
using System.Threading.Tasks ;
using PipeMethodCalls ;
namespace NamedPipes ;
public class NamedPipeClient ( string pipeName , string? serverLocation = null , string? serverName = null , Action < string > ? logger = null ) : IDebugVisualizer , IDisposable
{
private bool IsConnected = > PipeClient . State = = PipeState . Connected ;
2026-04-01 15:47:54 +02:00
private PipeClient < IDebugVisualizer > PipeClient { get ; } = new ( new PipeSerializer ( ) , pipeName ) ;
2026-04-01 12:46:48 +02:00
private string ServerLocation { get ; } = serverLocation ? ? Environment . GetEnvironmentVariable ( "USERPROFILE" ) + @"\Documents\Visual Studio 2026\Visualizers\Server\NrxVisualizer\" ;
private string ServerName { get ; } = serverName ? ? "Num.Roto.Nrx.VisualizerServer" ;
private Action < string > Logger { get ; } = logger ? ? ( ( m ) = > Trace . WriteLine ( m ) ) ;
private async Task StartServerAsync ( )
{
if ( IsConnected ) return ;
PipeClient . SetLogger ( ( m ) = > Trace . WriteLine ( m ) ) ;
var serverAvailable = Process . GetProcessesByName ( ServerName ) . Length > 0 ;
2026-04-01 15:47:54 +02:00
Logger ( $"Server available: {serverAvailable}" ) ;
2026-04-01 12:46:48 +02:00
if ( ! serverAvailable )
{
var serverPath = ServerLocation + ServerName + ".exe" ;
2026-04-01 15:47:54 +02:00
if ( ! File . Exists ( serverPath ) ) throw new FileNotFoundException ( $"{nameof(StartServerAsync)}, Server does not exist, Path = {serverPath}" ) ;
2026-04-01 12:46:48 +02:00
var server = new Process { StartInfo = { FileName = serverPath } } ;
server . Start ( ) ;
}
2026-04-01 15:47:54 +02:00
try
{
await PipeClient . ConnectAsync ( ) . ConfigureAwait ( true ) ;
Logger ( "NamedPipeClient.StartServerAsync succeded." ) ;
return ;
}
catch ( Exception e )
{
Logger ( e . ToString ( ) ) ;
throw ;
}
}
2026-04-01 12:46:48 +02:00
public async Task < bool > SetDebugObjectAsync ( DebugObject debugObject )
{
2026-04-01 15:47:54 +02:00
await StartServerAsync ( ) . ConfigureAwait ( true ) ;
var result = await PipeClient . InvokeAsync ( server = > server . SetDebugObjectAsync ( debugObject ) ) ;
Logger ( "NamedPipeClient.SetDebugObjectAsync: result = " + result ) ;
2026-04-01 12:46:48 +02:00
return result ;
}
public async Task < bool > SetMessageAsync ( string message )
{
2026-04-01 15:47:54 +02:00
await StartServerAsync ( ) . ConfigureAwait ( true ) ;
var result = await PipeClient . InvokeAsync ( server = > server . SetMessageAsync ( message ) ) ;
Logger ( "NamedPipeClient.SetMessageAsync: result = " + result ) ;
2026-04-01 12:46:48 +02:00
return result ;
}
public void Dispose ( )
{
GC . SuppressFinalize ( this ) ;
PipeClient . Dispose ( ) ;
}
}