Using MetadataResolver with Windows CardSpace and WCF
If you want to use CardSpace from a WCF client without hard-coding config or using an App.config file then try using the MetadataResolver class. Here is some code that works with .NET Framework 3.0 Beta 2 ("WinFX"):
I've been meaning to get a MetadataResolver example working for a while and I was finally able to spend some time today with it. Not too difficult although it's due to change a little bit with the June CTP. The revocation check was necessary to get around my certificate CRL being unavailable.
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.IdentityModel.Selectors;
namespace HelloClient
{
class Program
{
static void Main(string[] args)
{
try
{
Uri mexUri = new Uri("http://localhost:4123/helloService/mex");
EndpointAddress mexEndpointAddress = new EndpointAddress(mexUri);
ServiceEndpointCollection endpoints = MetadataResolver.Resolve(mexEndpointAddress);
ContractDescription contract = ContractDescription.GetContract(typeof(HelloService.IHello));
foreach (ServiceEndpoint endpoint in endpoints)
{
if (endpoint.Contract.Namespace.Equals(contract.Namespace) && endpoint.Contract.Name.Equals(contract.Name))
{
ChannelFactory<HelloService.IHello> cf =
new ChannelFactory<HelloService.IHello>(endpoint.Binding, endpoint.Address);
InfoCardClientCredentials credentials = new InfoCardClientCredentials();
credentials.ServiceCertificate.Authentication.RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck;
cf.Endpoint.Behaviors.Add(credentials);
HelloService.IHello chn = cf.CreateChannel();
Console.WriteLine(chn.Say());
cf.Close();
}
}
}
catch (UserCancellationException)
{
Console.WriteLine("User cancelled");
}
catch (UntrustedRecipientException)
{
Console.WriteLine("User does not trust the recipient");
}
catch (ServiceNotStartedException)
{
Console.WriteLine("CardSpace service not started");
}
catch (InfoCardException ice)
{
Console.WriteLine("Generic CardSpace exception :" + ice.Message);
}
catch (Exception e)
{
Console.WriteLine("Other exceptions :" + e.Message);
}
finally
{
Console.WriteLine("Press any key to finish");
Console.ReadKey();
}
}
}
}