Sunday, 9 September 2012

ALL Operations on Active Directory (AD) using c#

Objective

This article will explain how to perform operations on Active Directory (AD) using C#. In this step-by-step tutorial, I will build a class library (DLL) project that will perform all the AD Operations and then you can use this class library in any application to use this functionality.

Basic introduction of Active Directory is provided and code examples for operations like

<!--[if !supportLists]-->1. <!--[endif]-->Finding user by login name

<!--[if !supportLists]-->2. <!--[endif]-->Finding user by Name

<!--[if !supportLists]-->3. <!--[endif]-->Finding user by First Name

<!--[if !supportLists]-->4. <!--[endif]-->Resolving AD Group in users etc

What is Active Directory

This is a Directory structure used in Windows for storing information about networks and domains. This was first used in Windows 2000. This is a hierarchical structure which helps in organizing information on objects. In lay term it is used to store user information, network information in an organization.

Solution Explorer for the Active Directory Helper Class library



ADImg1.gif   

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ActiveDirectoryHelperis the main working class. This class will contain all the functions for various operations on AD. Other classes are helping class to perform operations and being used in ActiveDirectoryHelperclass. After adding DLL of this project, at the client side object of ActiveDirectory class will get created and the function will get called.

Diving into code to Perform Operations

Step 1

Create a new project by selecting project template Class Library.

Step 2


Add below references to the project

System.DirectoryServices

System.DirectoryServices.AccountManagement

System.DirectoryServices.Protocols.

System.Configuration

Step 3


Add an Application Configuration file to project. And add App setting for

<!--[if !supportLists]-->1. <!--[endif]-->LDAP User Name

<!--[if !supportLists]-->2. <!--[endif]-->LDAP Password

<!--[if !supportLists]-->3. <!--[endif]-->LDAP Path

So App.Config file will look like below,

App.Config


<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<appSettings>

<add key="LDAPPassword" value="xxxPasswordxxx" />

<add key="LDAPPath" value="LDAP://domain/DC=xxx,DC=com" />

<add key="LDAPUser" value="xxxUserxxx" />

</appSettings>

</configuration>

Note: Give user name, password and path according to your LDAP

Step 4. Creating ADUser class


Create or add a class in the project for ADUser details. This class will have the properties corresponding to the information of the AD User.

<!--[if !supportLists]-->1. <!--[endif]-->This class has read only properties for fetching First Name, Last Name, City, Login Name etc.

<!--[if !supportLists]-->2. <!--[endif]-->Constructor of the class is taking one parameter of type DirectoryEntry class.

<!--[if !supportLists]-->3. <!--[endif]-->In Constructor all the information about ADUser is getting fetched using static class ADProperties.

<!--[if !supportLists]-->4. <!--[endif]-->There are two static functions inside this class. GetUser and GetProperty

<!--[if !supportLists]-->5. <!--[endif]-->Get Property is returning a string which holds property of AD User.

<!--[if !supportLists]-->6. <!--[endif]-->GetUser static function is returning anADUser.

ADUserDetail.cs


using System;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.DirectoryServices;


namespaceActiveDirectoryHelper

{

public class ADUserDetail

{

private String _firstName;

private String _middleName;

private String _lastName;

private String _loginName;

private String _loginNameWithDomain;

private String _streetAddress;

private String _city;

private String _state;

private String _postalCode;

private String _country;

private String _homePhone;

private String _extension;

private String _mobile;

private String _fax;

private String _emailAddress;

private String _title;

private String _company;

private String _manager;

private String_managerName;

private String _department;


public String Department

{

get{ return _department; }

}


public String FirstName

{

get{ return _firstName; }

}


public StringMiddleName

{

get{ return _middleName; }

}


public String LastName

{

get{ return _lastName; }

}


public String LoginName

{

get{ return _loginName; }

}


public String LoginNameWithDomain

{

get{ return _loginNameWithDomain; }

}


public String StreetAddress

{

get{ return _streetAddress; }

}


public String City

{

get{ return _city; }

}


public String State

{

get{ return _state; }

}


public String PostalCode

{

get{ return _postalCode; }

}


public String Country

{

get{ return _country; }

}


public String HomePhone

{

get{ return _homePhone; }

}


public String Extension

{

get{ return _extension; }

}


public StringMobile

{

get{ return _mobile; }

}


public String Fax

{

get{ return _fax; }

}


public String EmailAddress

{

get{ return _emailAddress; }

}


public String Title

{

get{ return _title; }

}


public String Company

{

get{ return _company; }

}


public ADUserDetail Manager

{

get

{

if (!String.IsNullOrEmpty(_managerName))

{

ActiveDirectoryHelperad = new ActiveDirectoryHelper();

returnad.GetUserByFullName(_managerName);

}

return null;

}

}


public String ManagerName

{

get{ return _managerName; }

}



privateADUserDetail(DirectoryEntry directoryUser)

{


StringdomainAddress;

StringdomainName;

_firstName = GetProperty(directoryUser, ADProperties.FIRSTNAME);

_middleName = GetProperty(directoryUser, ADProperties.MIDDLENAME);

_lastName = GetProperty(directoryUser, ADProperties.LASTNAME);

_loginName = GetProperty(directoryUser,ADProperties.LOGINNAME);

StringuserPrincipalName = GetProperty(directoryUser, ADProperties.USERPRINCIPALNAME);

if(!string.IsNullOrEmpty(userPrincipalName))

{

domainAddress = userPrincipalName.Split('@')[1];

}

else

{

domainAddress = String.Empty;

}


if(!string.IsNullOrEmpty(domainAddress))

{

domainName = domainAddress.Split('.').First();

}

else

{

domainName = String.Empty;

}

_loginNameWithDomain = String.Format(@"{0}\{1}", domainName, _loginName);

_streetAddress = GetProperty(directoryUser, ADProperties.STREETADDRESS);

_city = GetProperty(directoryUser, ADProperties.CITY);

_state = GetProperty(directoryUser,ADProperties.STATE);

_postalCode = GetProperty(directoryUser, ADProperties.POSTALCODE);

_country = GetProperty(directoryUser, ADProperties.COUNTRY);

_company = GetProperty(directoryUser, ADProperties.COMPANY);

_department = GetProperty(directoryUser, ADProperties.DEPARTMENT);

_homePhone = GetProperty(directoryUser,ADProperties.HOMEPHONE);

_extension = GetProperty(directoryUser, ADProperties.EXTENSION);

_mobile = GetProperty(directoryUser, ADProperties.MOBILE);

_fax = GetProperty(directoryUser, ADProperties.FAX);

_emailAddress = GetProperty(directoryUser,ADProperties.EMAILADDRESS);

_title = GetProperty(directoryUser,ADProperties.TITLE);

_manager = GetProperty(directoryUser, ADProperties.MANAGER);

if(!String.IsNullOrEmpty(_manager))

{

String[] managerArray = _manager.Split(',');

_managerName = managerArray[0].Replace("CN=", "");

}

}



private static StringGetProperty(DirectoryEntry userDetail, String propertyName)

{

if(userDetail.Properties.Contains(propertyName))

{

returnuserDetail.Properties[propertyName][0].ToString();

}

else

{

return string.Empty;

}

}


public static ADUserDetailGetUser(DirectoryEntry directoryUser)

{

return new ADUserDetail(directoryUser);

}

}

}

Step 5: Creating ADProperties class



Create or add a class in the project for ADProperties. This class will have the properties corresponding to the information of the AD User. This is a static class. This class is having all the properties as constant string for ADUser. This class is giving readable name to all the properties of user details.

ADProperties.cs


using System;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;


namespaceActiveDirectoryHelper

{

public static class ADProperties

{

public const StringOBJECTCLASS = "objectClass";

public const String CONTAINERNAME = "cn";

public const StringLASTNAME = "sn";

public const StringCOUNTRYNOTATION = "c";

public const String CITY = "l";

public const String STATE = "st";

public const String TITLE = "title";

public const StringPOSTALCODE = "postalCode";

public const StringPHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName";

public const StringFIRSTNAME = "givenName";

public const StringMIDDLENAME = "initials";

public const StringDISTINGUISHEDNAME = "distinguishedName";

public const StringINSTANCETYPE = "instanceType";

public const StringWHENCREATED = "whenCreated";

public const StringWHENCHANGED = "whenChanged";

public const StringDISPLAYNAME = "displayName";

public const StringUSNCREATED = "uSNCreated";

public const StringMEMBEROF = "memberOf";

public const StringUSNCHANGED = "uSNChanged";

public const StringCOUNTRY = "co";

public const String DEPARTMENT = "department";

public const StringCOMPANY = "company";

public const StringPROXYADDRESSES = "proxyAddresses";

public const StringSTREETADDRESS = "streetAddress";

public const String DIRECTREPORTS = "directReports";

public const String NAME = "name";

public const StringOBJECTGUID = "objectGUID";

public const StringUSERACCOUNTCONTROL = "userAccountControl";

public const StringBADPWDCOUNT = "badPwdCount";

public const StringCODEPAGE = "codePage";

public const StringCOUNTRYCODE = "countryCode";

public const StringBADPASSWORDTIME = "badPasswordTime";

public const String LASTLOGOFF = "lastLogoff";

public const String LASTLOGON = "lastLogon";

public const StringPWDLASTSET = "pwdLastSet";

public const StringPRIMARYGROUPID = "primaryGroupID";

public const StringOBJECTSID = "objectSid";

public const StringADMINCOUNT = "adminCount";

public const String ACCOUNTEXPIRES = "accountExpires";

public const StringLOGONCOUNT = "logonCount";

public const StringLOGINNAME = "sAMAccountName";

public const StringSAMACCOUNTTYPE = "sAMAccountType";

public const StringSHOWINADDRESSBOOK = "showInAddressBook";

public const StringLEGACYEXCHANGEDN = "legacyExchangeDN";

public const StringUSERPRINCIPALNAME = "userPrincipalName";

public const StringEXTENSION = "ipPhone";

public const StringSERVICEPRINCIPALNAME = "servicePrincipalName";

public const StringOBJECTCATEGORY = "objectCategory";

public const StringDSCOREPROPAGATIONDATA = "dSCorePropagationData";

public const StringLASTLOGONTIMESTAMP = "lastLogonTimestamp";

public const StringEMAILADDRESS = "mail";

public const StringMANAGER = "manager";

public const StringMOBILE = "mobile";

public const String PAGER = "pager";

public const String FAX ="facsimileTelephoneNumber";

public const StringHOMEPHONE = "homePhone";

public const StringMSEXCHUSERACCOUNTCONTROL = "msExchUserAccountControl";

public const StringMDBUSEDEFAULTS = "mDBUseDefaults";

public const StringMSEXCHMAILBOXSECURITYDESCRIPTOR = "msExchMailboxSecurityDescriptor";

public const StringHOMEMDB = "homeMDB";

public const StringMSEXCHPOLICIESINCLUDED = "msExchPoliciesIncluded";

public const StringHOMEMTA = "homeMTA";

public const String MSEXCHRECIPIENTTYPEDETAILS = "msExchRecipientTypeDetails";

public const StringMAILNICKNAME = "mailNickname";

public const StringMSEXCHHOMESERVERNAME = "msExchHomeServerName";

public const StringMSEXCHVERSION = "msExchVersion";

public const String MSEXCHRECIPIENTDISPLAYTYPE = "msExchRecipientDisplayType";

public const StringMSEXCHMAILBOXGUID = "msExchMailboxGuid";

public const StringNTSECURITYDESCRIPTOR = "nTSecurityDescriptor";

}

}


Step 6. Creating ActiveDirectoryHelper class



<!--[if !supportLists]-->1. <!--[endif]-->This class will have all the function to perform operations to Active Directory.

<!--[if !supportLists]-->2. <!--[endif]-->There are four properties in the class

LDAPPath property


This property is reading the LDAPPath from config file.

private StringLDAPPath

{

get

{

return ConfigurationManager.AppSettings["LDAPPath"];

}

}



LDAPUser property



This property is reading the LDAP user from the config file.


private StringLDAPUser

{

get

{

return ConfigurationManager.AppSettings["LDAPUser"];

}

}


LDAPPassword property


This property is reading the LDAP Password from the config file.

private StringLDAPPassword

{

get

{

return ConfigurationManager.AppSettings["LDAPPassword"];

}

}


Search Root Property


This Property is initializing the Directory entry by passing the LDAPUser, LDAPPAth, and LDAPPassword. This property is creating a new instance DirectoryEntry and returning that.

private DirectoryEntrySearchRoot

{

get

{

if(_directoryEntry == null)

{

_directoryEntry = new DirectoryEntry(LDAPPath, LDAPUser, LDAPPassword, AuthenticationTypes.Secure);

}

return_directoryEntry;

}

}

Various operations in ActiveDirectoryHelper class


Get User by Full Name


This function will take a full name as input parameter and return AD user corresponding to that.

public ADUserDetailGetUserByFullName(String userName)

{

try

{

_directoryEntry = null;

DirectorySearcherdirectorySearch = new DirectorySearcher(SearchRoot);

directorySearch.Filter = "(&(objectClass=user)(cn=" + userName + "))";

SearchResultresults = directorySearch.FindOne();


if(results != null)

{

DirectoryEntryuser = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);

return ADUserDetail.GetUser(user);

}

else

{

return null;

}

}

catch(Exception ex)

{

return null;

}

}

Get User by Login Name


This function will return AD user. This takes Login name as input parameter.

public ADUserDetail GetUserByLoginName(String userName)

{

try

{

_directoryEntry = null;

DirectorySearcherdirectorySearch = new DirectorySearcher(SearchRoot);

directorySearch.Filter = "(&(objectClass=user)(SAMAccountName="+ userName + "))";

SearchResultresults = directorySearch.FindOne();


if(results != null)

{

DirectoryEntryuser = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);

return ADUserDetail.GetUser(user);

}

return null;

}

catch(Exception ex)

{

return null;

}

}

Get Users by from a AD Group by Group Name


This function will take a group name as input and return list of AD User in that group.

public List<ADUserDetail> GetUserFromGroup(String groupName)

{

List<ADUserDetail> userlist = new List<ADUserDetail>();

try

{

_directoryEntry = null;

DirectorySearcherdirectorySearch = new DirectorySearcher(SearchRoot);

directorySearch.Filter = "(&(objectClass=group)(SAMAccountName="+ groupName + "))";

SearchResultresults = directorySearch.FindOne();

if(results != null)

{


DirectoryEntrydeGroup = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);

System.DirectoryServices.PropertyCollection pColl = deGroup.Properties;

intcount = pColl["member"].Count;



for(int i = 0; i < count; i++)

{

string respath = results.Path;

string[] pathnavigate = respath.Split("CN".ToCharArray());

respath = pathnavigate[0];

string objpath = pColl["member"][i].ToString();

string path = respath + objpath;



DirectoryEntry user = new DirectoryEntry(path, LDAPUser, LDAPPassword);

ADUserDetail userobj = ADUserDetail.GetUser(user);

userlist.Add(userobj);

user.Close();

}

}

returnuserlist;

}

catch(Exception ex)

{

returnuserlist;

}


}

Get Users and Group by from a AD basis on starting with string


This function will return Users and Group information from AD on basis of first characters. Wild character * is used to filter the criteria.

public List<ADUserDetail>GetUsersByFirstName(string fName)

{


//UserProfile user;

List<ADUserDetail> userlist = new List<ADUserDetail>();

stringfilter = "";


_directoryEntry = null;

DirectorySearcherdirectorySearch = new DirectorySearcher(SearchRoot);

directorySearch.Asynchronous = true;

directorySearch.CacheResults = true;

//directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))";

filter = string.Format("(givenName={0}*", fName);

//filter = "(&(objectClass=user)(objectCategory=person)" + filter + ")";

filter = "(&(objectClass=user)(objectCategory=person)(givenName="+fName+"*))";



directorySearch.Filter = filter;


SearchResultCollectionuserCollection = directorySearch.FindAll();

foreach(SearchResult users inuserCollection)

{

DirectoryEntryuserEntry = new DirectoryEntry(users.Path, LDAPUser, LDAPPassword);

ADUserDetailuserInfo = ADUserDetail.GetUser(userEntry);



userlist.Add(userInfo);

}


directorySearch.Filter = "(&(objectClass=group)(SAMAccountName="+fName + "*))";

SearchResultCollectionresults = directorySearch.FindAll();

if (results !=null)

{


foreach(SearchResult r inresults)

{

DirectoryEntry deGroup = new DirectoryEntry(r.Path, LDAPUser, LDAPPassword);

// ADUserDetail dhan = new ADUserDetail();

ADUserDetail agroup = ADUserDetail.GetUser(deGroup);

userlist.Add(agroup);

}


}

returnuserlist;

}

Adding User to Active Directory Group


This function will take a user login name and add this to a group of AD.

public boolAddUserToGroup(string userlogin, string groupName)

{

try

{

_directoryEntry = null;

ADManageradmanager = new ADManager(LDAPDomain, LDAPUser, LDAPPassword);

admanager.AddUserToGroup(userlogin, groupName);

return true;

}

catch(Exception ex)

{

return false;

}

}

Removing User to Active Directory Group



This function will take a user login name and remove this to a group of AD.


public bool RemoveUserToGroup(stringuserlogin, string groupName)

{

try

{

_directoryEntry = null;

ADManageradmanager = new ADManager("xxx", LDAPUser, LDAPPassword);

admanager.RemoveUserFromGroup(userlogin, groupName);

return true;

}

catch(Exception ex)

{

return false;

}

}


In above two functions ADManagerclass is being used for adding and removing user in AD.

ADManager.cs


using System;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.DirectoryServices.AccountManagement;


namespaceActiveDirectoryHelper

{

public class ADManager

{


PrincipalContextcontext;


publicADManager()

{

context = new PrincipalContext(ContextType.Machine,"xxx", "xxx","xxx");


}



publicADManager(string domain, string container)

{

context = new PrincipalContext(ContextType.Domain, domain, container);

}


publicADManager(string domain, string username, stringpassword)

{

context = new PrincipalContext(ContextType.Domain, username, password);

}


public bool AddUserToGroup(stringuserName, string groupName)

{

booldone = false;

GroupPrincipalgroup = GroupPrincipal.FindByIdentity(context, groupName);

if(group == null)

{

group = new GroupPrincipal(context, groupName);

}

UserPrincipaluser = UserPrincipal.FindByIdentity(context, userName);

if(user != null & group != null)

{

group.Members.Add(user);

group.Save();

done = (user.IsMemberOf(group));

}

returndone;

}



public bool RemoveUserFromGroup(stringuserName, string groupName)

{

booldone = false;

UserPrincipaluser = UserPrincipal.FindByIdentity(context, userName);

GroupPrincipalgroup = GroupPrincipal.FindByIdentity(context, groupName);

if(user != null & group != null)

{

group.Members.Remove(user);

group.Save();

done = !(user.IsMemberOf(group));

}

returndone;

}

}

}


This is the way all the operation could be perform on the AD.

Complete code for ActiveDirectoryHelper.cs class



using System;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.DirectoryServices;

usingSystem.Configuration;


namespaceActiveDirectoryHelper

{

public class ActiveDirectoryHelper

{

private DirectoryEntry_directoryEntry = null;


private DirectoryEntrySearchRoot

{

get

{

if(_directoryEntry == null)

{

_directoryEntry = new DirectoryEntry(LDAPPath, LDAPUser, LDAPPassword, AuthenticationTypes.Secure);

}

return_directoryEntry;

}

}


private StringLDAPPath

{

get

{

return ConfigurationManager.AppSettings["LDAPPath"];

}

}


private StringLDAPUser

{

get

{

return ConfigurationManager.AppSettings["LDAPUser"];

}

}


private StringLDAPPassword

{

get

{

return ConfigurationManager.AppSettings["LDAPPassword"];

}

}


private StringLDAPDomain

{

get

{

return ConfigurationManager.AppSettings["LDAPDomain"];

}

}


internal ADUserDetailGetUserByFullName(String userName)

{

try

{

_directoryEntry = null;

DirectorySearcherdirectorySearch = new DirectorySearcher(SearchRoot);

directorySearch.Filter = "(&(objectClass=user)(cn=" + userName + "))";

SearchResultresults = directorySearch.FindOne();


if(results != null)

{

DirectoryEntryuser = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);

return ADUserDetail.GetUser(user);

}

else

{

return null;

}

}

catch(Exception ex)

{

return null;

}

}


public ADUserDetailGetUserByLoginName(String userName)

{

try

{

_directoryEntry = null;

DirectorySearcherdirectorySearch = new DirectorySearcher(SearchRoot);

directorySearch.Filter = "(&(objectClass=user)(SAMAccountName="+ userName + "))";

SearchResultresults = directorySearch.FindOne();


if(results != null)

{

DirectoryEntryuser = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);

return ADUserDetail.GetUser(user);

}

return null;

}

catch(Exception ex)

{

return null;

}

}



/// <summary>

/// This function will take a DL or Group name and return list of users

/// </summary>

/// <param name="groupName"></param>

/// <returns></returns>

public List<ADUserDetail> GetUserFromGroup(String groupName)

{

List<ADUserDetail> userlist = new List<ADUserDetail>();

try

{

_directoryEntry = null;

DirectorySearcherdirectorySearch = new DirectorySearcher(SearchRoot);

directorySearch.Filter = "(&(objectClass=group)(SAMAccountName="+ groupName + "))";

SearchResultresults = directorySearch.FindOne();

if(results != null)

{


DirectoryEntrydeGroup = new DirectoryEntry(results.Path, LDAPUser, LDAPPassword);

System.DirectoryServices.PropertyCollection pColl = deGroup.Properties;

intcount = pColl["member"].Count;



for(int i = 0; i < count; i++)

{

string respath = results.Path;

string[] pathnavigate = respath.Split("CN".ToCharArray());

respath = pathnavigate[0];

stringobjpath = pColl["member"][i].ToString();

string path = respath + objpath;



DirectoryEntry user = new DirectoryEntry(path, LDAPUser, LDAPPassword);

ADUserDetail userobj = ADUserDetail.GetUser(user);

userlist.Add(userobj);

user.Close();

}

}

returnuserlist;

}

catch(Exception ex)

{

returnuserlist;

}


}


#region Get user with First Name


public List<ADUserDetail>GetUsersByFirstName(string fName)

{


//UserProfile user;

List<ADUserDetail> userlist = new List<ADUserDetail>();

stringfilter = "";


_directoryEntry = null;

DirectorySearcherdirectorySearch = new DirectorySearcher(SearchRoot);

directorySearch.Asynchronous = true;

directorySearch.CacheResults = true;

filter = string.Format("(givenName={0}*", fName);

// filter = "(&(objectClass=user)(objectCategory=person)(givenName="+fName+"*))";



directorySearch.Filter = filter;


SearchResultCollectionuserCollection = directorySearch.FindAll();

foreach(SearchResult users inuserCollection)

{

DirectoryEntryuserEntry = new DirectoryEntry(users.Path, LDAPUser, LDAPPassword);

ADUserDetailuserInfo = ADUserDetail.GetUser(userEntry);


userlist.Add(userInfo);


}


directorySearch.Filter = "(&(objectClass=group)(SAMAccountName="+fName + "*))";

SearchResultCollectionresults = directorySearch.FindAll();

if(results != null)

{


foreach(SearchResult r inresults)

{

DirectoryEntry deGroup = new DirectoryEntry(r.Path, LDAPUser, LDAPPassword);


ADUserDetail agroup = ADUserDetail.GetUser(deGroup);

userlist.Add(agroup);

}


}

returnuserlist;

}


#endregion



#region AddUserToGroup

public boolAddUserToGroup(string userlogin, string groupName)

{

try

{

_directoryEntry = null;

ADManageradmanager = new ADManager(LDAPDomain, LDAPUser, LDAPPassword);

admanager.AddUserToGroup(userlogin, groupName);

return true;

}

catch(Exception ex)

{

return false;

}

}

#endregion


#region RemoveUserToGroup

public boolRemoveUserToGroup(string userlogin, string groupName)

{

try

{

_directoryEntry = null;

ADManageradmanager = new ADManager("xxx", LDAPUser, LDAPPassword);

admanager.RemoveUserFromGroup(userlogin, groupName);

return true;

}

catch(Exception ex)

{

return false;

}

}

#endregion

}

}

How to use this class library


Just add DLL or reference of this project to your application and make an Instance of ActiveDirectoryHelperclass. After an instance is created, you may call the functions and properties to perform the operations on AD.

How to mentain a Log file

public void LogMessage(string sMessage)
        {
            string sDate = DateTime.Now.ToString() + " : ";
            File.AppendAllText(@"C:\ApplicationData\Cloud.log", sDate + sMessage + Environment.NewLine);
        }

What is the difference between SharePoint Foundation and SharePoint 2010, or between Standard and Enterprise editions?

“What is the difference between SharePoint Foundation and SharePoint 2010?” “What is part of Standard and Enterprise editions?” These are two of the most common questions I get asked by both people who are new to the SharePoint platform and by people who have worked with one flavor of SharePoint.

Microsoft has a great resource that lists exactly which features are part of which edition of SharePoint. You can even filter the features list by functional area (sites, communities, content, search, insights, and composites). Not only is each feature listed, but hovering over the feature will display a short description of the features. Some features even link to a video showing the feature.

image

This is one of the few golden resources that I recommend you print, bookmark, email to colleagues, send to OneNote, tweet, … whatever it takes to make it readily available. Enjoy.

Sharepoint 2010 Form Based Authentication Using Active Directory

In this article I will try to show how we can use Active Directory Form Based Authentication in Sharepoint 2010 using Lightweight Directory Access Protocol (LDAP)
1. Add Connection string and membership provider in Central Administration web.config
1.png

2.png

3.png

4.png

NOTE: connectionString will differ based on domain configuration. Please contact you Administrator to provide the LDAP details.
2. Add Connection string and membership provider in SecurityTokenServiceApplication web.config
5.png

6.png

7.png

NOTE: connectionString will differ based on domain configuration. Please contact you Administrator to provide the LDAP details.

3. Create a new site with claim based authentication using Central Administration
8.png

Authentication : Claim Based
Claims Authentication Types: Enable Windows Authentication -> Integrated Windows authentication - > NTLM
Leave others to default

9.png
4. Now Create Site Collection at port 2233
10.png

And add Primary / Secondary Site Collection Administrators

11.png

12.png

So the resultant site will look like below.
13.png

5 Extend the web application to port 3322 and enable form based authentication (FBA)
14.png

Set the public URL Zone- Intranet or Extranet
5. Add Users to the Intranet zone using User Policy
15.png

16.png

17.png

18.png

Add more users as required with desired permissions.
Now open the newly extended application, and use your domain credentials to login the app.

19.png

20.png

Wednesday, 30 May 2012

How to setup FBA Claims in SharePoint 2010 with A D Membership Provider

In this post I am going to explain how to set up a SharePoint 2010 claims base authentication from Active Directory Membership Provider.

There are several posts which follow certain config changes and some other entries to achieve the same. But, after following atleast 10 of them, I was still stuck. I have finally figured out the sequence of events to be done to achieve the desired output.

Step1: Create web application with Claims Authentication Mode. Go to Central Admin, Create new web application. Choose Claims Based Authentication.
Now, here when you reach the identity providers section, you can also choose windows also as your identity provider along with forms. For testing purposes, I started with taking both windows and forms as my provider.
Enter the name of your membership provider. I am taking the name as 'admember'.

Step2: Next you need to make changes in three web.config entries:
1. Web config of Central Admin.
2. Web config of your newly created web application.
3. Web config of STS (Security Token Service) application.

Open the web config of Central Admin and add the below entries:First the connection string,
'connectionStrings'
'add name="adconn"'
'connectionString="LDAP://logimindz.net/CN=Users,DC=logimindz,DC=net"/
/connectionStrings'

Here, connecton strin represents the below:
LDAP://abc.com/cn=users,dc=abc,dc=com/ This will change according to your organisation.

Then the provider
add name="admembers"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="adconn"
enableSearchMethods="true"
attributeMapUsername="sAMAccountName" /

Make sure the connection string is placed outside the 'System.Web' section and the 'provider' is placed within the System.web section.

Make sure the provider admembers is the default provider against your membership tag.

Open the web config of the web application

First the connection string:
connectionstrings>
add name="adconn" connectionString="LDAP://logimindz.net/CN=Users,DC=logimindz,DC=net"/
/connectionStrings

Next search the word 'membership' in your config file. You will find there is already a membership declared with the name 'i'. Add the below to the membership tag.

add name="admembers"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="adconn"
enableSearchMethods="true"
attributeMapUsername="sAMAccountName" /

Make sure the provider i is the default provider against your membership tag.

Save and close the web.config.

Open the web.config of your STS:

You can do this in two ways - Go to inetmgr - Sites - Sharepoint web services - SecurityTokenServiceApplication. Click on explore and open the web.config.
Or go to c:/program files/common files/ microsoft shared/ web server extensions/web services/security token and open the web.config

First add the connection string:
connectionStrings>
add name="adconn" connectionString="LDAP://logimindz.net/CN=Users,DC=logimindz,DC=net"/
/connectionStrings

Then add the provider entry:
add name="admembers"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="adconn"
enableSearchMethods="true"
attributeMapUsername="sAMAccountName" /

You will probably need to add the 'System.Web' tag also. The below tags will need to be added:

'System.Web'
'Membership'
'Providers'
'Add name='

Next do an iisreset.

Step3: Wire up provider to the web application

1. Go to CA - Web application management page, select your web application and choose 'Authentication Providers' from the ribbon.
2. Choose 'Default' and go the 'Identity Providers' section.
3. Select 'Enable ASP.net membership and role provider' and type the name of your provider in the text box.

Step4: Add users for the web application

1. Select your web application.
2. Hit User policy in the ribbon above.
3. Hit the browse users button in the people picker web part.
4. Notice the dialog box is changed, there are sections like 'Active Directory', 'All Users', 'Form Auth', 'Organization'.
5. Type in an AD user name and search.
6. There should be two results for the same user - one through NTLM and one through form auth. Select the user from form auth result and hit finish.

Step5: Create top level site in the web application

Now you can create the desired top level site in the web application. You will get two options while trying to log in - Windows and Form based authentication.

You can either use both or disable windows auth from the web application settings to get only form based login.

How to create a SharePoint menu from xml

We had a requirement wherein we wanted to create a SharePoint menu with 4 level of menus. We used an xml source for the same for the same.

Step1: Create a document library and add a new xml document from SharePoint designer.

Step 2: Open your master page and add a new datasource. To add a new datasource, click on the above ribbon and select DataSource - select your xml file. It will include the below code in your master page

'SharePoint:SPXmlDataSource runat="server" id="SPXmlDataSource1"' 'DataFileParameters' 'asp:Parameter Name="FileName" DefaultValue="main_menu.xml"/' 'asp:Parameter Name="FilePath" DefaultValue="Menu"/' '/DataFileParameters' '/SharePoint:SPXmlDataSource'

Step 3: Make the below changes in your AspMenu control:

'SharePoint:AspMenu
ID="SPSiteMapProvider1"
Runat="server"
EnableViewState="false"
DataSourceID="SPXmlDataSource1"
UseSimpleRendering="true"
UseSeparateCss="false"
Orientation="Horizontal"
StaticDisplayLevels="2"
MaximumDynamicDisplayLevels="4"
SkipLinkText=""
CssClass="Custom-tn"'
'DataBindings'
'asp:menuitembinding NavigateUrlField="url"
TextField="text" /' '/DataBindings'
'/SharePoint:AspMenu'


Notice two things above - DataSourceID is the same as the XML datasource.
Also, we have included something as DataBindings to get the exact value from the xml. This is going to change depending on the text field in the xml you are using.

In case you need the same setting for your sub sites as well, you will need to create another master page. Simply copy everything in your master page, create a new one and make the below change.

Adding metadata properties in advanced search

While we were working with search, we created hiererchy, we created managed metadata properties and added refinements to our search on basis of those managed metadata properties.
Now, we want the same metadata properties in our advanced search. How to customise the advanced search webpart to view our metadata properties.

1. Go to the advanced search page, click on edit page
2. Click on 'Edit web part' on the Advance search box web part.
3. Expand the properties section.
4. Copy the xml in the properties section, paste to xml editor or visual studio.
5. Collapse all nodes.The last two nodes are the ones which we have to change.
6. First is the propertydefs node.
7. Copy and paste the below line in the property defs tag -
PropertyDef Name="Department" DataType="text" DisplayName="Department"
8. Now go to the 'ResultTypes' node and paste the below line in each section - PropertyRef Name="Department"
9. This line should go in all the sub sections of 'ResultTypes'.
10. Copy this xml and paste in the properties section of the web part.
11. Click on OK and come out of edit.

You will see the property as below in the advanced search section: