Monday, February 18, 2013

How to programmatically create cross-site lookup field

Hi,
when you use SharePoint 2010 you may need to create cross-site lookup field. That is problem because SP 2010 doesn't natively support this kind of field. But as always there is some work around :) Even though the work around doesn't involve GUI, it isn't difficult at all.
Here is sample of code how you can easily create cross-site lookup field:


//Add new column to list and ensure cross side lookup
try
{
    //Web contains list where a new column is required
    SPSite currentSite = new SPSite("https://server/siteContainsListWithRequiredNewColumn");
    SPWeb currentWeb = currentSite.OpenWeb();
    SPList currentlist = currentWeb.Lists["Some List"];
               
    //Web that holds data for lookup field
    SPSite lookupSite = new SPSite("https://server/lookupSite");
    SPWeb lookupWeb = lookupSite.OpenWeb();
    SPList lookupList = lookupWeb.Lists["Lookup list"];

    string fieldXML = "<Field DisplayName='Name of new column' Type='Lookup' Required='TRUE' List='" + lookupList.ID + "' WebId='" + lookupWeb.ID + "' Name='LookupField' ShowField='" + "Viewed field" + "' />";
    //Add new column to the list
    currentlist.Fields.AddFieldAsXml(fieldXML, true, SPAddFieldOptions.AddFieldToDefaultView);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

Ok that's it... not too bad right? Once you create your custom cross-site lookup field you can open column properties in list properties and there you should be able to change some its properties...
After you you add cross-site field I would recommend you to open column properties although you don't need to change anything. It happened to me that newly added column doesn't work properly and re-saving those column properties solved problem.

Happy codding....

Friday, February 15, 2013

Start with developing applications to work with Active Directory using C# code

Hi developers,
It has been while since I post last article. Actually I was planning to post this a little bit earlier, but... you know those excuses :-D
So what this is all about. I had to create project which has to operate with Active Directory and that was quite a new stuff for me. I though it won't be difficult and as usual I was wrong :-D Well, to be clear it isn't as difficult as it is confusing :) So this article isn't for describing some hard codding stuffs, but it should be good starter for anyone who has no experience in this and wants to find a quick and straight way to start developing. (Let's face it, most of the demands involve just simple operation in the active directory) So enough jibber-jabber...

 For the start you should know there are two libraries to work with AD. System.DirectoryServices and System.DirectoryServices.AccountManagement, In my opinion DirectoryServices is the most powerful, but difficult to use. AccountManagement is quite easier but it won't let you to do "everything" you want to. Here is large article about them and it contains a lot of information and examples: http://ianatkinson.net/computing/adcsharp.htm#examples2 and there is even more on the Internet ;-). But I will stick just with the introduction these classes to make this post simple as much as it is possible.
Now you may wondering what this post is about. Well I am gonna show you sample code of both libraries, then describe how to extend AccountManagement to let you do more cool stuffs and at the end I will show you some workarounds I had to use when I was codding project.

System.DirectoryServices
For start do not forget use this using System.DirectoryServices; using statement.
And here is the code



//User's sAMAccountName
            string user = "User's sAMAccountName";
            try
            {
                //Connect to the AD
                DirectoryEntry de = new DirectoryEntry("LDAP://serverIP_or_adress", @"userName", "password");

                //Create a new instance of DirectorySearcher class to find required user
                DirectorySearcher deSearch = new DirectorySearcher();

                //Set the start of searching
                deSearch.SearchRoot = de;
                //Set filter
                deSearch.Filter = "(&(objectClass=user) (sAMAccountName=" + user + "))";

                //Save result to the instance of SearchResult class
                SearchResult result = deSearch.FindOne();

                //Check the result
                if (result != null)
                {
                    //Save new to the instnce of DirectoryEntry so you can operate with user.
                    DirectoryEntry foundedUser = new DirectoryEntry(result.Path);

                    //Create a writer and open the file
                    TextWriter tw = new StreamWriter("ADUserDefaultProperties.txt");

                    //Loop through all users properties
                    foreach (var property in result.Properties.PropertyNames)
                    {
                        try
                        {
                            if (result.Properties[property.ToString()] != null && result.Properties[property.ToString()].Count > 0)
                            {
                                tw.WriteLine(property.ToString() + ": " + foundedUser.Properties[property.ToString()].Value.ToString());
                            }
                            else
                            {
                                tw.WriteLine(property.ToString() + ": " + "Couldn't reach the property!");
                            }
                        }
                        catch (NullReferenceException nullEx)
                        {
                            tw.WriteLine(property.ToString() + ": " + "Exception / Couldn't reach the property!");
                        }

                    }

                    // close the stream
                    tw.Close();
                }

            }

If you would need to change some user's attribute you can use this code:
foundedUser.Rename("cn=" + name + " " + surname);
foundedUser.CommitChanges();
There is more you can do with System.DirectoryServices, but it is not theme of this post...

System.DirectoryServices.AccountManagement
Again do not forget to add: using System.DirectoryServices.AccountManagement;
This code is actually from site I mentioned above:
// enter AD settings 
PrincipalContext AD = new PrincipalContext(ContextType.Domain, "leeds-art.ac.uk");

// create search user and add criteria 
Console.Write("Enter logon name: ");
UserPrincipal u = new UserPrincipal(AD);
u.SamAccountName = Console.ReadLine();

// search for user 
PrincipalSearcher search = new PrincipalSearcher(u);
UserPrincipal result = (UserPrincipal)search.FindOne();
//Do not forget to dispose search object
search.Dispose();

// show some details 
Console.WriteLine("Display Name : " + result.DisplayName);
Console.WriteLine("Phone Number : " + result.VoiceTelephoneNumber);

Nothing difficult right? But what if I want to have access to other properties except DisplayName, VoiceTelephoneNumber etc. You can have your own properties in AD which need to be accessed. You will have to use extend UserPrincipal class.Then you will have access to the other attributes (actually you will have access to the attributes you defined in your extended class :) ) I won't show this approach here because you can find great example on the msdn: http://msdn.microsoft.com/en-us/library/bb384372(v=vs.90).aspx
I just would like to point out another great extended class you can find there. It is extending AvanceFilters class. If you will extend this class you can define your own criteria for searching in AD. Isn't that great? And it simple like this:
public class UserPrincipalsExSearchFilter : AdvancedFilters
    {
        public UserPrincipalsExSearchFilter(Principal p) : base(p) { }
        public void EmployeeID(int value, MatchType mt)
        {
            this.AdvancedFilterSet("employeeID", value.ToString(), typeof(string), mt);
        }

    }


Ok that's all for introduction. I know I haven't mentioned how to create user, delete user etc., but those things you can easily "google it". Once you know where to start and that there are two main classes to work with AD(and if you can distinguish their purposes) the rest of the work should be a peace of cake. At least for the start...
At the end I would like to mention two "problems" I had. 
1. Once I wasn't able to update property in AD using System.DirectoryServices.AccountManagement. You can always combine both classes if you want to. So if you already have UserPrincipal of some user, you don't need to search him again using DirectoryServices. You can do it like this:
DirectoryEntry de = (DirectoryEntry)userPrincipalOfNewUser.GetUnderlyingObject();
                                de.Rename("cn=" + userPrincipalOfNewUser.Surname + " " + userPrincipalOfNewUser.GivenName);
                                de.CommitChanges();


This can be quite helpful I guess...

2. I was using those classes in WCF service and I could't connect to the AD server or do any changes. My problem was with impersonation. So simple wrap your code like this:
using (HostingEnvironment.Impersonate())
{
  //Put your code here
}
It helped me ;)

Ok that's all...I hope this will help you to start with DirectoryServices and AccountManagement classes.
Happy codding..