Skip to main content

Displaying a collapsible conversation view of messages within in a folder using ASP.Net

I’ve been playing around with displaying message conversations in a group by format similar to what you can do with Outlook customized views. The and stuff is certainly a lot more accommodating when you are trying to do this vs ADO and ASP classic. Although they still have a little way to go with displaying hierarchal data. (that said the 2.0 looks like it’s a great leap forward). For my code though I only had 1.1 so I had to make do with what there is.

As a base for this code I used the stuff I posted here and added in some other fields to retrieve to allow me to start to group by conversation. The main fields I’ve used to do the group by are the PR_Conversation_topic x0070001E and PR_Subject_prefix x003D001E. Basically I used the prefix fields to work out if a mail in the queryied folder was the first mail in a conversation (eg any response will have a prefix the first message won’t). And the PR_Conversation_topic was used to relate the emails together.

A quick run though of the flow of the page is that it makes a WebDAV request for the last 1000 items in the target folder. The number of items retrieved is controlled via the range header. Request.AddRange("rows", 0,1000)

Once the request is received it populates an ADO dataset with all the props I started out using readxml but it didn’t work so well when parsing date-time datatypes. I think speed wise there’s not much advantage anyway. I’ve also added an auto-number field to the record-set so I could use it to create reference id’s in some of the div's I’ve used on the page.

The next part of the code creates a self-referencing relation on the datatable that joins the Subject to the PR_Conversation_topic. The next part of the code then creates a view that filters the records so you only see the initial conversation starting email (eg anything that hasn’t got a Subject prefix). This view is then bound to an ASP data repeater.

The displaying of the data is where some of the tricks come in I’ve used two methods to display the data in a collapsible conversation view. The first is to display the data in a hierarchal format I’ve used nested repeaters. This article came in handy for working out how to use this sort of thing. To get it to display the child rows of the data from the dataview CreateChildView is used which retrieves the rows from the underlying table using the data relation but ignoring the view constraints I put on (which is pretty cool)

To create a collapsing view of the data when you click the subject of the message I used this method from the guysfromrolla . Because I wanted to display tabular data I added code to place the records in html tables. I’ve also added a field that will hyperlink to OWA if you want to see the content of the message.

This still needs a bit of work I’d like to paginate the results that come back and also include a row that shows when the last time someone sent an email in that conversation. This code works best in a folder where there are a lot of conversations for instance I’m using it to view data that is sent to a mailing list. The one thing I couldn’t do that outlook does is sort the data by last updated conversation I’m still thinking about this.

The data section of the code looks like this if you want to look at the whole thing I’ve put a downloadable copy here.

Public Class AcceptAllCertificatePolicy
Implements ICertificatePolicy
Public Overridable Function CheckValidationResult(ByVal srvPoint As ServicePoint, ByVal certificate As X509Certificate, ByVal request As WebRequest, ByVal problem As Integer) As Boolean Implements ICertificatePolicy.CheckValidationResult
Return True 'this accepts all certificates
End Function
End Class

Sub Page_Load(sender As Object, e As EventArgs)
System.Net.ServicePointManager.CertificatePolicy = New AcceptAllCertificatePolicy
Dim Request As System.Net.HttpWebRequest
Dim Response As System.Net.HttpWebResponse
Dim strRootURI As String
Dim strQuery As String
Dim bytes() As Byte
Dim workrow As System.Data.DataRow
Dim resrow As System.Data.DataRow
Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext
Dim currentWindowsIdentity As System.Security.Principal.WindowsIdentity
currentWindowsIdentity = CType(User.Identity, System.Security.Principal.WindowsIdentity)
impersonationContext = currentWindowsIdentity.Impersonate()
Dim MyCredentialCache As System.Net.CredentialCache
Dim resdataset As New System.Data.DataSet
Dim RequestStream As System.IO.Stream
Dim ResponseStream As System.IO.Stream
Dim ResponseXmlDoc As System.Xml.XmlDocument
Dim hrefNodes,SubjectNodes,FromnameNodes,x003D001ENodes,x0070001ENodes,datereceivedNodes As System.Xml.XmlNodeList
Dim objsearch As New System.DirectoryServices.DirectorySearcher
Dim strrootdse As String = objsearch.SearchRoot.Path
Dim objdirentry As New system.DirectoryServices.DirectoryEntry(strrootdse)
Dim objresult As system.DirectoryServices.SearchResult
Dim stremailaddress As String
Dim strhomeserver As String
Dim ResDsSet as DataSet = New DataSet
objsearch.Filter = "(&(&(&(& (mailnickname=*) (| (&(objectCategory=person)(objectClass=user)(|(homeMDB=*)" _
& "(msExchHomeServerName=*))) )))(objectCategory=user)(userPrincipalName=*)(mailNickname=" & System.Environment.UserName & ")))"
objsearch.SearchScope = DirectoryServices.SearchScope.Subtree
objsearch.Sort.Direction = DirectoryServices.SortDirection.Ascending
objsearch.Sort.PropertyName = "mail"
Dim colresults As DirectoryServices.SearchResultCollection = objsearch.FindAll()
For Each objresult In colresults
stremailaddress = objresult.GetDirectoryEntry().Properties("mail").Value
strhomeserver = objresult.GetDirectoryEntry().Properties("msExchHomeServerName").Value
Dim emailNameNodes As System.Xml.XmlNodeList
strhomeserver = Right(strhomeserver, Len(strhomeserver) - (InStr(strhomeserver, "cn=Servers/cn=") + 13))
strRootURI = "https://" & strhomeserver & "/exchange/" & stremailaddress & "/Inbox/"
strQuery = "" & _
"" & _
"SELECT ""urn:schemas:mailheader:subject"", ""urn:schemas:httpmail:fromname"", " & _
" ""urn:schemas:httpmail:datereceived"" , """", " & _
" """" FROM """ & strRootURI & """" & _
"WHERE ""DAV:ishidden"" = false AND ""DAV:isfolder"" = false AND ""DAV:contentclass"" = 'urn:content-classes:message'" & _
Request = CType(System.Net.WebRequest.Create(strRootURI), _
Request.Credentials = System.Net.CredentialCache.DefaultCredentials
Request.Method = "SEARCH"
bytes = System.Text.Encoding.UTF8.GetBytes(strQuery)
Request.ContentLength = bytes.Length
RequestStream = Request.GetRequestStream()
RequestStream.Write(bytes, 0, bytes.Length)
Request.ContentType = "text/xml"
Request.AddRange("rows", 0,1000)
Request.Headers.Add("Translate", "F")
Response = CType(Request.GetResponse(), System.Net.HttpWebResponse)
ResponseStream = Response.GetResponseStream()
ResponseXmlDoc = New System.Xml.XmlDocument
ResDsSet = New System.Data.DataSet
Dim resultstable As DataTable
resultstable=new DataTable()
resultstable.TableName = "queryres"
Dim autoid As Data.DataColumn
autoid = resultstable.Columns.Add("autoid", GetType(Int32))
autoid.AutoIncrement = True
autoid.AutoIncrementSeed = 1
autoid.AutoIncrementStep = 1
hrefNodes = ResponseXmlDoc.GetElementsByTagName("a:href")
SubjectNodes = ResponseXmlDoc.GetElementsByTagName("d:subject")
FromnameNodes = ResponseXmlDoc.GetElementsByTagName("e:fromname")
x003D001ENodes = ResponseXmlDoc.GetElementsByTagName("f:x003D001E")
x0070001ENodes = ResponseXmlDoc.GetElementsByTagName("f:x0070001E")
datereceivedNodes = ResponseXmlDoc.GetElementsByTagName("e:datereceived")
If SubjectNodes.Count > 0 Then
Dim i As Integer
For i = 0 To datereceivedNodes.Count - 1
AddRow(resultstable, hrefNodes(i).InnerText, FromnameNodes(i).InnerText, SubjectNodes(i).InnerText,x0070001ENodes(i).InnerText,x003D001ENodes(i).InnerText,datereceivedNodes(i).InnerText)
End If
Dim relcol1, relcol2 As Data.DataColumn
relcol1 = ResDsSet.Tables("queryres").Columns("subject")
relcol2 = ResDsSet.Tables("queryres").Columns("x0070001E")
Dim grprelations As Data.DataRelation
grprelations = New Data.DataRelation("GroupEmails", relcol1, relcol2, False)
Dim fldView As DataView = New DataView(ResDsSet.Tables("queryres"), "x003D001E = ''", "", DataViewRowState.CurrentRows)
Dim mailView As DataView
ConversationRepeater.DataSource = fldView

End Sub

Sub AddRow(resultstable As DataTable,href as string, FromName As String, Subject As String, x0070001E as string,x003D001E as string, Daterecieved as string )
Dim row As DataRow
Dim Daterecieved1 As System.DateTime
Daterecieved1 = CDate(Daterecieved)
row("Daterecieved")=Daterecieved1.ToShortDateString & " " & Daterecieved1.ToShortTimeString
End Sub

Popular posts from this blog

Export calendar Items to a CSV file using EWS and Powershell

Somebody asked about this last week and while I have a lot of EWS scripts that do access the Calendar I didn't have a simple example that just exported a list of the Calendar events with relevant information to a CSV file so here it is. I've talked on this one before in this howto  but when you query the calendar folder using EWS you need to use a CalendarView which will expand any recurring appointments in a calendar. There are some limits when you use a calendarview in that you can only return a maximum of 2 years of appointments at a time and paging will limit the max number of items to 1000 per call. So if you have a calendar with a very large number of appointments you need to break your query into small date time blocks. In this example script I'm just grabbing the next 7 days of appointments if you want to query a longer period you need to adjust the following lines (keeping in mind what I just mentioned) #Define Date to Query $StartDate = (Get-Date) $EndDate

Downloading a shared file from Onedrive for business using Powershell

I thought I'd quickly share this script I came up with to download a file that was shared using One Drive for Business (which is SharePoint under the covers) with Powershell. The following script takes a OneDrive for business URL which would look like This script is pretty simple it uses the SharePoint CSOM (Client side object Model) which it loads in the first line. It uses the URI object to separate the host and relative URL which the CSOM requires and also the SharePointOnlineCredentials object to handle the Office365 SharePoint online authentication. The following script is a function that take the OneDrive URL, Credentials for Office365 and path you want to download the file to and downloads the file. eg to run the script you would use something like ./spdownload.ps1 '

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 . 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 Graph is limited to a m
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.