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 ASP.net and ADO.net 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 asp.net 2.0 looks like it’s a great leap forward). For my code though I only had ASP.net 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.PropertiesToLoad.Add("mail")
objsearch.PropertiesToLoad.Add("msExchHomeServerName")
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
Next
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"" , ""http://schemas.microsoft.com/mapi/proptag/x003D001E"", " & _
" ""http://schemas.microsoft.com/mapi/proptag/x0070001E"" FROM """ & strRootURI & """" & _
"WHERE ""DAV:ishidden"" = false AND ""DAV:isfolder"" = false AND ""DAV:contentclass"" = 'urn:content-classes:message'" & _
"
"
Request = CType(System.Net.WebRequest.Create(strRootURI), _
System.Net.HttpWebRequest)
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)
RequestStream.Close()
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
ResponseXmlDoc.Load(ResponseStream)
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
resultstable.Columns.Add("href")
resultstable.Columns.Add("fromname")
resultstable.Columns.Add("subject")
resultstable.Columns.Add("x0070001E")
resultstable.Columns.Add("x003D001E")
resultstable.Columns.Add("Daterecieved")
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)
Next
End If
ResDsSet.Tables.Add(resultstable)
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)
ResDsSet.Relations.Add(grprelations)
Dim fldView As DataView = New DataView(ResDsSet.Tables("queryres"), "x003D001E = ''", "", DataViewRowState.CurrentRows)
Dim mailView As DataView
ConversationRepeater.DataSource = fldView
ConversationRepeater.DataBind()



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
row=resultstable.NewRow()
row("href")=href
row("fromname")=FromName
row("Subject")=Subject
row("x0070001E")=x0070001E
row("x003D001E")=x003D001E
Dim Daterecieved1 As System.DateTime
Daterecieved1 = CDate(Daterecieved)
row("Daterecieved")=Daterecieved1.ToShortDateString & " " & Daterecieved1.ToShortTimeString
resultstable.Rows.Add(row)
End Sub

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

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 https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . 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

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th
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.