Monday, March 23, 2009

.NET Remoting: Authentication Failure

Se um dia começarem a levar com uma exception no vosso código .NET com Remoting, aqui vos deixo a causa provável e solução: é necessário criar um canal único para a ligação remota em vez de usar um canal genérico.

Código problemático:
ICCSRemotingService localObj;
TcpClientChannel channel = new TcpClientChannel();
if (ChannelServices.GetChannel(channel.ChannelName) == null)
{
ChannelServices.RegisterChannel(channel, true);
}
MarshalByRefObject remoteObj = (MarshalByRefObject)RemotingServices.Connect(
typeof(ICCSRemotingService), "tcp://localhost:5343/MYSERVICE");
localObj = (ICCSRemotingService)remoteObj;
localObj.myRemoteMethod(); <- BANG! EXCEPTION!

Solução: criar um canal único para cada ligação!
BinaryClientFormatterSinkProvider clientProvider =
new BinaryClientFormatterSinkProvider();
BinaryServerFormatterSinkProvider serverProvider =
new BinaryServerFormatterSinkProvider();
serverProvider.TypeFilterLevel =
System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
IDictionary props = new Hashtable();
props["port"] = 0;
string s = System.Guid.NewGuid().ToString();
props["name"] = s;
props["typeFilterLevel"] = TypeFilterLevel.Full;
TcpChannel chan = new TcpChannel(props, clientProvider, serverProvider);
ChannelServices.RegisterChannel(chan, false);
Type typeofRI = typeof(ICCSRemotingService);
ICCSRemotingService localObj = (ICCSRemotingService)Activator.GetObject(typeofRI,
"tcp://localhost:5343/MYSERVICE");
localObj.myRemoteMethod();
ChannelServices.UnregisterChannel(chan);

Enjoy! ;o)

0 comments:

Post a Comment