Add following assemblies in your project:
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
private void GetADUsers()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2]
{
new DataColumn("AccountName", typeof (string)),
new DataColumn("GivenName", typeof (string))
});
var context = new PrincipalContext(ContextType.Domain, "domainname");
var usr = new UserPrincipal(context);
var filter = new Filters(usr);
filter.CreatedAfter(DateTime.UtcNow.AddDays(-50));//get last 50 days created users
foreach (var result in new PrincipalSearcher(usr).FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
var clsuser = new ClsUsers();
dt.Rows.Add(Convert.ToString(de.Properties["samAccountName"].Value), Convert.ToString(de.Properties["givenName"].Value));
createuser(Convert.ToString(de.Properties["samAccountName"].Value), Convert.ToString(de.Properties["givenName"].Value));//create user in crm
break;
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void createuser(String username, String fullname)
{
String dom = @"UMT\";
IOrganizationService service = GetCRMService();
Entity user = new Entity("systemuser");
user["domainname"] = dom + username;
user["firstname"] = "A";
user["lastname"] = fullname;
user["businessunitid"] = new EntityReference("businessunit", new Guid(""));
service.Create(user);
}
public class Filters : AdvancedFilters// this class is used for to apply filters
{
public Filters(Principal p)
: base(p)
{
}
public void CreatedAfter(DateTime value)
{
var strValue = value.ToString("yyyyMMddHHmmss.0Z");
this.AdvancedFilterSet("WhenCreated", strValue, typeof(string), MatchType.GreaterThanOrEquals);
}
}
public class ClsUsers
{
public string AccountName { get; set; }
public string DisplayName { get; set; }
}