473,401 Members | 2,127 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,401 software developers and data experts.

Code: Viewing Exchange Contacts in ASP.NET

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
0 1991

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Nitec Dev | last post by:
Our setup: server1 ASP database running on IIS5, Outlook 2000 and SQL 2000 on Windows 2000. Server2 runs Windows 2000 with Exchange 2000 using CDO 1.2 MAPI Sessions. Clients use IE5/6 and had...
0
by: Richard Morey | last post by:
Hi, Our company currently has a SQL Server 2000 database with various client information, accessed through an ASP driven intranet. We also use Exchange 2000 and a shared contacts folder. Many...
0
by: John | last post by:
I have a linked table in Access to an Exhange Server Contacts Folder. The problem I am having is that only the Contacts that have a valid email (SMTP, EX or FAX) show up in the table. Is there a...
0
by: mky98767 | last post by:
I'm trying to link an MS Outlook 2003 contacts table in an Exchange mailbox to an MS Access 2003 table. I have 436 contact records in the contacts folder but when I run the link table wizard using...
1
by: Arran Pearce | last post by:
I am wanting to create a web application which will use Microsoft Exchange Server. We currently use Exchange 2000 but if i needed it we would upgrade to 2003. Is 2003 going to provide easyer...
0
by: mmondok | last post by:
Here is my scenario: I am currently developing a CRM-Transaction Management app for my company. The entire application must be run through a browser window. My boss wants to use Outlook (based...
4
by: John Boy | last post by:
Hi, Can anyone help. This is really doing my nut in. 3 years ASP exp. and now doing .DOT which is a step in the wrong direction. Basically I am left with the code of a guy who has left. When I...
11
by: ML | last post by:
What is th best/easiest way to access a public contacts folder on an Exchange server from a winforms vb.net applciation? I would like to be able to provide the user with a list of contacts and...
0
by: NissanSE98 | last post by:
Hello, I'm building an asp.net application that will get contact information from an Access Database that is linked to microsoft exchange or outlook. I go to link tables in Access and choose...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.