Monday, 8 October 2012

Send meeting requests to the outlook programmatically using iCal


1.       Suppose we have a calendar list in sharepoint site.
2.       On item adding event I want to send meeting requests to the user who created the meeting (event) and the attendees of the meeting (event) by attaching a event handler to it.
3.       Following is the code to which gets ical format to frame a meeting request and then use that ical while sending the request to the outlook. Pass the details needed to the send meeting request method by capturing them in item added event.
4.    It uses plain .net dlls and does not need any outlook dlls to deliver the meeting request to outlook.


using System;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Text.RegularExpressions;
using System.Collections;
using System.Net.Mail;
using System.Net.Mime;
using System.Collections.Generic;
using System.Configuration;

Method to send meeting request:


public void SendMeetingRequest(SPWeb web, string listName, int itemID, SPFieldUserValue organizerEmail, string title, MailAddressCollection macAttendeeList, SPFieldUserValueCollection attendees,string strSubject, string strSummary)
        {

  Guid siteID = web.Site.ID;

                MailMessage mmMessage = new MailMessage();

                ContentType typeCalendar = new ContentType("text/calendar");

                string icalData = string.Empty;
              
                    mmMessage.From = new MailAddress(organizerEmail.User.Email);

icalData = GetICSFormat(web, listName, itemID, organizerEmail.User.Email,organizerEmail.User.Name,macAttendeeList,attendees); // GetICSFormat Method defined below
               
                           
                typeCalendar.Parameters.Add("method", "REQUEST");

                typeCalendar.Parameters.Add("name", "meeting.ics");

              AlternateView viewCalendar = AlternateView.CreateAlternateViewFromString(icalData, typeCalendar);

            viewCalendar.TransferEncoding = TransferEncoding.SevenBit;

            mmMessage.AlternateViews.Add(viewCalendar);



                foreach (MailAddress attendee in macAttendeeList)
                {
                    mmMessage.To.Add(attendee);
                }

                mmMessage.Subject = strSubject;

                mmMessage.Body = strSummary;

            

                SmtpClient smtp = new SmtpClient(ConfigurationManager.AppSettings["SMTPServer"].ToString(), Convert.ToInt32(ConfigurationManager.AppSettings["Port"]));

               smtp.EnableSsl = true;

                smtp.UseDefaultCredentials = false;

                smtp.Credentials = new NetworkCredential("user id", "password");

                ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };


                if (macAttendeeList.Count > 0)
                {
                    smtp.Send(mmMessage);


                }
}

               
Method to generate iCal Format: 
public string GetICSFormat(SPWeb web, string listName, int itemID, string OrganizerEmail,string organizerDisplayname, MailAddressCollection MACollection,SPFieldUserValueCollection attendees)
        {

            StringBuilder str = new StringBuilder();

            SPList list = web.Lists[listName];

            if (list == null)
            {
                return string.Empty;
            }

str.Append("BEGIN:VCALENDAR\r\n");

str.Append("METHOD:REQUEST\r\n");

           
str.Append ("PRODID:Microsoft CDO for Microsoft Exchange\r\n");

str.Append ("VERSION:2.0\r\n");


            String tzid = "India Standard Time";

            str.Append ("BEGIN:VTIMEZONE");

            str.Append ("TZID:"+tzid);

            str.Append ("X-MICROSOFT-CDO-TZID:11");

           
            str.Append ("BEGIN:STANDARD");

            str.Append ("DTSTART:16010101T020000");

          

            str.Append ("TZOFFSETFROM:-0500");

           
            str.Append ("TZOFFSETTO:-0600");

           
            str.Append ("END:STANDARD");

            str.Append ("BEGIN:DAYLIGHT");

            str.Append ("DTSTART:16010101T020000");

           
            str.Append ("TZOFFSETFROM:-0600");


           
            str.Append ("TZOFFSETTO:-0500");

            str.Append ("END:DAYLIGHT");

            str.Append ("END:VTIMEZONE");



            Hashtable idToGuid = new Hashtable();

            SPListItem item = list.GetItemById(itemID);

            bool allDay = (bool)item["All Day Event"];

            bool recur = ((bool)item["Recurrence"]) && (((Int32)item["Event Type"]) == 1);

            bool exception = (((Int32)item["Event Type"]) == 4);

            bool deleted = (((Int32)item["Event Type"]) == 3);

            String guid = ((String)item["GUID"]).Trim(new char[] { '{', '}' });

            DateTime created = Convert.ToDateTime(item["Created"]);

            String url = currentWeb.Url + item.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].ServerRelativeUrl + "?ID=" + item.ID;

            DateTime start = Convert.ToDateTime(item["EventDate"]);

            DateTime end = Convert.ToDateTime(item["EndDate"]);

            String recurValue = null;

            if (deleted)
                return;

            if (recur)
            {
                str.Append ("type:"+ item["Event Type"]);

                String recurrence = ((String)item["RecurrenceData"]);

recurValue = ParseRecurrence(recurrence); // Parse Recurrence Method defined below

SPListItem rItem = GetFirstInstance(item); // GetFirstInstance Method defined below


                if (rItem == null)
                {
                    
                    recur = false;
                }
                else
                {
                    start = Convert.ToDateTime(rItem["EventDate"]);

                    end = start.AddSeconds((int)rItem["Duration"]);
                }
            }

                        str.Append ("BEGIN:VEVENT");


            // Created date
            str.Append ("DTSTAMP:"+created.ToUniversalTime().ToString("yyyyMMddTHHmmssZ"));


            // Start date (different format if all-day event)
            if (allDay)
            {
                str.Append ("DTSTART;VALUE=DATE:"+start.ToUniversalTime().ToString("yyyyMMdd"));
            }
            else
            {
                str.Append ("DTSTART:"+ start.ToUniversalTime().ToString("yyyyMMddTHHmmssZ"));
            }

            // Duration if we're an all-day event
            if (allDay)
            {
                // All-day events always end at :59, so we have to add one minute for this to work correctly
                str.Append ("DURATION:P" + ((TimeSpan)(end.AddMinutes(1) - start)).Days + "D");
            }


         
            // Time of the instance we replaced, if we're an exception
            if (exception)
            {
                str.Append ("RECURRENCE-ID;TZID=" + timeZone+ ":"+(Convert.ToDateTime(item["Recurrence ID"])).ToString("yyyyMMddTHHmmssZ"));
            }

            // Recurrence rule and deleted instances
            if (recur)
            {
                str.Append ("RRULE:"+recurValue);

                // Get all the deleted instances of this series
                ArrayList deletedInstances = GetDeletedInstancesOfSeries(item);

                // Loop through them
                foreach (SPListItem deletedInstance in deletedInstances)
                {
                    // Write out an exception rule for each one
                    str.Append ("EXDATE;TZID=" + timeZone+ ":" +(Convert.ToDateTime(deletedInstance["Recurrence ID"])).ToString("yyyyMMddTHHmmssZ"));
                }
            }
            // Title
            str.Append ("SUMMARY:"+Escape(item.Title));

            // Unique ID
            if (recur)
            {
                // Add the ID-to-GUID mapping for later, but only if it's a recurrence
                idToGuid.Add(item.ID, guid);
            }
            else if (exception)
            {
                // Replace this item's ID with the ID of the master series if it's an exception
                guid = (String)idToGuid[item["MasterSeriesItemID"]];
            }

            str.Append("UID:{"+ guid+"}\r\n");


            foreach (SPFieldUserValue MailAttendee in attendees)
            {
                if (!string.IsNullOrEmpty(MailAttendee.User.Email))
                {
                                        str.Append("ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=\"" + MailAttendee.User.Name + "\":MAILTO:" + MailAttendee.User.Email + "\r\n");

                    str.Append("ACTION;RSVP=TRUE;CN=\"" + MailAttendee.User.Name + "\":MAILTO:" + MailAttendee.User.Email + "\r\n");
                }
            }

            // Organizer
            str.Append("ORGANIZER;CN=\""+orgDisplayname+"\":MAILTO:"+OrganizerEmail+"\r\n");

         
            str.Append ("LOCATION:"+Escape(item["Meeting Location"]));


            // End date (only if not an all-day event)
            if (!allDay)
            {
                str.Append ("DTEND:"+end.ToUniversalTime().ToString("yyyyMMddTHHmmssZ"));
            }

          
            // Description
            str.Append("DESCRIPTION:"+ Escape(item.Fields["Meeting Subject"].GetFieldValueAsText(item["Meeting Subject"]))+"\\\\N\r\n");


            // Sequence (aka version)
            str.Append("SEQUENCE:1\r\n");

            str.Append ("PRIORITY:5\r\n");

            str.Append("CLASS:\r\n");

str.Append ("CREATED:"+created.ToString("yyyyMMddTHHmmssZ"));

str.Append ("LAST-MODIFIED:"+created.ToString("yyyyMMddTHHmmssZ"));

str.Append ("STATUS:CONFIRMED");

str.Append ("TRANSP:OPAQUE");

str.Append ("X-MICROSOFT-CDO-BUSYSTATUS:BUSY");

str.Append ("X-MICROSOFT-CDO-INSTTYPE:0");

str.Append ("X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY");

str.Append ("X-MICROSOFT-CDO-ALLDAYEVENT:FALSE");

str.Append ("X-MICROSOFT-CDO-IMPORTANCE:1");

str.Append ("X-MICROSOFT-CDO-OWNERAPPTID:-1");

str.Append ("X-MICROSOFT-CDO-ATTENDEE-CRITICAL-CHANGE:"+created.ToString("yyyyMMddTHHmmssZ"));

str.Append ("X-MICROSOFT-CDO-OWNER-CRITICAL-CHANGE:"+created.ToString("yyyyMMddTHHmmssZ"));

str.Append ("BEGIN:VALARM");

str.Append ("ACTION:DISPLAY");

str.Append ("DESCRIPTION:REMINDER");

str.Append ("TRIGGER;RELATED=STAR:-PT00H15M00S");

str.Append ("END:VALARM");

             str.Append ("END:VEVENT");

              str.Append ("END:VCALENDAR");

            return str.ToString();
        }



private SPListItem GetFirstInstance(SPListItem item)
        {
            DateTime itemStartDate = (DateTime)item["EventDate"];
            SPQuery query = new SPQuery();
            query.ExpandRecurrence = true;
            query.Query = "<Where><DateRangesOverlap><FieldRef Name=\"EventDate\" /><FieldRef Name=\"EndDate\" /><FieldRef Name=\"RecurrenceID\" /><Value Type=\"DateTime\"><Month /></Value></DateRangesOverlap></Where>";
            SPListItem i = null;
            int monthOffset = 0;
            SPListItemCollection allItems;

            // Look up to a little over a month ahead
            while (monthOffset < 14)
            {
                // Start from (start date + offset*30) and look ahead a month
                query.CalendarDate = ((DateTime)item["EventDate"]).AddMonths(monthOffset);

                // Get all the items
                allItems = item.ParentList.GetItems(query);

                // These items are sorted earliest to latest by start date
                foreach (SPListItem expandedItem in allItems)
                {
                    // Did we find an instance that matches our series ID?
                    if (expandedItem.ID == item.ID)
                    {
                        return expandedItem;
                    }
                }

                // If we didn't find anything, look in the next month
                monthOffset++;
            }

            // Return null if we looked all over and couldn't find anything.
            return null;
        }


  private String ParseRecurrence(String recurrence)
        {
            String recurValue;


            recurrence = recurrence.ToLower();


            Regex pattern = new Regex(@"<repeat><(?<FREQ>\w+)\s(?<OPTIONS>.*)/></repeat>");


            Match match = pattern.Match(recurrence);


            String freq = match.Groups["FREQ"].ToString().ToUpper();
            String options = match.Groups["OPTIONS"].ToString().ToLower();
            String byday = null;

            // Is there a weekly="true" flag in the options?
            if (freq.Equals("DAILY") && options.Contains(@"weekday=""true"""))
            {
                // There's no support for daily-weekday patterns in this format, so we have to do some mangling
                freq = "WEEKLY";
                byday = "MO,TU,WE,TH,FR";
            }

            // Put the frequency into the return value, but handle special cases for tricky month/year patterns
            if (freq.Equals("MONTHLYBYDAY"))
            {
                recurValue = "FREQ=MONTHLY";
            }
            else if (freq.Equals("YEARLYBYDAY"))
            {
                recurValue = "FREQ=YEARLY";
            }
            else
            {
                recurValue = "FREQ=" + freq;
            }

            // Build a regex to parse out the interval
            pattern = new Regex(@"(day|week|month|year)frequency=""(?<INTERVAL>\d+)""");

            // Match against the XML
            match = pattern.Match(options);

            // Pull out the interval
            String interval = match.Groups["INTERVAL"].ToString();

            // If we found an interval, add it to the recur pattern
            if (!interval.Equals(""))
            {
                recurValue = recurValue + ";INTERVAL=" + interval;
            }

            // Include the starting day of the week if we're a weekly pattern
            if (freq.Equals("WEEKLY"))
            {
                // Only set up the byday list if we didn't already mangle it to support weekday recurrences
                if (byday == null)
                {
                    // Initialize it so it's no longer null
                    byday = "";

                    // The list of day values we're going to scan for
                    String[] days = new String[] { "SU", "MO", "TU", "WE", "TH", "FR", "SA" };

                    foreach (String d in days)
                    {
                        // Is this day set in the recurrence options?
                        if (options.Contains(d.ToLower() + @"=""true"""))
                        {
                            // Add a comma if we're sticking our value on the end of an existing one
                            if (!byday.Equals(""))
                            {
                                byday = byday + ",";
                            }

                            // Add it to the list
                            byday = byday + d;
                        }
                    }
                }

                // Add the day pattern to the recur pattern
                recurValue = recurValue + ";BYDAY=" + byday;

                // Build a regex to parse out the first day of the week
                pattern = new Regex(@"<firstdayofweek>(?<FIRST>\w\w)</firstdayofweek>");

                // Match against the XML
                match = pattern.Match(recurrence);

                // Pull out the first day of the week
                String first = match.Groups["FIRST"].ToString().ToUpper();

                // Add it to the recur pattern
                recurValue = recurValue + ";WKST=" + first;
            }

            // Parse out monthly-specific options
            if (freq.Equals("MONTHLY"))
            {
                // Build a regex to parse out the day in a "every N months on the Nth" pattern
                pattern = new Regex(@"\sday=""(?<BYDAY>\d+)""");

                // Match against the pattern options XML
                match = pattern.Match(options);

                // Pull out the by day option
                String byDay = match.Groups["BYDAY"].ToString().ToUpper();

                // Add it to the recur pattern
                if (!byDay.Equals(""))
                {
                    recurValue = recurValue + ";BYMONTHDAY=" + byDay;
                }
            }

            // Parse out yearly-specific options
            if (freq.Equals("YEARLY"))
            {
                // Build a regex to parse out the month in a "every N (month) Nrd" pattern
                pattern = new Regex(@"\smonth=""(?<BYMONTH>\d+)""");

                // Match against the pattern options XML
                match = pattern.Match(options);

                // Pull out the by month option
                String byMonth = match.Groups["BYMONTH"].ToString().ToUpper();

                // Add it to the recur pattern
                if (!byMonth.Equals(""))
                {
                    recurValue = recurValue + ";BYMONTH=" + byMonth;
                }
            }

            // Parse out more complex monthly-and-yearly-specific options
            if (freq.Equals("MONTHLYBYDAY") || freq.Equals("YEARLYBYDAY"))
            {
                // Parse out the weekdayOfMonth property into an index we can use
                int i = GetWeekdayOfMonthValue(options);

                // Is this a yearly pattern?
                if (freq.Equals("YEARLYBYDAY"))
                {
                    // Yes, so parse out the month that it's supposed to occur in
                    pattern = new Regex(@"\smonth=""(?<MONTH>\d+)""");

                    // Match against the XML
                    match = pattern.Match(options);

                    // Pull out the number of occurrences
                    String monthIndex = match.Groups["MONTH"].ToString();

                    // Add it to the recurrence pattern
                    recurValue = recurValue + ";BYMONTH=" + monthIndex;
                }

                // Is this a "the Nth day" pattern?
                if (options.StartsWith(@"day=""true"""))
                {
                    recurValue = recurValue + ";BYMONTHDAY=" + i;
                }

                // Is this a "the Nth weekday" pattern?
                else if (options.Contains(@"weekday=""true"""))
                {
                    recurValue = recurValue + ";BYDAY=MO,TU,WE,TH,FR;BYSETPOS=" + i;
                }

                // Is this a "the Nth weekend day" pattern?
                // NOTE: this only works if the month doesn't start on a Sunday.  Since the
                // spec doesn't seem to support this pattern, I have to make it up.
                else if (options.Contains(@"weekend_day=""true"""))
                {
                    recurValue = recurValue + ";BYDAY=SU,SA;BYSETPOS=" + i;
                }

                // This must be a "the Nth D (day name)" pattern, then...
                else
                {
                    // The list of day values we're going to scan for
                    String[] days = new String[] { "SU", "MO", "TU", "WE", "TH", "FR", "SA" };

                    foreach (String d in days)
                    {
                        // Is this day set in the recurrence options?
                        if (options.Contains(d.ToLower() + @"=""true"""))
                        {
                            // It is -- and there can be only one of them -- so tack it on and exit the loop
                            recurValue = recurValue + ";BYDAY=" + i + d;
                            break;
                        }
                    }
                }
            }

            // Build a regex to parse out the number of occurrences
            pattern = new Regex(@"<repeatinstances>(?<REPEAT>\d+)</repeatinstances>");

            // Match against the XML
            match = pattern.Match(recurrence);

            // Pull out the number of occurrences
            String repeat = match.Groups["REPEAT"].ToString();

            // If we found a number of occurrences, add it to the recur pattern
            if (!repeat.Equals(""))
            {
                recurValue = recurValue + ";COUNT=" + repeat;
            }

            // Build a regex to parse out the end by date
            pattern = new Regex(@"<windowend>(?<ENDDATE>.+)</windowend>");

            // Match against the XML
            match = pattern.Match(recurrence);

            // Pull out the end date
            String endDate = match.Groups["ENDDATE"].ToString();

            // If we found a value, add it to the recur pattern
            if (!endDate.Equals(""))
            {
                DateTime endDT = Convert.ToDateTime(endDate);
                recurValue = recurValue + ";UNTIL=" + endDT.ToUniversalTime().ToString("yyyyMMddTHHmmssZ");
            }

            return recurValue;
        }