Create an ical file in ASP.NET MVC
I recently had to write some code that generates an ical file and sends it to the browser. I decided to utilize the awesomeness that is asp.net mvc and try it like that. Following the information I got from reading Stephen Walther’s blog entry on using MVC to generate files to download, I started by creating a MVC controller that processes the request.
Public Class ICalController Inherits Controller Private _sessionRepo As ISessionRepository Private _locationRepo As ILocationRepository Public Sub New(ByVal sessionRepo As ISessionRepository, _ ByVal locationRepo As ILocationRepository) _sessionRepo = sessionRepo _locationRepo = locationRepo End Sub Public Function SessionEvent(ByVal sessionID As Long) As ActionResult Dim s As SessionsEntity = _sessionRepo.GetSession(sessionID) Dim loc As LocationsEntity = _locationRepo.Get(s.LocationID) Return ICalEvent("session.ics", loc.CodeAndName, _ s.SessionName, s.SessionName, _ s.StartDateUTC, s.EndDateUTC) End Function End Class
I then created a custom ActionResult that creates the actual ical file. Not surprisingly I called it ICalEventResult. I created an DateTime extension method to format the utc dates into the correct format for the ical file (I won’t include it here).
Public Class ICalEventResult Inherits ActionResult Private _startUtc As DateTime Private _endUtc As DateTime Private _summary As String Private _description As String Private _location As String Private _fileName As String Public Sub New(ByVal startUtc As DateTime, ByVal endUtc As DateTime, _ ByVal summary As String, ByVal description As String, _ ByVal location As String, ByVal fileName As String) _startUtc = startUtc _endUtc = endUtc _summary = summary _description = description _location = location _fileName = fileName End Sub Public Overrides Sub ExecuteResult(ByVal context As System.Web.Mvc.ControllerContext) Dim str As New StringBuilder() With str .AppendLine("BEGIN:VCALENDAR") .AppendLine("VERSION:2.0") .AppendLine("BEGIN:VEVENT") .AppendLine(String.Format("DTSTART:{0}", _startUtc.ToUniversalTimeString)) .AppendLine(String.Format("DTEND:{0}", _endUtc.ToUniversalTimeString)) .AppendLine(String.Format("SUMMARY:{0}", _summary)) .AppendLine(String.Format("DESCRIPTION:{0}", _description)) .AppendLine(String.Format("LOCATION:{0}", _location)) .AppendLine("END:VEVENT") .AppendLine("END:VCALENDAR") End With context.HttpContext.Response.ContentType = "text/calendar" context.HttpContext.Response.AddHeader("Content-disposition", String.Format("attachment; filename={0}", _fileName)) context.HttpContext.Response.Write(str.ToString) context.HttpContext.Response.End() End Sub End Class
Finally I created a controller extension method called ICalEvent that simply returns an instance of the ICalEventResult.

