HI WELCOME TO SIRIS

Create iCal ics Files in C# ASP.NET MVC – Several Methods

Leave a Comment
Creating an iCal (ics file) is really simple. In this post I will show you how to create one using iCal.NET library and one using plain ol StringBuilder.
First of all, this is the basic format for an iCal
  1. BEGIN:VCALENDAR
  2. PRODID:-//LEEDS MUSIC SCENE//EN
  3. VERSION:2.0
  4. METHOD:PUBLISH
  5. BEGIN:VEVENT
  6. SUMMARY:BAND @ VENUE
  7. PRIORITY:0
  8. CATEGORIES:GIG
  9. CLASS:PUBLIC
  10. DTSTART:STARTTIME
  11. DTEND:ENDTIME
  12. URL:LINK TO LMS GIG PAGE
  13. DESCRIPTION:FULL BAND LIST
  14. LOCATION:VENUE
  15. END:VEVENT
  16. END:VCALENDAR
Source: This PasteBin
The calendar begins with the keyword BEGIN:VCALENDAR and ends with END:VCALENDAR. In between the calendar you can add as many events as you want beginning each event with BEGIN:VEVENT and ending with END:VEVENT.
There is a catch when adding multiple events to a calendar, and that is the type of METHOD you use. With METHOD:PUBLISH, you can add multiple events and upoin opening the iCal with MS Outlook it will create a new calendar, separate from your main Exchange calendar. METHOD:REQUEST creates a calendar invite, so you can only include one event and upon openning with MS Outlook it will ask you to accept the event and add it to your main Exchange calendar. With this method you have to include the orginizer (ORGANIZER;CN=Your Name:mailto:email@company.com)

Using iCal.NET

Download iCal.NET via nuget package then import the libraries to your class.
In the code below I create an email message and at the end I attach the iCal to the email message.
Everything else in the code below is pretty self-explanatory. You create a new calendar, loop thru a list of events, serialize the calendar, convert to bytes, put into a memory stream and finally attach it to the email message.
  1. using Ical.Net;
  2. using Ical.Net.DataTypes;
  3. using Ical.Net.Serialization.iCalendar.Serializers;
  4. using Ical.Net.Serialization;
  5. ...
  6. MailMessage message = new MailMessage();
  7. message.To.Add("johndoe@user.com");
  8. message.From = new MailAddress("info@company.com", "Company, Inc");
  9. message.Subject = "subject";
  10. message.Body = "emailbody";
  11. message.IsBodyHtml = true;
  12. ...
  13. var calendar = new Ical.Net.Calendar();
  14. foreach (var res in reg.Reservations) {
  15. calendar.Events.Add(new Event {
  16. Class = "PUBLIC",
  17. Summary = res.Summary,
  18. Created = new CalDateTime(DateTime.Now),
  19. Description = res.Details,
  20. Start = new CalDateTime(Convert.ToDateTime(res.BeginDate)),
  21. End = new CalDateTime(Convert.ToDateTime(res.EndDate)),
  22. Sequence = 0,
  23. Uid = Guid.NewGuid().ToString(),
  24. Location = res.Location,
  25. });
  26. }
  27. var serializer = new CalendarSerializer(new SerializationContext());
  28. var serializedCalendar = serializer.SerializeToString(calendar);
  29. var bytesCalendar = Encoding.UTF8.GetBytes(serializedCalendar);
  30. MemoryStream ms = new MemoryStream(bytesCalendar);
  31. System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(ms, "event.ics", "text/calendar");
  32. message.Attachments.Add(attachment);
  33. ...
The output of the serializedCalendar calendar is similar to my sample string calendar at the top of the page.

Using StringBuilder

I like this approach better as you have more flexibility and not be bound by a library that may or may not have all of the iCal attributes implemented. Now, don’t get me wrong iCal.NET is a great library, but I prefer to write the string myself.
Just as the above method, here I create a mail message, then with the StringBuilder I begin the calendar, loop thru my list of events creating calendar events, then ending the calendar and finally attaching my calendar to the email message. Pretty simple.
If you notice, I have DESCRIPTION attribute commented out, this only accepts plain text and X-ALT-DESC;FMTTYPE=text/html accepts HTML. Note that I have only tested on MS Outlook, not sure if X-ALT-DESC will work with other applications.
  1. ...
  2. MailMessage message = new MailMessage();
  3. message.To.Add("johndoe@user.com");
  4. message.From = new MailAddress("info@company.com", "Company, Inc");
  5. message.Subject = "subject";
  6. message.Body = "emailbody";
  7. message.IsBodyHtml = true;
  8. ...
  9. StringBuilder sb = new StringBuilder();
  10. string DateFormat = "yyyyMMddTHHmmssZ";
  11. string now = DateTime.Now.ToUniversalTime().ToString(DateFormat);
  12. sb.AppendLine("BEGIN:VCALENDAR");
  13. sb.AppendLine("PRODID:-//Compnay Inc//Product Application//EN");
  14. sb.AppendLine("VERSION:2.0");
  15. sb.AppendLine("METHOD:PUBLISH");
  16. foreach (var res in reg.Reservations) {
  17. DateTime dtStart = Convert.ToDateTime(res.BeginDate);
  18. DateTime dtEnd = Convert.ToDateTime(res.EndDate);
  19. sb.AppendLine("BEGIN:VEVENT");
  20. sb.AppendLine("DTSTART:" + dtStart.ToUniversalTime().ToString(DateFormat));
  21. sb.AppendLine("DTEND:" + dtEnd.ToUniversalTime().ToString(DateFormat));
  22. sb.AppendLine("DTSTAMP:" + now);
  23. sb.AppendLine("UID:" + Guid.NewGuid());
  24. sb.AppendLine("CREATED:" + now);
  25. sb.AppendLine("X-ALT-DESC;FMTTYPE=text/html:" + res.DetailsHTML);
  26. //sb.AppendLine("DESCRIPTION:" + res.Details);
  27. sb.AppendLine("LAST-MODIFIED:" + now);
  28. sb.AppendLine("LOCATION:" + res.Location);
  29. sb.AppendLine("SEQUENCE:0");
  30. sb.AppendLine("STATUS:CONFIRMED");
  31. sb.AppendLine("SUMMARY:" + res.Summary);
  32. sb.AppendLine("TRANSP:OPAQUE");
  33. sb.AppendLine("END:VEVENT");
  34. }
  35. sb.AppendLine("END:VCALENDAR");
  36. var calendarBytes = Encoding.UTF8.GetBytes(sb.ToString());
  37. MemoryStream ms = new MemoryStream(calendarBytes);
  38. System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(ms, "event.ics", "text/calendar");
  39. message.Attachments.Add(attachment);
  40. ...

Bonus

If you are planning to create calendars from multiple classses, it would be beneficial to create a class or method to help you with this. Below is the current approach that I am taking.
One thing to note is that here, unlike in my above examples, I am using METHOD:REQUEST and creating multiple calendars invites for multiple events so that when the end user opens the calendar invite it will get added to their main Exchange calendar, also creating an alarm for each invite.
Create an iCalendar class that will hold the calendar properties.
iCalendar.cs
  1. namespace Program
  2. {
  3. public class iCalendar
  4. {
  5. public DateTime EventStartDateTime { get; set; }
  6. public DateTime EventEndDateTime { get; set; }
  7. public DateTime EventTimeStamp { get; set; }
  8. public DateTime EventCreatedDateTime { get; set; }
  9. public DateTime EventLastModifiedTimeStamp { get; set; }
  10. public string UID { get; set; }
  11. public string EventDescription { get; set; }
  12. public string EventLocation { get; set; }
  13. public string EventSummary { get; set; }
  14. public string AlarmTrigger { get; set; }
  15. public string AlarmRepeat { get; set; }
  16. public string AlarmDuration { get; set; }
  17. public string AlarmDescription { get; set; }
  18. public iCalendar() {
  19. EventTimeStamp = DateTime.Now;
  20. EventCreatedDateTime = EventTimeStamp;
  21. EventLastModifiedTimeStamp = EventTimeStamp;
  22. }
  23. }
  24. }
Create a method or class
This class or method will give you a list of strings containing the calendar invites.
In my case I chose to create a public method in a separate class that holds “common tasks” shared accross my application, this method will receive a list of calendar objects (remember the iCalendarclass I created above??) and return a list calendar strings.
  1. public static List<string> iCals(List<iCalendar> iCals) {
  2. List<string> calendars = new List<string>();
  3. foreach(iCalendar iCal in iCals) {
  4. StringBuilder sb = new StringBuilder();
  5. //Calendar
  6. sb.AppendLine("BEGIN:VCALENDAR");
  7. sb.AppendLine("PRODID:-//Compnay Inc//Product Application//EN");
  8. sb.AppendLine("VERSION:2.0");
  9. sb.AppendLine("METHOD:REQUEST");
  10. //Event
  11. sb.AppendLine("BEGIN:VEVENT");
  12. sb.AppendLine("DTSTART:" + toUniversalTime(iCal.EventStartDateTime));
  13. sb.AppendLine("DTEND:" + toUniversalTime(iCal.EventEndDateTime));
  14. sb.AppendLine("DTSTAMP:" + toUniversalTime(iCal.EventTimeStamp));
  15. sb.AppendLine("ORGANIZER;CN=John Doe:mailto:johndoe@company.com");
  16. sb.AppendLine("UID:" + iCal.UID);
  17. //sb.AppendLine("ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=marydoe@company.com;X-NUM-GUESTS=0:mailto:marydoe@company.com");
  18. sb.AppendLine("CREATED:" + toUniversalTime(iCal.EventCreatedDateTime));
  19. sb.AppendLine("X-ALT-DESC;FMTTYPE=text/html:" + iCal.EventDescription);
  20. sb.AppendLine("LAST-MODIFIED:" + toUniversalTime(iCal.EventLastModifiedTimeStamp));
  21. sb.AppendLine("LOCATION:" + iCal.EventLocation);
  22. sb.AppendLine("SEQUENCE:0");
  23. sb.AppendLine("STATUS:CONFIRMED");
  24. sb.AppendLine("SUMMARY:" + iCal.EventSummary);
  25. sb.AppendLine("TRANSP:OPAQUE");
  26. //Alarm
  27. sb.AppendLine("BEGIN:VALARM");
  28. sb.AppendLine("TRIGGER:" + String.Format("-PT{0}M", iCal.AlarmTrigger));
  29. sb.AppendLine("REPEAT:" + iCal.AlarmRepeat);
  30. sb.AppendLine("DURATION:" + String.Format("PT{0}M", iCal.AlarmDuration));
  31. sb.AppendLine("ACTION:DISPLAY");
  32. sb.AppendLine("DESCRIPTION:" + iCal.AlarmDescription);
  33. sb.AppendLine("END:VALARM");
  34. sb.AppendLine("END:VEVENT");
  35. sb.AppendLine("END:VCALENDAR");
  36. calendars.Add(sb.ToString());
  37. }
  38. return calendars;
  39. }
  40. public static string toUniversalTime(DateTime dt) {
  41. string DateFormat = "yyyyMMddTHHmmssZ";
  42. return dt.ToUniversalTime().ToString(DateFormat);
  43. }
Finally call everything and create the calendars
Loop thru the list of events creating a separate calendar invite and attaching them to the email message.
  1. ...
  2. MailMessage message = new MailMessage();
  3. message.To.Add("johndoe@user.com");
  4. message.From = new MailAddress("info@company.com", "Company, Inc");
  5. message.Subject = "subject";
  6. message.Body = "emailbody";
  7. message.IsBodyHtml = true;
  8. ...
  9. List<iCalendar> iCals = new List<iCalendar>();
  10. foreach (var res in reg.Reservations) {
  11. iCals.Add(new iCalendar {
  12. EventStartDateTime = Convert.ToDateTime(res.BeginDate),
  13. EventEndDateTime = Convert.ToDateTime(res.EndDate),
  14. UID = Guid.NewGuid().ToString(),
  15. EventDescription = res.DetailsHTML,
  16. EventLocation = res.Location,
  17. EventSummary = res.Summary,
  18. AlarmTrigger = "30",
  19. AlarmRepeat = "2",
  20. AlarmDuration = "15",
  21. AlarmDescription = res.Details
  22. });
  23. }
  24. List<string> calendars = Common.iCals(iCals);
  25. int i = 1;
  26. foreach (string iCal in calendars) {
  27. var calendarBytes = Encoding.UTF8.GetBytes(iCal);
  28. MemoryStream ms = new MemoryStream(calendarBytes);
  29. System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(ms, String.Format("invite{0}.ics", i), "text/calendar");
  30. message.Attachments.Add(attachment);
  31. i++;
  32. }
  33. ...

Downloading the iCal

If you are not attaching the iCal to an email, instead you are making it available as a download, below is the partial code
  1. public ActionResult DownloadiCal(...)
  2. {
  3. //Create the calendar
  4. ...
  5. byte[] calendarBytes = System.Text.Encoding.UTF8.GetBytes(iCal); //iCal is the calendar string
  6. return File(calendarBytes, "text/calendar", "event.ics");
  7. }
Share if you liked this little tutorial!
https://www.kanzaki.com/docs/ical/

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.