By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,738 Members | 1,493 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,738 IT Pros & Developers. It's quick & easy.

Code: Viewing Exchange Contacts in ASP.NET

P: n/a
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 DisplayExchangeContacts
private void DisplayExchangeContacts()
{
StringBuilder sbErr = new StringBuilder();

// Create Resource URL
string sSourceURL = "";
sSourceURL = String.Concat(@"/contacts/?Cmd=contents", sSourceURL);
sSourceURL = String.Concat(Session["UserLogin"].ToString(), sSourceURL);
sSourceURL =
String.Concat(ConfigurationSettings.AppSettings["ExchangeServerURL"].ToStrin
g(), sSourceURL);

// Create a DataView for the Contacts
DataView dvContacts;

try
{
// Fetch the WebDAV Contacts Xml
string sXmlData = FetchContactsXml(sSourceURL);
// Extract Xml into DataView
dvContacts = CreateDataViewfromXml(sXmlData);

// Check Row Count
if (dvContacts.Count > 0)
{
// Bind the DataGrid to the DataView
dvContacts.Sort = SortExpression;
dgContacts.DataSource = dvContacts;
dgContacts.DataBind();

sbErr.Append("The following is a list of your Outlook Contacts. Total:
<b>");
sbErr.Append(dvContacts.Count);
sbErr.Append("</b>");
}
else
{
sbErr.Append("There are no Outlook Contacts to display");
}

descriptive.InnerHtml = sbErr.ToString();
}
catch (Exception oException)
{
ExceptionManager.Publish(oException);
throw(oException);
}
}
#endregion

#region CreateCredentialCache
private CredentialCache CreateCredentialCache(string sSourceURL)
{
try
{
CredentialCache oCredentialCache = new CredentialCache();
oCredentialCache.Add(
new System.Uri(sSourceURL),
"NTLM",
new NetworkCredential(
ConfigurationSettings.AppSettings["ExchangeAdminAccount"].ToString(),

@ConfigurationSettings.AppSettings["ExchangeAdminAccountPwd"].ToString(),
ConfigurationSettings.AppSettings["DomainName"].ToString()));

return oCredentialCache;
}
catch (Exception oException)
{
ExceptionManager.Publish(oException);
throw(oException);
}
}
#endregion

#region FetchContactsXml
private string FetchContactsXml(string sSourceURL)
{
StringBuilder sbPayload = new StringBuilder();
sbPayload.Append("<?xml version=\"1.0\"?>");
sbPayload.Append("<a:searchrequest xmlns:a=\"DAV:\">");
sbPayload.Append("<sql> SELECT \"urn:schemas:contacts:fileas\" ");
sbPayload.Append(", \"urn:schemas:contacts:givenName\" ");
sbPayload.Append(", \"urn:schemas:contacts:sn\" ");
sbPayload.Append("FROM Scope('SHALLOW TRAVERSAL OF \"\"') ");
sbPayload.Append("Where \"DAV:isfolder\" = false AND \"DAV:contentclass\"
");
sbPayload.Append("= 'urn:content-classes:person'");
sbPayload.Append(" ORDER BY \"urn:schemas:contacts:fileas\" ASC");
sbPayload.Append("</>");
sbPayload.Append("</>");

// Array to hold Xml Payload
byte[] arPayload = null;

try
{
// Get Payload and Encode it to utf-8
arPayload = Encoding.UTF8.GetBytes((string)sbPayload.ToString( ));

// Create HTTP Web Request & Set Properties
HttpWebRequest oWebRequest =
(System.Net.HttpWebRequest)HttpWebRequest.Create(s SourceURL);
oWebRequest.Method = "SEARCH";
oWebRequest.ContentType = "text/xml";
oWebRequest.ContentLength = arPayload.Length;

// Inject the Search Payload into the RequestStream
Stream oRequestStream = oWebRequest.GetRequestStream();
oRequestStream.Write(arPayload, 0, arPayload.Length);
oRequestStream.Close();

// Set Credentials to Access Exchange Store
oWebRequest.Credentials = CreateCredentialCache(sSourceURL);

// Create the Web Response Object
System.Net.WebResponse oWebResponse = (System.Net.WebResponse)
oWebRequest.GetResponse();
// Get the Xml Response Stream
Stream oStream = oWebResponse.GetResponseStream();
// utf-8 handle it
Encoding oEncoding = System.Text.Encoding.GetEncoding("utf-8");
StreamReader oStreamReader = new StreamReader(oStream, oEncoding);
// Get the WebDAV Xml into a string
string sXmlData = oStreamReader.ReadToEnd();

// Clean Up
oStreamReader.Close();
oStream.Close();
oWebResponse.Close();

// Return the Xml string
return sXmlData;
}
catch (Exception oException)
{
ExceptionManager.Publish(oException);
throw(oException);
}
}
#endregion

#region CreateDataViewfromXml
private DataView CreateDataViewfromXml(string sXmlData)
{
XmlNodeList oXmlNodeListHref;
XmlNodeList oXmlNodeListDisplayName;
XmlNodeList oXmlNodeListFirstName;
XmlNodeList oXmlNodeListLastName;

XmlNode oXmlNodeHref;
XmlNode oXmlNodeDisplayName;
XmlNode oXmlNodeFirstName;
XmlNode oXmlNodeLastName;

try
{
// Load XML into an XmlDataDocument
XmlDataDocument oXmlDataDocument = new XmlDataDocument();
oXmlDataDocument.LoadXml(sXmlData);

// Get the Node Lists
oXmlNodeListHref = oXmlDataDocument.GetElementsByTagName("a:href");
oXmlNodeListDisplayName =
oXmlDataDocument.GetElementsByTagName("d:fileas");
oXmlNodeListFirstName =
oXmlDataDocument.GetElementsByTagName("d:givenName ");
oXmlNodeListLastName = oXmlDataDocument.GetElementsByTagName("d:sn");

// Create the DataTable
DataTable dtContacts = new DataTable();
DataRow drContact;

// Add Columns to the DataTable
dtContacts.Columns.Add(new DataColumn("ContactName", typeof(string)));
dtContacts.Columns.Add(new DataColumn("Href", typeof(string)));
dtContacts.Columns.Add(new DataColumn("FirstName", typeof(string)));
dtContacts.Columns.Add(new DataColumn("LastName", typeof(string)));

// Loop Variables
int i,j,k;

for (i=0, j=0, k=0; i<oXmlNodeListHref.Count; i++, j++, k++)
{
oXmlNodeHref = oXmlNodeListHref.Item(i);
oXmlNodeDisplayName = oXmlNodeListDisplayName.Item(j);
oXmlNodeFirstName = oXmlNodeListFirstName.Item(k);
oXmlNodeLastName = oXmlNodeListLastName.Item(l);

// Create New DataRow
drContact = dtContacts.NewRow();

// Check for Missing Display Name
if (oXmlNodeDisplayName.InnerText.Trim() != string.Empty)
{
drContact[0] = oXmlNodeDisplayName.InnerText;
drContact[1] = oXmlNodeHref.InnerText;
drContact[2] = oXmlNodeFirstName.InnerText;
drContact[3] = oXmlNodeLastName.InnerText;
}

// Add new DataRow to DataTable
dtContacts.Rows.Add(drContact);
}

// Return the DataView
DataView dvContacts = new DataView(dtContacts);
return dvContacts;
}
catch (Exception oException)
{
ExceptionManager.Publish(oException);
throw(oException);
}
}
#endregion

Here's the DataGrid on the front end

<asp:datagrid id="dgContacts" runat="server" BorderColor="#CCCCCC"
BorderStyle="None" BorderWidth="1px"
BackColor="White" CellPadding="4" GridLines="Horizontal"
CssClass="datagridSCM" AutoGenerateColumns="False"
Width="95%" PageSize="15">
<SelectedItemStyle CssClass="selecteditemstyle"></SelectedItemStyle>
<HeaderStyle CssClass="headerstyle"></HeaderStyle>
<FooterStyle CssClass="footerstyle"></FooterStyle>
<Columns>
<asp:TemplateColumn HeaderText="Contact Name" ItemStyle-Width="90%"
SortExpression="ContactName">
<ItemTemplate>
<asp:hyperlink Text='<%# DataBinder.Eval(Container,
"DataItem.ContactName") %>' NavigateUrl='<%# "exch_contact_import.aspx?URL="
+ DataBinder.Eval(Container, "DataItem.Href") %>' runat="server" >
</asp:hyperlink>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle Position="TopAndBottom" CssClass="pagerstyle"></PagerStyle>
</asp:datagrid>
Nov 17 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.