facebook  linkedin  Twitter  skype  Rss googlePlus

Creating an ASP.Net Trackback Handler

Jan 28 2004
5347

What are Trackbacks?

Trackbacks are taken from popular blogging applications that allow your site to be notified when someone links to a page contained on your site. Developed by MovableType.org for their publishing system. Trackbacks and pingbacks (another method for site notification using XML-RPC), are growing fast in their use, and in the .Net development community in applications like .Text weblogs.

Here is an outline of the trackback notification process:

  1. An external website is updated with a link to your site
  2. Some process in the external site is notified of the new link and sends a request to your site to see if the page being linked contains information on where to send a trackback notification.
  3. If the information is found, the external site contacts the trackback handler for your site to notify that a link has been added to the page.
  4. Your trackback handler then verifies the existence of the link in the page and adds an entry to your trackback table.

For WWWCoder.com we then add an entry in our comments table that is displayed in the article. This entry contains the title of the site and a link to the page that contains a link to the article.

For this example we will create a Trackback.aspx page for handling our trackback notifications. You could also opt to use an HTTPHandler for dealing with the trackbacks as well.

Create a Pointer to Your Trackback

The first thing you need to do for the trackback transaction is provide the external site with information about your trackback. This information is provided by embedding Resource Description Framework (RDF) information within the document. The RDF information is basically XML information about your trackback handler and the current document. For example:

You can see from the RDF information above that we provide a link to the current document, the URL of the trackback handler, and description information. This information will be used by the external site's trackback notifyer to provide information to our handler about the document they linked to. We will not provide a mechanism for generating this string, but you should be able to generate the string based on your specific application and then insert the information into the source HTML.

Create the Handler

Now we need something to handle the trackback request when it comes in. First we'll create an aspx page called Trackback.aspx. This page will receive the requests from the external site and respond to them.

Imports System
Imports System.Web
Imports System.Xml
 
Public Class Trackback
 
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'Put user code to initialize the page here
            Dim strBody As String
            Try
                Response.Clear()
                Response.ContentType = "text/xml"
                'now make sure they are referencing some article id.
                If Request.Params("id") <> "" Then
                    Dim title As String
                    Dim excerpt As String
                    Dim url As String
                    Dim blog_name As String
                    If Not Request.Params("title") Is Nothing Then
                        title = Request.Params("title").ToString
                    End If
                    If Not Request.Params("excerpt") Is Nothing Then
                        excerpt = Request.Params("excerpt").ToString
                    End If
                    If Not Request.Params("url") Is Nothing Then
                        Dim aurl As String()
                        'what comes back in the url field is an array with two elements:
                        'the first element is the requesting url of the external site,
                        'this is what we need in order to verify the link.
                        aurl = Split(Request.Params("url"), ",")
                        url = aurl(0)
                    End If
                    If Not Request.Params("blog_name") Is Nothing Then
                        blog_name = Request.Params("blog_name").ToString
                    End If
                    If Request.HttpMethod = "POST" Then
                        Dim id As String = CType(Request.Params("id"), Integer)
                        'since this is a dynamically generated article, we need the id of the page
                        'in order to generate a link to check.
                        Dim targetPage As String = GenerateLink(id)
                        If url.Length > 0 Then
                            'first make sure there is an article for this id.
                            'We'll make a call to another class.
                            Dim objBlogs As New MyNamespace.PingBackService
                            Dim tmpTitle As String = objBlogs.CheckforURL(url, targetPage, title)
                            If tmpTitle <> "0" Then
                                'create the comment
                                ::
                                ::
                            Else
                                TrackbackResponse(2, "Sorry couldn't find a " & _
                                   "relevant link for " & targetPage & " in " & url)
                            End If
                        End If
                    Else
                        Dim articleTitle As String
                        Dim articleURL As String
                        Dim w As XmlTextWriter = New XmlTextWriter(Response.Output)
                        w.Formatting = Formatting.Indented
                        w.WriteStartDocument()
                        w.WriteStartElement("response")
                        w.WriteElementString("error", "0")
                        w.WriteStartElement("rss")
                        w.WriteAttributeString("version", "0.91")
                        w.WriteStartElement("channel")
                        w.WriteElementString("title", articleTitle)
                        w.WriteElementString("link", articleURL)
                        w.WriteElementString("description", "")
                        w.WriteElementString("language", "en-us")
                        w.WriteEndElement()
                        w.WriteEndElement()
                        w.WriteEndElement()
                        w.WriteEndDocument()
                    End If
                Else
                    TrackbackResponse(1, "EntryID is invalid or missing")
                End If
            Catch ex As Exception
                'handle the error.
            End Try
        End Sub

You'll notice in the method above, we made a couple calls to outside methods:

GenerateLink - accepts an id of the primary key of the article in the database. This method will return a friendly URL of the dynamically generated article on our site. We will not cover this method in this article since systems may use various methods of generating links.

TrackbackResponse - This method returns XML text error messages to the site sending the trackback request.

Private Sub TrackbackResponse(ByVal errNum As Integer, ByVal errText As String)
        Dim strBody As String
        Try
            Dim d As New XmlDocument
            Dim root As XmlElement = d.CreateElement("response")
            d.AppendChild(root)
            Dim er As XmlElement = d.CreateElement("error")
            root.AppendChild(er)
            er.AppendChild(d.CreateTextNode(errNum.ToString))
            If errText <> "" Then
                Dim msg As XmlElement = d.CreateElement("message")
                root.AppendChild(msg)
                msg.AppendChild(d.CreateTextNode(errText))
            End If
            d.Save(Response.Output)
            Response.End()
        Catch ex As Exception
            
        End Try
    End Sub

CheckforURL - This method is contained in another class for handling the request to ensure that the external page contains a link to our page. Once this is verified, we then add the link back to the external page in our comments table. The method will obtain the page text for the external page, pull out the title of the page and check for the existence of the link in the page. If it does not return a link, it will then return a "0" string value.

Imports System
Imports System.Net
Imports System.Web
Imports System.IO
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Web.Services
::
::
     Public Class PingBackService
       Public Function CheckForURL(ByVal sURI As String, _
            ByVal tURI As String, ByVal pageTitle As String) As String
            Try
                Dim page As String = GetPageHTML(sURI)
                If (page.Trim = "") Or (page.IndexOf(tURI) < 0) Then
                    Return "0"
                Else
                    Dim pat As String = ".*(.*).*"
                    Dim reg As Regex = New Regex(pat, RegexOptions.IgnoreCase.Singleline)
                    Dim m As Match = reg.Match(page)
                    If m.Success Then
                        pageTitle = m.Result("$1")
                        Return pageTitle
                    End If
                End If
            Catch ex As Exception               
                Return "0"
            End Try
            Return pageTitle
        End Function
::
::

The CheckForURL method calls the GetPageHTML method to obtain the text information from the Web page using an HTTP request.

Public Function GetPageHTML(ByVal inURL As String) As String
        Dim req As WebRequest = WebRequest.Create(inURL)
        Dim Null As Object
        Dim wreq As HttpWebRequest = req
        If Not (wreq Is Null) Then
            wreq.UserAgent = "My User Agent String"
            wreq.Referer = "http://www.wwwcoder.com/"
            wreq.Timeout = 60000
        End If
        Dim response As HttpWebResponse = wreq.GetResponse
        Dim s As Stream = response.GetResponseStream
        Dim enc As String = response.ContentEncoding.Trim
        If enc = "" Then enc = "us-ascii"
        Dim encode As Encoding = System.Text.Encoding.GetEncoding(enc)
        Dim sr As StreamReader = New StreamReader(s, encode)
        Return sr.ReadToEnd
    End Function

Once the GetPageHTML returns the text back to our CheckForURLs method, the CheckForURL method will search the text for any existence of the link.

Some other things of note here, you may want to do some checking on the parameters that are sent to your handler to ensure that the data is corrected and safe for your application. In addition, if you generate static RSS 2.0 files that use the <slash:comments> element, you will need to regenerate your RSS file to display the updated trackback information and/or comments count.

About the Author, Patrick Santry

Patrick Santry, has two decades of experience in enabling businesses to take advantage of the digital landscape. A well rounded experience in technology, and business is what sets me apart from the rest of the pack. When it comes to an overall digital strategy my experience is impressive.

BS in Computer Information Systems. Four time recipient of the Microsoft MVP Award, and author of several books and magazine articles on digital technologies.


blog comments powered by Disqus

Latest Podcast

New Podcast: Apple, Disqus, and More!

 

Subscribe to Pat's Digital Podcast on iTunes! Latest Podcast

Listen to Pat's Podcast

 

Thank you for visiting our site, before you leave, please visit some of the areas or information you may have missed.