21
11/10
Referrer Harvesting For ASP.NET
So I’m happy that I can now see who’s linking to my blog—whether they use PingBacks et cetera or not—which got me thinking that it’d be somewhat cool to do the same thing for my homepage, which is written in ASP.NET.
So here’s code that does exactly the same thing as the PHP code I posted in my last blog post, except with ASP.NET (and C#):
try { if (Request.UrlReferrer!=null) { Response.Write( "<div class=\"categorybox\">You were linked to here from <a href=\""+ Request.UrlReferrer.ToString()+ "\">here</a>.</div>" ); Boolean exists=false; using (System.IO.StreamReader read=new System.IO.StreamReader( new System.IO.FileStream( System.IO.Path.Combine( Server.MapPath(null), "referrerlist.txt" ), System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read, System.IO.FileShare.Read ) )) { String holdthis; while ((holdthis=read.ReadLine())!=null) { if (Request.UrlReferrer.Host==holdthis) { exists=true; break; } } } if (!exists) { using (System.IO.StreamWriter write=new System.IO.StreamWriter( new System.IO.FileStream( System.IO.Path.Combine( Server.MapPath(null), "referrerlist.txt" ), System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None ) )) { write.WriteLine(Request.UrlReferrer.Host); } System.Net.Mail.SmtpClient mail=new System.Net.Mail.SmtpClient("192.168.50.4",25); mail.Send( "noreply@rleahy.ca", "rleahy@rleahy.ca", "Your Website Has Been Linked To", "The domain "+ Request.UrlReferrer.Host+ " has started linking to your site from "+ Request.UrlReferrer.ToString()+ "." ); } } } catch { }
Since .NET’s SmtpClient doesn’t pull from a configuration file–unlike PHP’s mail, which pulls SMTP settings from php.ini—there are few more “fill in the blanks” as opposed to yesterday:
- Your SMTP server’s IP/hostname.
- Your SMTP server’s port.
- The from address for your server.
- The to address (just like the PHP script).
If you want to be a real keener—or if it just fits in with your application—you can replace these “blanks” with calls to ConfigurationManager.AppSettings and store all of that in your web.config file.
Other than that, just put it between <% and %> anywhere in your *.aspx file, and you’re set.
If your environment uses authentication or SSL for SMTP, read the SmtpClient documentation and adjust the mailer portion accordingly.
Afterthought: This is the first blog post I’ve made before midnight…what a night owl I am…



—so it doesn’t fuck with your WordPress or anything (unless my WordPress is fucked?).