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

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

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You need to authorize it in you tenant (eg build a small ap

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.