Monday, October 19, 2009

Output Active Directory LDAP user properties to MS Word

Sometimes you want to generate Outlook signatures automatically using a users's Active Directory data. There are plenty of articles on how to do this during a user login event, but I thought I'd pass along some code in C#, because almost everything out there is in VBscript, which is fine but I'm sick of using scripts and there are certain tricks you cannot pull, like making an image, like a logo or a twitter button, into a link within the signature.  For that, you'll need the full Word Interop.

Here is a little function that will get you through the part I found trickiest.  Note that you'll need to add the following references:
  • Microsoft.Office.Interop.Word
  • System.DirectoryServices
  • System.DirectoryServices.AccountManagement...
*************************************

using Word = Microsoft.Office.Interop.Word;

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

protected void PrintLdapProperties()
{

Word.Application oApplication = new Microsoft.Office.Interop.Word.Application();
oApplication.Visible = true;

if (oApplication == null)
{
return;
}

string strDistinguishedName = UserPrincipal.Current.DistinguishedName;
DirectoryEntry oEntry = new DirectoryEntry("LDAP://" + strDistinguishedName);
System.DirectoryServices.PropertyCollection oColl = oEntry.Properties;
Object oMissing = System.Type.Missing;
Word.Document oDocument = oApplication.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
Word.Selection oSelection = oApplication.Selection;

int NumRows = 2;
int NumColumns = 2;

Microsoft.Office.Interop.Word.Table oTable = oSelection.Tables.Add(oSelection.Range, NumRows, NumColumns, ref oMissing, ref oMissing);

Microsoft.Office.Interop.Word.Cell oCell = oTable.Cell(1, 1);

int i = 1;

foreach (string strPropertyName in oColl.PropertyNames)

{

oCell.Select();
oSelection.TypeText(strPropertyName);
oCell.Next.Select();
oSelection.TypeText(oColl[strPropertyName].Value.ToString());
oTable.Rows.Add(ref oMissing);
oCell = oTable.Cell(i + 1, 1);
i++;

}

}

No comments:

Post a Comment