473,756 Members | 5,656 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 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>
Nov 17 '05 #1
0 2022

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

Similar topics

0
4662
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 Outlook 2000 installed. Upgraded to ASP running on IIS6, Outlook 2000 and SQL 2000 on Windows 2003. Server2 runs windows 2003 with Exchange 2003 using CDO 1.2 MAPI Sessions. Clients use IE5/6 and have Outlook 2000/2003 installed.
0
1231
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 of the contacts are also in the SQL Db and when we get a new client, information is often entered in both places. What I would like to figure out how to do, hopefully via ASP is create a
0
1172
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 way to see all the contacts? Thanks in advance for any suggestions. John
0
1155
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 the Exchange conduit the resulting table contains only 369 records, and many of them are duplicates except for the business fax number. I can't see any pattern to the omitted contact records. Is there something I should be doing to get them all...
1
3562
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 programming with C# (and DotNet in general) than 2000? If so i will wait a bit longer. thanks for any insights. Arran
0
1296
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 on an Exchange Server) as our CRM tool. I need to know, using ASP.NET, if I can access everyone's contacts, calendars, etc. with ASP.NET and then place all this data into SQL Server for reuse. I understand that I will need a daemon to sync the...
4
3516
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 click a button on a pop-up window the javascript for that button click does a 'button.form.submit'. On the Server side there is a Button click event for this button, but for some reason it no longer fires. It worked fine before and everything...
11
2839
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 their associated details from what is stored in Exchnage on a custom form inside a winforms application.
0
1587
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 outlook() and am able to link to the contacts data base. However, when I run my application locally, I get the error: No MAPI clients installed on this machine. Install a MAPI client such as Outlook. Well, Outlook is installed on the local machine but...
0
9454
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10028
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9868
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9836
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9707
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6533
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5301
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3804
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.