Skip to main content

Active Directory to hCard Web Service

I’ve been playing around further with microformats this week and I decided to come up with something practical I could use to transfer contact information between apps. As a starting point because most of my contact information is stored in active directory I wanted something that would be able to convert an Active Directory user object into a hCard contact. As a conduit I decided to go with a WebService as this was something that could be easily integrated into everything from a script to a fully blown windows application. There are some good tools already out there that can deal with the information once its in hCard form like Tails for Firefox or Technorati Contacts Feed Service .

The webservice itself is pretty basic it takes the useraccount name as an input parameter for which account you want to convert and then it returns a XML document that contains the user account information that has been extracted from various active directory attributes using the System.directoryservice namespace and then formatted as a hcard using the XMLtextwriter. Because the hcard format is based on the vcard format matching the information from AD wasn’t that hard (although a little time consuming) the only thing that took at little time to work out was mapping the office attribute to the extended-address.

What can you do with hcard’s probably the one of the best examples at the moment in the Live clipboard. Its still an emerging standard but the coolest thing about it is once you have the contact information in a hcard format its very easy to work with as compared to a standard vcard.

I put a downloadable copy of the code here the code itself looks like


using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.DirectoryServices;
using System.Xml;
using System.IO;

[WebService(Namespace = "http://msgdev.mvps.org/ADhCardv2/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {

//Uncomment the following line if using designed components
//InitializeComponent();
}
public SearchResult GetADAccount(string snSamaccountname)
{

SearchResult srSearchResult;
DirectorySearcher dsDirectorySearcher = new DirectorySearcher();
string roRootDSE = dsDirectorySearcher.SearchRoot.Path;
DirectoryEntry deDirectoryEntry = new DirectoryEntry(roRootDSE);
dsDirectorySearcher.SearchScope = SearchScope.Subtree;
dsDirectorySearcher.Filter = "(sAMAccountName=" + snSamaccountname + ")";
dsDirectorySearcher.PropertiesToLoad.Add("co");
dsDirectorySearcher.PropertiesToLoad.Add("company");
dsDirectorySearcher.PropertiesToLoad.Add("displayName");
dsDirectorySearcher.PropertiesToLoad.Add("department");
dsDirectorySearcher.PropertiesToLoad.Add("distinguishedName");
dsDirectorySearcher.PropertiesToLoad.Add("description");
dsDirectorySearcher.PropertiesToLoad.Add("facsimileTelephoneNumber");
dsDirectorySearcher.PropertiesToLoad.Add("givenName");
dsDirectorySearcher.PropertiesToLoad.Add("homePhone");
dsDirectorySearcher.PropertiesToLoad.Add("info");
dsDirectorySearcher.PropertiesToLoad.Add("initials");
dsDirectorySearcher.PropertiesToLoad.Add("l");
dsDirectorySearcher.PropertiesToLoad.Add("mail");
dsDirectorySearcher.PropertiesToLoad.Add("middleName");
dsDirectorySearcher.PropertiesToLoad.Add("mobile");
dsDirectorySearcher.PropertiesToLoad.Add("name");
dsDirectorySearcher.PropertiesToLoad.Add("physicalDeliveryOfficeName");
dsDirectorySearcher.PropertiesToLoad.Add("postalCode");
dsDirectorySearcher.PropertiesToLoad.Add("postOfficeBox");
dsDirectorySearcher.PropertiesToLoad.Add("pager");
dsDirectorySearcher.PropertiesToLoad.Add("sn");
dsDirectorySearcher.PropertiesToLoad.Add("st");
dsDirectorySearcher.PropertiesToLoad.Add("streetAddress");
dsDirectorySearcher.PropertiesToLoad.Add("telephoneNumber");
dsDirectorySearcher.PropertiesToLoad.Add("title");
dsDirectorySearcher.PropertiesToLoad.Add("wWWHomePage");
srSearchResult = dsDirectorySearcher.FindOne();
return srSearchResult;
}
public XmlDocument CreatehCard(SearchResult srSearchResult)
{
string fnFirstname = "";
string snSurname = "";
string mnMiddleName = "";
string wwURLwebsite = "";
string emEmailAddress = "";
string hpHomephone = "";
string mpMobilephone = "";
string bpBusinessphone = "";
string saStreetAddress = "";
string pbPostofficeBox = "";
string stState = "";
string sbSuburb = "";
string cnCountry = "";
string pcPostcode = "";
string fnFaxNumber = "";
string tnTitle = "";
string cncompanyName = "";
string dnDepartmentName = "";
string noNote = "";
string eaExtendedAddress = "";


if (srSearchResult.Properties.Contains("givenName")) { fnFirstname = (string)srSearchResult.Properties["givenName"][0]; }
if (srSearchResult.Properties.Contains("sn")) { snSurname = (string)srSearchResult.Properties["sn"][0]; }
if (srSearchResult.Properties.Contains("middleName")) { mnMiddleName = (string)srSearchResult.Properties["middleName"][0]; }
if (srSearchResult.Properties.Contains("wWWHomePage")) { wwURLwebsite = (string)srSearchResult.Properties["wWWHomePage"][0]; }
if (srSearchResult.Properties.Contains("homePhone")) { hpHomephone = (string)srSearchResult.Properties["homePhone"][0]; }
if (srSearchResult.Properties.Contains("mobile")) { mpMobilephone = (string)srSearchResult.Properties["mobile"][0]; }
if (srSearchResult.Properties.Contains("telephoneNumber")) { bpBusinessphone = (string)srSearchResult.Properties["telephoneNumber"][0]; }
if (srSearchResult.Properties.Contains("mail")) { emEmailAddress = (string)srSearchResult.Properties["mail"][0]; }
if (srSearchResult.Properties.Contains("l")) { sbSuburb = (string)srSearchResult.Properties["l"][0]; }
if (srSearchResult.Properties.Contains("postalCode")) { pcPostcode = (string)srSearchResult.Properties["postalCode"][0]; }
if (srSearchResult.Properties.Contains("streetAddress")) { saStreetAddress = (string)srSearchResult.Properties["streetAddress"][0]; }
if (srSearchResult.Properties.Contains("co")) { cnCountry = (string)srSearchResult.Properties["co"][0]; }
if (srSearchResult.Properties.Contains("st")) { stState = (string)srSearchResult.Properties["st"][0]; }
if (srSearchResult.Properties.Contains("facsimileTelephoneNumber")) { fnFaxNumber = (string)srSearchResult.Properties["facsimileTelephoneNumber"][0]; }
if (srSearchResult.Properties.Contains("postOfficeBox")) { pbPostofficeBox = (string)srSearchResult.Properties["postOfficeBox"][0]; }
if (srSearchResult.Properties.Contains("title")) { tnTitle = (string)srSearchResult.Properties["title"][0]; }
if (srSearchResult.Properties.Contains("company")) { cncompanyName = (string)srSearchResult.Properties["company"][0]; }
if (srSearchResult.Properties.Contains("department")) { dnDepartmentName = (string)srSearchResult.Properties["department"][0]; }
if (srSearchResult.Properties.Contains("description")) { noNote = (string)srSearchResult.Properties["description"][0]; }
if (srSearchResult.Properties.Contains("physicalDeliveryOfficeName")) { eaExtendedAddress = (string)srSearchResult.Properties["physicalDeliveryOfficeName"][0]; }

XmlDocument hcHcardDocuemnt = new XmlDocument();
StringWriter xsXmlString = new StringWriter();
XmlWriter xrXmlWritter = new XmlTextWriter(xsXmlString);
// write Div
xrXmlWritter.WriteStartDocument();
xrXmlWritter.WriteStartElement("div");
xrXmlWritter.WriteAttributeString("class", "vcard");

//Name Element
xrXmlWritter.WriteStartElement("a");
xrXmlWritter.WriteAttributeString("class","url fn n");
xrXmlWritter.WriteAttributeString("href", wwURLwebsite);
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "given-name");
xrXmlWritter.WriteValue(fnFirstname);
xrXmlWritter.WriteEndElement();
if (mnMiddleName != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "additional-name");
xrXmlWritter.WriteValue(mnMiddleName);
xrXmlWritter.WriteEndElement();
}
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "family-name");
xrXmlWritter.WriteValue(snSurname);
xrXmlWritter.WriteEndElement();
// End Name element
// Email Element Start
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteStartElement("a");
xrXmlWritter.WriteAttributeString("class", "email fn");
xrXmlWritter.WriteAttributeString("href","mailto:" + emEmailAddress);
xrXmlWritter.WriteValue(fnFirstname + " " + snSurname);
xrXmlWritter.WriteEndElement();
if (bpBusinessphone != "")
{
//Primary Telephone Element
xrXmlWritter.WriteStartElement("div");
xrXmlWritter.WriteAttributeString("class", "tel");
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "value");
xrXmlWritter.WriteValue(bpBusinessphone);
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteStartElement("abbr");
xrXmlWritter.WriteAttributeString("class", "type");
xrXmlWritter.WriteAttributeString("title", "work");
xrXmlWritter.WriteValue("business");
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteEndElement();
}
//Home Telephone Elemenet
if (hpHomephone != "")
{
xrXmlWritter.WriteStartElement("div");
xrXmlWritter.WriteAttributeString("class", "tel");
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "value");
xrXmlWritter.WriteValue(hpHomephone);
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteStartElement("abbr");
xrXmlWritter.WriteAttributeString("class", "type");
xrXmlWritter.WriteAttributeString("title", "home");
xrXmlWritter.WriteValue("home");
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteEndElement();
}
//Mobile Phone Elemenet
if (mpMobilephone != "")
{
xrXmlWritter.WriteStartElement("div");
xrXmlWritter.WriteAttributeString("class", "tel");
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "value");
xrXmlWritter.WriteValue(mpMobilephone);
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteStartElement("abbr");
xrXmlWritter.WriteAttributeString("class", "type");
xrXmlWritter.WriteAttributeString("title", "cell");
xrXmlWritter.WriteValue("cell");
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteEndElement();
}
//Fax Elemenet
if (fnFaxNumber != "")
{
xrXmlWritter.WriteStartElement("div");
xrXmlWritter.WriteAttributeString("class", "tel");
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "value");
xrXmlWritter.WriteValue(fnFaxNumber);
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteStartElement("abbr");
xrXmlWritter.WriteAttributeString("class", "type");
xrXmlWritter.WriteAttributeString("title", "fax");
xrXmlWritter.WriteValue("fax");
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteEndElement();
}
// Address Element
xrXmlWritter.WriteStartElement("div");
xrXmlWritter.WriteAttributeString("class", "adr");
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "type");
xrXmlWritter.WriteValue("work");
xrXmlWritter.WriteEndElement();
if (pbPostofficeBox != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "post-office-box");
xrXmlWritter.WriteString(pbPostofficeBox);
xrXmlWritter.WriteEndElement();
}
if (eaExtendedAddress != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "extended-address");
xrXmlWritter.WriteString(eaExtendedAddress);
xrXmlWritter.WriteEndElement();
}
if (saStreetAddress != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "street-address");
xrXmlWritter.WriteString(saStreetAddress);
xrXmlWritter.WriteEndElement();
}
if (sbSuburb != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "locality");
xrXmlWritter.WriteString(sbSuburb);
xrXmlWritter.WriteEndElement();
}
if (stState != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "region");
xrXmlWritter.WriteString(stState);
xrXmlWritter.WriteEndElement();
}
if (cnCountry != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "country-name");
xrXmlWritter.WriteString(cnCountry);
xrXmlWritter.WriteEndElement();
}
if (pcPostcode != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "postal-code");
xrXmlWritter.WriteString(pcPostcode);
xrXmlWritter.WriteEndElement();
}
xrXmlWritter.WriteEndElement();
//End Address Element
//Title Element
if (tnTitle != "")
{
xrXmlWritter.WriteStartElement("div");
xrXmlWritter.WriteAttributeString("class", "title");
xrXmlWritter.WriteString(tnTitle);
xrXmlWritter.WriteEndElement();
}
// OrgElement
if (cncompanyName != "" | dnDepartmentName != "") {
xrXmlWritter.WriteStartElement("div");
xrXmlWritter.WriteAttributeString("class", "org");
if (cncompanyName != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "organization-name");
xrXmlWritter.WriteString(cncompanyName);
xrXmlWritter.WriteEndElement();
}
if (dnDepartmentName != "")
{
xrXmlWritter.WriteStartElement("span");
xrXmlWritter.WriteAttributeString("class", "organization-unit");
xrXmlWritter.WriteString(dnDepartmentName);
xrXmlWritter.WriteEndElement();
}
xrXmlWritter.WriteEndElement();
}
if (noNote != "") {
xrXmlWritter.WriteStartElement("div");
xrXmlWritter.WriteAttributeString("class", "note");
xrXmlWritter.WriteString(noNote);
xrXmlWritter.WriteEndElement();
}
// Div vcard End element
xrXmlWritter.WriteEndElement();
xrXmlWritter.WriteEndDocument();
// Load and Return a XML Document
hcHcardDocuemnt.LoadXml(xsXmlString.ToString());
return hcHcardDocuemnt;

}

[WebMethod]
public XmlDocument GethCard(string snSamaccountname)
{
XmlDocument xrXmldocresult;
try
{
SearchResult srSearchResult = this.GetADAccount(snSamaccountname);
if (srSearchResult != null) { xrXmldocresult = this.CreatehCard(srSearchResult); }
else
{
xrXmldocresult = new XmlDocument();
XmlElement xeFirstDivElement = xrXmldocresult.CreateElement("div");
xeFirstDivElement.InnerText = "Active Directory Account not Found";
xrXmldocresult.AppendChild(xeFirstDivElement);
}
}
catch(Exception e) {
xrXmldocresult = new XmlDocument();
XmlElement xeFirstDivElement = xrXmldocresult.CreateElement("ErrorOccured");
xeFirstDivElement.InnerText = e.Message.ToString();
xrXmldocresult.AppendChild(xeFirstDivElement);
XmlElement xeFirstDivElement1 = xrXmldocresult.CreateElement("ErrorLineNumber");
xeFirstDivElement1.InnerText = e.Source.ToString();
xrXmldocresult.AppendChild(xeFirstDivElement1);
}
return xrXmldocresult;
;

}

}

Popular posts from this blog

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Gr...

Sending a MimeMessage via the Microsoft Graph using the Graph SDK, MimeKit and MSAL

One of the new features added to the Microsoft Graph recently was the ability to create and send Mime Messages (you have been able to get Message as Mime for a while). This is useful in a number of different scenarios especially when trying to create a Message with inline Images which has historically been hard to do with both the Graph and EWS (if you don't use MIME). It also opens up using SMIME for encryption and a more easy migration path for sending using SMTP in some apps. MimeKit is a great open source library for parsing and creating MIME messages so it offers a really easy solution for tackling this issue. The current documentation on Send message via MIME lacks any real sample so I've put together a quick console app that use MSAL, MIME kit and the Graph SDK to send a Message via MIME. As the current Graph SDK also doesn't support sending via MIME either there is a workaround for this in the future my guess is this will be supported.

Export calendar Items to a CSV file using Microsoft Graph and Powershell

For the last couple of years the most constantly popular post by number of views on this blog has been  Export calendar Items to a CSV file using EWS and Powershell closely followed by the contact exports scripts. It goes to show this is just a perennial issue that exists around Mail servers, I think the first VBS script I wrote to do this type of thing was late 90's against Exchange 5.5 using cdo 1.2. Now it's 2020 and if your running Office365 you should really be using the Microsoft Graph API to do this. So what I've done is create a PowerShell Module (and I made it a one file script for those that are more comfortable with that format) that's a port of the EWS script above that is so popular. This script uses the ADAL library for Modern Authentication (which if you grab the library from the PowerShell gallery will come down with the module). Most EWS properties map one to one with the Graph and the Graph actually provides better information on recurrences then...
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.