Last active
March 11, 2016 06:13
-
-
Save smchristensen/65d2ce91eb55fb219a1c to your computer and use it in GitHub Desktop.
General code for creating an authenticated (Basic) WCF service client. IFace is the WCF interface and Clnt is the Client that inherits from ClientBase. Uses an endpoint and endpoint url when creating the client. Also uses the self-cleaning service model from ChannelAdam.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.ServiceModel; | |
using ChannelAdam.ServiceModel; | |
using EcmServices.DataModel; | |
public class User | |
{ | |
public String Username { get; set; } | |
public String Password { get; set; } | |
} | |
public interface IAuthenticatedWcfServiceClientBuilder<I> | |
{ | |
I Build(User user); | |
} | |
public class AuthenticatedWcfServiceClientBuilder<IFace, Clnt> : IAuthenticatedWcfServiceClientBuilder<IFace> where Clnt : ClientBase<IFace> where IFace : class | |
{ | |
private string _endpointName; | |
private string _endpointUrl; | |
public AuthenticatedWcfServiceClientBuilder(string endpointName, string endpointUrl) | |
{ | |
_endpointName = endpointName; | |
_endpointUrl = endpointUrl; | |
} | |
public IFace Build(User user) | |
{ | |
var consumer = ServiceConsumerFactory.Create<IFace>(() => { | |
var service = (Clnt)Activator.CreateInstance(typeof(Clnt), new object[] { _endpointName, _endpointUrl }); | |
AddCredentials(service, user); | |
return service; | |
}); | |
return consumer.Operations; | |
} | |
private void AddCredentials(ClientBase<IFace> serviceClient, User user) | |
{ | |
if (serviceClient != null && user != null && !string.IsNullOrWhiteSpace(user.Username) && !string.IsNullOrWhiteSpace(user.Password)) { | |
serviceClient.ChannelFactory.Credentials.UserName.UserName = user.Username; | |
serviceClient.ChannelFactory.Credentials.UserName.Password = user.Password; | |
} | |
} | |
} | |
public class Runner { | |
public static void main(String[] args) { | |
// usage assuming a LoginService interface and LoginServiceClient client | |
var endpointName = "LoginClientEndpoint" | |
var endpointUrl = "http://example.com/login.svc" | |
var svc = new AuthenticatedWcfServiceClientBuilder<LoginService, LoginServiceClient>(endpointName, endpointUrl); | |
var user = new User() { | |
Username = "someuser", | |
Password = "somepass" | |
} | |
var resp = svc.Build(user).login(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment