In the Line of Fire….Shaunak Pandit

Random thoughts abt life and my work (in the line of fire between Testers,Managers and clients)

Sending a Appointment programmatically through Code , ASP.NET ,ICalendar Format

Posted by Shaunak Pandit on September 10, 2008


Here is  in which you can send appointments via ICalendar format through code and not using the Outlook Object library (This is a very basic version of the way and does not involve much exception handling,and doesnt take care of nth case , explore a bit on that front :))


I am going to show the method of sending an appointment by creating a ICalendar Appointment file first and then sending it as an attachement over email.  (The way in which ICalendar format files are sent when you click on Tools ->Export -> as ICalendar file in the appointment )



Here is the declaration for the TimeFormat and some variables used to fill  the Appoinment details. viz start time,endtime etc.

const string c_strTimeFormat = “yyyyMMdd\\THHmmss\\Z”;
string
strStartTime=””;
string
strEndTime=””;
string
strTimeStamp=””;
string
strTempStartTime =””;
string
strTempEndTime = “”;
string
vCalendarFile = “”;

Create a Skeleton for the appointment ICalendar file format and using the variables created above we will assign the values accordingly into the Appoinment skeleton. (This string concatation can be optimised by using string builder)

// VCalendar Format.
const string
VCAL_FILE =
“BEGIN:VCALENDAR\n” +
“VERSION:1.0\n” +
“BEGIN:VEVENT\n” +
“DTSTART{0}\n” +
“DTEND{1}\n” +
“LOCATION;ENCODING=QUOTED-PRINTABLE:{2}\n” +
“DESCRIPTION;ENCODING=QUOTED-PRINTABLE:{3}\n” +
“SUMMARY;ENCODING=QUOTED-PRINTABLE:{4}\n” +
“TRIGGER:-PT15M\n” +
“PRIORITY:3\n” +
“END:VEVENT\n” +
“END:VCALENDAR” ;

Assign the Appointment values to the variables declared in the first code section and in the appropriate format.

DateTime dtmStartDate = DateTime.Parse(startDate.ToString());
DateTime dtmStartTime = DateTime.Parse(startDate + ” ” + startTime.ToString());
DateTime dtmEndTime = DateTime.Parse(startDate + ” ” + endTime.ToString());
strTempStartTime = string
.Format(“{0} {1}”,
dtmStartDate.ToShortDateString(),dtmStartTime.ToLongTimeString());
strTempEndTime = string
.Format(“{0} {1}”,
dtmStartDate.ToShortDateString(),dtmEndTime.ToLongTimeString());
strTimeStamp = (DateTime.Parse(strTempStartTime)).ToUniversalTime().ToString(c_strTimeFormat);
strStartTime = string
.Format(“:{0}”, strTimeStamp);
strEndTime = string
.Format(“:{0}”,
(DateTime.Parse(strTempEndTime)).ToUniversalTime().ToString(c_strTimeFormat));

Using String.format fill in the Appoinment skeleton created earlier with the variable values.

vCalendarFile =
String.Format(VCAL_FILE, strStartTime, strEndTime, location, summary, subject , strTimeStamp, attendeeEmail.Trim() , “ShaunakP”, attendeeName.Trim(), attendeeEmail.Trim(), organizerEmail.Trim());

Now that we have the ICalendar file created, we need to write it to the disk so as to attach it to the outgoing email
(Anybody knows a method of just creating the ICalendar file in memory and directly attaching the file without creating a Physical file please leave a feedback on how to do that,didnt get much time to look into it.)

filePath += “\\” + subject+ “.ics”;
TextWriter tw = new StreamWriter(filePath);

// write a line of text to the file
tw.WriteLine(vCalendarFile.ToString());

// close the stream
tw.Close();

Now that we have the ICalendar all we need to do is send a mail to the persons involved in the Appoinment with the ICalendar file as an attachment.

// Create object for sending mails

MailMessage mail = new MailMessage();
mail.To = attendeeEmail.Trim();
mail.From = organizerEmail.Trim();
mail.Subject = “You have got a Appointment.”;

// create the attachment
MailAttachment attachment = new MailAttachment(filePath, MailEncoding.UUEncode);
// Attach
mail.Attachments.Add( attachment );
SmtpMail.SmtpServer = _smtpServer;
SmtpMail.Send( mail );

When the Person who receives the mail opens the attached ICalendar file,it will open up in Outlook as an Outlook Appoinment.

Cheers!!

P.S There are a lot of improvements that can be done in this code like for e.g using stringbuilder etc but I have skipped on them as this is just a code snippet.

To see the code for the above SendAppoinment method click here

*Update : For those of you interested in sending a Meeting Request here is the VCalendar format

“BEGIN:VCALENDAR\n” +
“PRODID:-//Microsoft Corporation//Outlook 9.0 MIMEDIR//EN\n” +
“VERSION:2.0\n” +
“METHOD:REQUEST\n” +
“BEGIN:VEVENT\n” +
“ATTENDEE;CN=\”{8}\”;ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:{9}\n\n” +
“ORGANIZER:MAILTO:{10}\n” +
“DTSTART{0}\n” +
“DTEND{1}\n” +
“LOCATION:{2}\n” +
“TRANSP:OPAQUE\n” +
“SEQUENCE:0\n” +
“UID:{6}\n” +
“DTSTAMP:{5}\n” +
“DESCRIPTION:{3}\n” +
“SUMMARY:{4}\n” +
“PRIORITY:5\n” +
“X-MICROSOFT-CDO-IMPORTANCE:1 \n” +
“CLASS:PUBLIC\n” +
“BEGIN:VALARM\n” +
“TRIGGER:-PT15M\n” +
“ACTION:DISPLAY\n” +
“DESCRIPTION:Reminder\n” +
“END:VALARM\n” +
“END:VEVENT\n” +
“END:VCALENDAR” ;

* Known Issue: If a person rejects the meeting it wont be conveyed to you

About these ads

29 Responses to “Sending a Appointment programmatically through Code , ASP.NET ,ICalendar Format”

  1. Derrick said

    I’m already sending meeting requests as an .ics attachement like you described. Do you know of any way to send another .ics with the same UID that will cancel or delete a previously accecpted meeting request from a users calendar?

    Any help is appreciated!

    Derrick

  2. Derrick,

    Hmm thats interesting point you have it there.. why dont you send a meeting request through the code in the abolve fashion and cancel the request through outlook and try and save the ics file or the cancelation request into an ics file and open it and view the file to get the skeleton..

    Not sur eif the above idea will work fine , but worth a try..

    Shounak

  3. Janet said

    Brand new at this and trying to convert and use your code in vb to send .net (I’m using .net 2) appointment to Groupwise (Novell says it accepts iCal and iMip services). Tried a version, got the email, but when I clicked on the attachment, nothing appeared as an appointment. When I click “To see the code for the above SendAppoinment method click here”, I get a page not found. Any way you could forward?

    Thanks,
    Janet

  4. @Janet

    try this link
    http://shaunakpandit.wordpress.com/2008/09/10/sending-appointment-through-net/

    let me know if this doesn’t help

    Shounak Pandit

  5. Janet said

    Shounak,
    I’m still in there with a simple example. I get the email in Groupwise, but when I click on the attachment, it adds a new calendar file, not appointment. Any tips on what’s wrong?


    Dim filePath As String = String.Empty
    If System.IO.File.Exists("iCal\2.ics") Then
    System.IO.File.Delete("iCal\2.ics")
    End If
    Dim path As String = HttpContext.Current.Server.MapPath("iCal\")
    filePath = path + "2.ics"

    Dim myStr As String = String.Empty
    myStr = "BEGIN:VCALENDAR" & vbCrLf & _
    "VERSION:1.0" & vbCrLf & _
    "BEGIN:VEVENT" & vbCrLf & _
    "DTSTART:" & DateTime.Now.AddDays(1).ToUniversalTime().ToString("yyyyMMddTHHmmssZ") & vbCrLf & _
    "DTEND:" & (DateTime.Now.AddDays(1)).AddMinutes(35).ToUniversalTime().ToString("yyyyMMddTHHmmssZ") & vbCrLf & _
    "LOCATION:CDL" & vbCrLf & _
    "DESCRIPTION:Click the attached file to receive appointment" & vbCrLf & _
    "SUMMARY:testing another appointment" & vbCrLf & _
    "TRIGGER:-PT15M" & vbCrLf & _
    "PRIORITY:5" & vbCrLf & _
    "END:VEVENT" & vbCrLf & _
    "END:VCALENDAR"

    Dim writer As New System.IO.StreamWriter(filePath)
    writer.WriteLine(myStr)
    writer.Close()

    Dim mail As New System.Net.Mail.MailMessage("yada@emailfrom.net", "yada2@emailto.net", "test email appointment2", "click attached file2 for internet appointment")
    'message.CC.Add(New System.Net.Mail.MailAddress(Trim(txtEmail.Text)))
    mail.Attachments.Add(New System.Net.Mail.Attachment(filePath))

    Dim client As New System.Net.Mail.SmtpClient("wahoo")
    client.Send(mail)
    mail.Attachments.Dispose()
    mail.Dispose()
    mail = Nothing

    Thanks so much, Janet

  6. @Janet

    am not able to understand the exact error you are facing..What exactly you mean by

    1) I get the email in Groupwise,
    2) but when I click on the attachment, it adds a new calendar file, not appointment.

    you aren’t getting the ical file? or you getting the file but when you click on it some error is being thrown?

    Shounak Pandit

  7. Janet said

    When I click on the 2.ics attachment file, another calendar (versus simply an appointment) is added to my calendar list. No error. No appointment. I know I’ve probably got something wrong or missing – I’m just so new, I’m not sure where to go. …JB

  8. why dont you try the meeting request template mentioned at the end of the post.. i guess thats what you need?

  9. Janet said

    Okay, one baby-step at a time. Got both working, but no matter what, when I receive the email and double-click the ics file, another folder is set up. I set up a rule in Groupwise so that any appointment with the subject line is automatically added to another calendar folder. So, at least I could have them all in one? Do you know of any way to: 1) Not have to click on the ics file as an attachment but have the appointment come directly into GroupWise, e.g. no email as a wrapper? 2) How to make the ics file a part of the main parent calendar folder. 3) A good resource for all of the parameters, etc. you’ve given. You’ve been lovely with all of your replies – thanks again.

  10. @Janet:
    added my comments inline to the comment.

    Okay, one baby-step at a time. Got both working,
    Shounak: Thats great news finally sucess!! :)

    but no matter what, when I receive the email and double-click the ics file, another folder is set up.
    Shounak: another folder is setup? dint understand this? ideally it should send you a mail with the ics file as an attachment.

    I set up a rule in Groupwise so that any appointment with the subject line is automatically added to another calendar folder. So, at least I could have them all in one? Do you know of any way to:

    1) Not have to click on the ics file as an attachment but have the appointment come directly into GroupWise, e.g. no email as a wrapper?
    Shounak: Yes, but in that case you will have to use Microsoft Office library for outlook check this post of mine
    http://shaunakpandit.wordpress.com/2008/10/06/programming-outlook-2003-in-c-using-outlook-shaunak-pandit/

    Pros to this approach
    1) Uses the default users outlook account
    2) Sends mail through the outlook , mail is kept in the sent items

    Cons to this approach
    1) Microsoft outlook is necessary (as per my last research i had done 3-4 years back not sure even if we require it now)
    2)Microsoft security update patches have disabled the usage of outlook library through code unless the user manually clicks on a prompt stating that some thrid party is trying to access outlook should it be granted access

    2) How to make the ics file a part of the main parent calendar folder.
    Shounak: I am not sure how groupwise functions but in MS outlook the ics file opens into a calendar in the main calendar only. Do you have 2 calendars setup on your system? it might be going in the default one.

    3) A good resource for all of the parameters, etc. you’ve given.
    Shounak: dint understand wht you meant here? do you require some reference for the code? or mail class?

    You’ve been lovely with all of your replies – thanks again.
    Shounak: Thanks a tonne for the appreciations feel good to know my lil help is appreciated!! :)

    there are some third party controls for sending mails too,

    Shaunak

  11. CHANDRA said

    Although the above works in creating an outlook calendar event, It does not work for me when I am trying to write chinese characters ‘日期’ into the body. I have tried setting the stream writers encoding to utf-8; but failing on all attempts. Is there anything wrong that i am doing.

    Any help much appreciated.

    Thanks,
    Chandra

    • @Chandra:

      Havent tried sending UTF data but here are some pointers…

      Try in the following way to pinpoint the exact issue here..

      1) First check if you are able to save chinese data into a file outside the appointment component using file operations.If this is happening then it means you need to check on the way we are creating the appointment file.

      2) If the file using file operations cannot save Chinese data then you will have to find out the way to get that done and implement the changes in the apointment component here.

      keep me posted on this.

  12. Amol said

    I am sending the ICS file in the mail, but the problem that I have is that the application is working in EST time zone. So, if a user who is in CST or Mountain time takes an appointment for EST timings shown on the screen, the ics file in the mail should convert the time to the desired time zone in the mail. Is this possible?

  13. Hey Amol,

    Why dont you try tweaking the time you send by specifying the timezone ? I am sending using the DateTime object which has various properties for getting time in various timezones…

    Let me know how it goes.

    Shaunak

  14. @Chandra:

    Havent tried sending UTF data but here are some pointers…

    Try in the following way to pinpoint the exact issue here..

    1) First check if you are able to save chinese data into a file outside the appointment component using file operations.If this is happening then it means you need to check on the way we are creating the appointment file.

    2) If the file using file operations cannot save Chinese data then you will have to find out the way to get that done and implement the changes in the apointment component here.

    keep me posted on this.

  15. nithya said

    Thanks a lot for the amazing post Shaunak!!
    It really worked well. However, I have a little problem.
    When I send a meeting request, I want to “Show time as :Free”.
    Any ideas on this? Thanks in advance.

  16. @Nithya: ur welcome :)

    I am not sure what you mean by free time? if by free time you meaning keeping the meeting open?

    See basically the code above is a tweak for generating the ics file thru code using a template… we can play around with the values inside the template to change the meeting the way we want.. try tweaking the values of time etc…

    or else do it through outlook first then save that meeting as an .ICS file and open in notepad to check the contents and use them in your code…

  17. manish said

    hi nithya,

    i m facing the same problem with appointment calenar using asp.net can u please let me now what is the solution.

  18. rodnas said

    Hi,

    Do you know if it’s possible to send the appointment/meeting request in a way that it appears directly in Outlook calendar as accepted, without the user having to open the attachment and accept it?
    I guess sending the ics file as attachment wouldn’t work for this problem…

    Thanks,
    rodnas

    • Jenkins said

      Hi rodnas,

      Please help me, Same requirement for me also.
      My requirement appointment/meeting request, it appears directly in Outlook calendar as accepted, without the user having to open the attachment and accept it,
      Please guide me

      Its urgent
      Advance Thanks

      Jenkins

      May 13, 2009 at 9:45 am
      Hi,

      Do you know if it’s possible to send the appointment/meeting request in a way that it appears directly in Outlook calendar as accepted, without the user having to open the attachment and accept it?
      I guess sending the ics file as attachment wouldn’t work for this problem…

      Thanks,

  19. Hey Shaunak,

    Very handy piece of code! Thanks so much for putting this up.

    I found one place to make an (optional) enhancement and figured I would share.

    Instead of actually writing out a file to disk, you can create the attachment directly from the vCalendarFile string. The System.Net.Mail.Attachment class has a static method called CreateAttachmentFromString(). So instead of:

    FilePath += “\\” + Subject + “.ics”;
    TextWriter tw = new StreamWriter( FilePath );
    tw.WriteLine( vCalendarFile.ToString() );
    tw.Close();
    Attachment attachment = new Attachment( FilePath );
    mail.Attachments.Add( attachment );

    You can simply use:

    mail.Attachments.Add( Attachment.CreateAttachmentFromString( vCalendarFile, Subject + “.ics” ) );

    Obviously some people may want to have a copy of the attachment on the server but this worked perfectly for my application.

    Thanks again!

  20. Hey Matt,

    Yup thats another possibility you have brought forward to the subject thanks for sharing a file free approach

  21. Hi Rodnas,

    Yes for such a requirement you will have to use the outlook object library to connect to the outlook profile and send the meeting invite.

    In the above approach one doesnt need a outlook s/w installed on the server as long as one has the SMTP setup.

  22. Veena said

    I am using above technique to send Appointment Attachemt w/ email, working fine But don’t get any reminders in OUTlook 2007.

    I am using this code:

    ‘ VCalendar Format.
    Dim myStr As String = String.Empty
    myStr = “BEGIN:VCALENDAR” & vbCrLf & _
    “VERSION:1.0″ & vbCrLf & _
    “BEGIN:VEVENT” & vbCrLf & _
    “DTSTART:” & myEventDate.ToUniversalTime().ToString(“yyyyMMddTHHmmssZ”) & vbCrLf & _
    “DTEND:” & myEventDate.ToUniversalTime().AddHours(CDBL(row(“EventHours”))).ToString(“yyyyMMddTHHmmssZ”) & vbCrLf & _
    “TITLE:” & Cstr(row(“EventName”)) & vbCrLf & _
    “DESCRIPTION:” & stripHTML(Cstr(row(“Description”))) & vbCrLf & _
    “SUMMARY: ” & Cstr(row(“EventName”)) & ” appointment” & vbCrLf & _
    “PRIORITY:1″ & vbCrLf & _
    “X-MICROSOFT-CDO-IMPORTANCE:1 ” & vbCrLf & _
    “CLASS:PUBLIC” & vbCrLf & _
    “BEGIN:VALARM” & vbCrLf & _
    “TRIGGER:-PT15M” & vbCrLf & _
    “ACTION:DISPLAY” & vbCrLf & _
    “DESCRIPTION:Reminder” & vbCrLf & _
    “END:VALARM” & vbCrLf & _
    “END:VEVENT” & vbCrLf & _
    “END:VCALENDAR”

  23. Veena said

    Hi Is there any Particular Setting in OUtlook 2007 For reminders Because I can get the startTime, endtime fine, But no reminders. In outlook 2003 I can get reminders.
    ‘ VCalendar Format.
    Dim myStr As String = String.Empty
    myStr = “BEGIN:VCALENDAR” & vbCrLf & _
    “VERSION:1.0″ & vbCrLf & _
    “BEGIN:VEVENT” & vbCrLf & _
    “DTSTART:” & myEventDate.ToUniversalTime().ToString(“yyyyMMddTHHmmssZ”) & vbCrLf & _
    “DTEND:” & myEventDate.ToUniversalTime().AddHours(CDBL(row(“EventHours”))).ToString(“yyyyMMddTHHmmssZ”) & vbCrLf & _
    “TITLE:” & Cstr(row(“EventName”)) & vbCrLf & _
    “DESCRIPTION:” & stripHTML(Cstr(row(“Description”))) & vbCrLf & _
    “SUMMARY: ” & Cstr(row(“EventName”)) & ” appointment” & vbCrLf & _
    “PRIORITY:1″ & vbCrLf & _
    “X-MICROSOFT-CDO-IMPORTANCE:1 ” & vbCrLf & _
    “CLASS:PUBLIC” & vbCrLf & _
    “BEGIN:VALARM” & vbCrLf & _
    “TRIGGER:-PT15M” & vbCrLf & _
    “ACTION:DISPLAY” & vbCrLf & _
    “DESCRIPTION:Reminder” & vbCrLf & _
    “END:VALARM” & vbCrLf & _
    “END:VEVENT” & vbCrLf & _
    “END:VCALENDAR”

    Thanks for your help
    Veena

  24. Rajesh Saini said

    @Amol , did you get the solution for time zone issue. M having same issue. if Yes, please share .

  25. hemchand said

    Hi,

    Is there any option in vcalander so that organizer’s calander will also blocked for a particular meeting request.Right now all your code is sending a meeting request to another party where in if he accepts organizer will get a resonse.Is there any way that organizer’s calander also auto booked once a mail is send using your code.Pls help me out…Thanks in advance

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: