Hey all,
I finally found the necessary resources in the Exchange 2003 SDK to "pull"
Contacts out of Exchange and display them on a WebForm. I have been trying
to do this forever, and couldn't until the Exchange 2003 SDK came out.
Here's the code. Hopefully someone else can find this useful.
#region DisplayExchange Contacts
private void DisplayExchange Contacts()
{
StringBuilder sbErr = new StringBuilder() ;
// Create Resource URL
string sSourceURL = "";
sSourceURL = String.Concat(@ "/contacts/?Cmd=contents", sSourceURL);
sSourceURL = String.Concat(S ession["UserLogin"].ToString(), sSourceURL);
sSourceURL =
String.Concat(C onfigurationSet tings.AppSettin gs["ExchangeServer URL"].ToStrin
g(), sSourceURL);
// Create a DataView for the Contacts
DataView dvContacts;
try
{
// Fetch the WebDAV Contacts Xml
string sXmlData = FetchContactsXm l(sSourceURL);
// Extract Xml into DataView
dvContacts = CreateDataViewf romXml(sXmlData );
// Check Row Count
if (dvContacts.Cou nt > 0)
{
// Bind the DataGrid to the DataView
dvContacts.Sort = SortExpression;
dgContacts.Data Source = dvContacts;
dgContacts.Data Bind();
sbErr.Append("T he following is a list of your Outlook Contacts. Total:
<b>");
sbErr.Append(dv Contacts.Count) ;
sbErr.Append("</b>");
}
else
{
sbErr.Append("T here are no Outlook Contacts to display");
}
descriptive.Inn erHtml = sbErr.ToString( );
}
catch (Exception oException)
{
ExceptionManage r.Publish(oExce ption);
throw(oExceptio n);
}
}
#endregion
#region CreateCredentia lCache
private CredentialCache CreateCredentia lCache(string sSourceURL)
{
try
{
CredentialCache oCredentialCach e = new CredentialCache ();
oCredentialCach e.Add(
new System.Uri(sSou rceURL),
"NTLM",
new NetworkCredenti al(
ConfigurationSe ttings.AppSetti ngs["ExchangeAdminA ccount"].ToString(),
@ConfigurationS ettings.AppSett ings["ExchangeAdminA ccountPwd"].ToString(),
ConfigurationSe ttings.AppSetti ngs["DomainName "].ToString()));
return oCredentialCach e;
}
catch (Exception oException)
{
ExceptionManage r.Publish(oExce ption);
throw(oExceptio n);
}
}
#endregion
#region FetchContactsXm l
private string FetchContactsXm l(string sSourceURL)
{
StringBuilder sbPayload = new StringBuilder() ;
sbPayload.Appen d("<?xml version=\"1.0\" ?>");
sbPayload.Appen d("<a:searchreq uest xmlns:a=\"DAV:\ ">");
sbPayload.Appen d("<sql> SELECT \"urn:schemas:c ontacts:fileas\ " ");
sbPayload.Appen d(", \"urn:schemas:c ontacts:givenNa me\" ");
sbPayload.Appen d(", \"urn:schemas:c ontacts:sn\" ");
sbPayload.Appen d("FROM Scope('SHALLOW TRAVERSAL OF \"\"') ");
sbPayload.Appen d("Where \"DAV:isfolder\ " = false AND \"DAV:contentcl ass\"
");
sbPayload.Appen d("= 'urn:content-classes:person' ");
sbPayload.Appen d(" ORDER BY \"urn:schemas:c ontacts:fileas\ " ASC");
sbPayload.Appen d("</>");
sbPayload.Appen d("</>");
// Array to hold Xml Payload
byte[] arPayload = null;
try
{
// Get Payload and Encode it to utf-8
arPayload = Encoding.UTF8.G etBytes((string )sbPayload.ToSt ring());
// Create HTTP Web Request & Set Properties
HttpWebRequest oWebRequest =
(System.Net.Htt pWebRequest)Htt pWebRequest.Cre ate(sSourceURL) ;
oWebRequest.Met hod = "SEARCH";
oWebRequest.Con tentType = "text/xml";
oWebRequest.Con tentLength = arPayload.Lengt h;
// Inject the Search Payload into the RequestStream
Stream oRequestStream = oWebRequest.Get RequestStream() ;
oRequestStream. Write(arPayload , 0, arPayload.Lengt h);
oRequestStream. Close();
// Set Credentials to Access Exchange Store
oWebRequest.Cre dentials = CreateCredentia lCache(sSourceU RL);
// Create the Web Response Object
System.Net.WebR esponse oWebResponse = (System.Net.Web Response)
oWebRequest.Get Response();
// Get the Xml Response Stream
Stream oStream = oWebResponse.Ge tResponseStream ();
// utf-8 handle it
Encoding oEncoding = System.Text.Enc oding.GetEncodi ng("utf-8");
StreamReader oStreamReader = new StreamReader(oS tream, oEncoding);
// Get the WebDAV Xml into a string
string sXmlData = oStreamReader.R eadToEnd();
// Clean Up
oStreamReader.C lose();
oStream.Close() ;
oWebResponse.Cl ose();
// Return the Xml string
return sXmlData;
}
catch (Exception oException)
{
ExceptionManage r.Publish(oExce ption);
throw(oExceptio n);
}
}
#endregion
#region CreateDataViewf romXml
private DataView CreateDataViewf romXml(string sXmlData)
{
XmlNodeList oXmlNodeListHre f;
XmlNodeList oXmlNodeListDis playName;
XmlNodeList oXmlNodeListFir stName;
XmlNodeList oXmlNodeListLas tName;
XmlNode oXmlNodeHref;
XmlNode oXmlNodeDisplay Name;
XmlNode oXmlNodeFirstNa me;
XmlNode oXmlNodeLastNam e;
try
{
// Load XML into an XmlDataDocument
XmlDataDocument oXmlDataDocumen t = new XmlDataDocument ();
oXmlDataDocumen t.LoadXml(sXmlD ata);
// Get the Node Lists
oXmlNodeListHre f = oXmlDataDocumen t.GetElementsBy TagName("a:href ");
oXmlNodeListDis playName =
oXmlDataDocumen t.GetElementsBy TagName("d:file as");
oXmlNodeListFir stName =
oXmlDataDocumen t.GetElementsBy TagName("d:give nName");
oXmlNodeListLas tName = oXmlDataDocumen t.GetElementsBy TagName("d:sn") ;
// Create the DataTable
DataTable dtContacts = new DataTable();
DataRow drContact;
// Add Columns to the DataTable
dtContacts.Colu mns.Add(new DataColumn("Con tactName", typeof(string)) );
dtContacts.Colu mns.Add(new DataColumn("Hre f", typeof(string)) );
dtContacts.Colu mns.Add(new DataColumn("Fir stName", typeof(string)) );
dtContacts.Colu mns.Add(new DataColumn("Las tName", typeof(string)) );
// Loop Variables
int i,j,k;
for (i=0, j=0, k=0; i<oXmlNodeListH ref.Count; i++, j++, k++)
{
oXmlNodeHref = oXmlNodeListHre f.Item(i);
oXmlNodeDisplay Name = oXmlNodeListDis playName.Item(j );
oXmlNodeFirstNa me = oXmlNodeListFir stName.Item(k);
oXmlNodeLastNam e = oXmlNodeListLas tName.Item(l);
// Create New DataRow
drContact = dtContacts.NewR ow();
// Check for Missing Display Name
if (oXmlNodeDispla yName.InnerText .Trim() != string.Empty)
{
drContact[0] = oXmlNodeDisplay Name.InnerText;
drContact[1] = oXmlNodeHref.In nerText;
drContact[2] = oXmlNodeFirstNa me.InnerText;
drContact[3] = oXmlNodeLastNam e.InnerText;
}
// Add new DataRow to DataTable
dtContacts.Rows .Add(drContact) ;
}
// Return the DataView
DataView dvContacts = new DataView(dtCont acts);
return dvContacts;
}
catch (Exception oException)
{
ExceptionManage r.Publish(oExce ption);
throw(oExceptio n);
}
}
#endregion
Here's the DataGrid on the front end
<asp:datagrid id="dgContacts " runat="server" BorderColor="#C CCCCC"
BorderStyle="No ne" BorderWidth="1p x"
BackColor="Whit e" CellPadding="4" GridLines="Hori zontal"
CssClass="datag ridSCM" AutoGenerateCol umns="False"
Width="95%" PageSize="15">
<SelectedItemSt yle CssClass="selec teditemstyle"></SelectedItemSty le>
<HeaderStyle CssClass="heade rstyle"></HeaderStyle>
<FooterStyle CssClass="foote rstyle"></FooterStyle>
<Columns>
<asp:TemplateCo lumn HeaderText="Con tact Name" ItemStyle-Width="90%"
SortExpression= "ContactNam e">
<ItemTemplate >
<asp:hyperlin k Text='<%# DataBinder.Eval (Container,
"DataItem.Conta ctName") %>' NavigateUrl='<% # "exch_contact_i mport.aspx?URL= "
+ DataBinder.Eval (Container, "DataItem.Href" ) %>' runat="server" >
</asp:hyperlink>
</ItemTemplate>
</asp:TemplateCol umn>
</Columns>
<PagerStyle Position="TopAn dBottom" CssClass="pager style"></PagerStyle>
</asp:datagrid>