Creating a WCF Net.TCP Service and Client using PowerShell

I'm currently attending Regis University for my grad degree, and just finished up a networking class. For my final, I chose to explore the Windows Net.TCP Port Sharing Service. I had this glorious vision of translating some C# code to 100% PowerShell code, but eventually gave into the fact that PowerShell doesn't support reflection, and a bit of the code had to be written in C#.

Ultimately, I also learned that TCP Port sharing is really just a port proxy facilitated by SMSvcHost.exe, and the differentiator, instead of being a port number, is a namespace. Below is the code I used for proof of concept. You may find it useful when testing your own C# code.

$source = ' using System; using System.ServiceModel; [ServiceContract] public interface IGreeting { [OperationContract] string Echo(string s); } public class GreetingService : IGreeting { public string Echo(string s) { return "You passed the following string: " + s; } }' Add-Type -ReferencedAssemblies 'System.ServiceModel.dll' -TypeDefinition $source $null = [Reflection.Assembly]::LoadWithPartialName("System.ServiceModel")

Service

$uri = "net.tcp://localhost:8080" $binding = New-Object System.ServiceModel.NetTcpBinding $binding.PortSharingEnabled = $true $securityMode = New-Object System.ServiceModel.SecurityMode $binding.Security.Mode = "None"

$sh = New-Object System.ServiceModel.Servicehost([GreetingService],$uri) $endpoint = $sh.AddServiceEndpoint("IGreeting",$binding,$uri) $sh.open()

Client

$contractDescription = [System.ServiceModel.Description.ContractDescription]::GetContract([IGreeting]) $serviceEndpoint = New-Object System.ServiceModel.Description.ServiceEndpoint $contractDescription $factory = New-Object System.ServiceModel.ChannelFactory[IGreeting] $serviceEndpoint $endpoint = New-Object System.ServiceModel.EndpointAddress($uri) $factory.Endpoint.Binding = $binding $factory.Endpoint.Address = $endpoint

$final = $factory.CreateChannel() $final.Echo("hello")

Thanks goes to Allan and this user for getting me started with the WCF PowerShell code.