Thursday, June 11, 2009

Retrieving domain users in a Silverlight application using a WCF Service

When you need to get the domain users in a Silverlight application the best option is to go behind a WCF service.Create your WCF service and expose the end points . The proxy created in the Silverlight application can get the details of the domain users using the methods exposed in the WCF.

WCF Class

[ServiceContract]
public class UserDomain
{
[OperationContract]
public List<DomainUser> getDomainUsers()
{
DirectorySearcher Search = new DirectorySearcher();
Search.SearchRoot = new DirectoryEntry("LDAP://dc=abc,dc=com");//here abc represents the domain name
Search.Filter = "(&(objectclass=user)(objectcategory=person))";
Search.SearchScope = SearchScope.Subtree;
Search.PropertiesToLoad.Add("userPrincipalName");

SearchResultCollection colQueryResults = Search.FindAll();
List<DomainUser> users = new List<DomainUser>();
foreach (SearchResult Result in colQueryResults)
{
if (Result.Properties["userPrincipalName"] != null)
{
if (Result.Properties["userPrincipalName"].Count > 0)
{
users.Add(new DomainUser() { ID = Result.Properties["userPrincipalName"][0].ToString(),
DisplayName = Result.Properties["name"][0].ToString() });
}
}
}
return users;
}
}
[DataContract]
public class DomainUser
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string DisplayName { get; set; }
}


Silverlight Implementation

Create the Silverlight application and add a service reference to the above created WCF service.Create the client proxy with the added service and call the WCF method to retrieve the domain users.


Code

public partial class MainPage : UserControl
{
public MainPage()
{
try
{
InitializeComponent();
UserDomainClient Proxy = new UserDomainClient();
Proxy.getDomainUsersCompleted += new EventHandler<getDomainUsersCompletedEventArgs>(Proxy_getDomainUsersCompleted);
Proxy.getDomainUsersAsync();
}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}
}

void Proxy_getDomainUsersCompleted(object sender, getDomainUsersCompletedEventArgs e)
{
List<DirectoryServiceExt.DomainUser> lstUsers=e.Result;
}
}



Make sure that you use basicHttpbinding while deploying the WCF service

No comments:

Post a Comment