/// <summary>
        /// Removes a specific event or a series of events
        /// </summary>
        /// <param name="objItems">Contains all the event items in a specific calendar/folder</param>
        /// <param name="subject">Subject of the event to delete</param>
        /// <param name="eventDate">If specified, this specific event is deleted instead of all events with subject</param>
        internal static void RemoveEvent(Outlook.Items objItems, string subject, string eventDate)
        {
            string methodTag = "RemoveEvent";

            LogWriter.WriteInfo(TAG, methodTag, "Starting: " + methodTag + " in " + TAG);

            Outlook.AppointmentItem agendaMeeting = null;

            if (eventDate == null)
            {
                objItems.Sort("[Subject]");
                objItems.IncludeRecurrences = true;

                LogWriter.WriteInfo(TAG, methodTag, "Attempting to find event with subject: " + subject);
                agendaMeeting = objItems.Find("[Subject]=" + subject);

                if (agendaMeeting == null)
                {
                    LogWriter.WriteWarning(TAG, methodTag, "No event found with subject: " + subject);
                }
                else
                {
                    LogWriter.WriteInfo(TAG, methodTag, "Removing all events with subject: " + subject);
                    do
                    {
                        agendaMeeting.Delete();

                        agendaMeeting = objItems.FindNext();

                        LogWriter.WriteInfo(TAG, methodTag, "Event found and deleted, finding next");
                    } while (agendaMeeting != null);

                    LogWriter.WriteInfo(TAG, methodTag, "All events with subject: " + subject + " found and deleted");
                }
            }
            else
            {
                LogWriter.WriteInfo(TAG, methodTag, "Finding event with subject" + subject + " and date: " + eventDate);
                agendaMeeting = objItems.Find("[Subject]=" + subject);

                if (agendaMeeting == null)
                {
                    LogWriter.WriteWarning(TAG, methodTag, "No event found with subject: " + subject);
                }
                else
                {
                    Outlook.RecurrencePattern recurrPatt = agendaMeeting.GetRecurrencePattern();
                    agendaMeeting = recurrPatt.GetOccurrence(DateTime.Parse(eventDate));

                    agendaMeeting.Delete();

                    LogWriter.WriteInfo(TAG, methodTag, "Event found and deleted");
                }
            }
        }
Exemple #2
0
        override public void DeleteAppointment(SubCalendarEvent ActiveSection, string NameOfParentCalendarEvent = "", string entryID = "")
        {
#if EnableOutlook
            if (entryID == "")
            {
                return;
            }
            Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
            Outlook.MAPIFolder  calendar   = outlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);

            Outlook.Items calendarItems = calendar.Items;
            try
            {
                string SubJectString = ActiveSection.getId + "**" + NameOfParentCalendarEvent;
                if (ActiveSection.getIsComplete)
                {
                    //SubJectString = ActiveSection.ID + "*\u221A*" + NameOfParentCalendarEvent;
                }
                Outlook.AppointmentItem item = calendarItems[SubJectString] as Outlook.AppointmentItem;
                item.Delete();
            }
            catch (Exception e)
            {
                return;
            }
#endif
        }
 /// <summary>
 /// Allows to delete the selected appointment (whether it's a recurring one or not)
 /// </summary>
 /// <param name="sender">Sender</param>
 /// <param name="e">EventArgs</param>
 private void mnuItemDeleteAppointment_Click(object sender, EventArgs e)
 {
     if (this.lstAppointments.SelectedIndices.Count != 0)
     {
         Outlook.AppointmentItem appt = this.lstAppointments.SelectedItems[0].Tag as Outlook.AppointmentItem;
         if (appt != null)
         {
             if (appt.IsRecurring)
             {
                 FormRecurringOpen f = new FormRecurringOpen();
                 f.Title   = "Warning: Delete Recurring Item";
                 f.Message = "This is one appointment in a series. What do you want to delete?";
                 if (f.ShowDialog() == DialogResult.OK)
                 {
                     if (f.OpenRecurring)
                     {
                         Outlook.AppointmentItem masterAppt = appt.Parent; // Get the master appointment item
                         masterAppt.Delete();                              // Will delete ALL instances
                     }
                     else
                     {
                         appt.Delete(); // Delete just this instance
                     }
                 }
             }
             else
             {
                 if (MessageBox.Show("Are you sure you want to delete this appointment?", "Delete appointment", MessageBoxButtons.YesNo) == DialogResult.Yes)
                 {
                     appt.Delete(); // Delete just this instance
                 }
             }
             // At the end, synchronously "refresh" appointments in case they have changed
             this.RetrieveAppointments();
         }
     }
 }
Exemple #4
0
        //gavdcodeend 09

        //gavdcodebegin 10
        private void btnDeleteAppointment_Click(object sender, RibbonControlEventArgs e)
        {
            Outlook.Application myApplication = Globals.ThisAddIn.Application;

            Outlook.MAPIFolder myCalendar = myApplication.Session.GetDefaultFolder(
                Outlook.OlDefaultFolders.olFolderCalendar);
            Outlook.Items           calendarItems   = myCalendar.Items;
            Outlook.AppointmentItem oneCalendarItem =
                (Outlook.AppointmentItem)calendarItems["Test Appointment to delete"];

            if (oneCalendarItem != null)
            {
                oneCalendarItem.Delete();
            }
        }
        public void TestSync_Time()
        {
            sync.SyncOption = SyncOption.MergeOutlookWins;

            // create new appointment to sync
            Outlook.AppointmentItem outlookAppointment = Synchronizer.CreateOutlookAppointmentItem(Synchronizer.SyncAppointmentsFolder);
            outlookAppointment.Subject     = name;
            outlookAppointment.Start       = DateTime.Now;
            outlookAppointment.End         = DateTime.Now.AddHours(1);
            outlookAppointment.AllDayEvent = false;

            outlookAppointment.Save();


            sync.SyncOption = SyncOption.OutlookToGoogleOnly;

            var googleAppointment = Factory.NewEvent();

            sync.UpdateAppointment(outlookAppointment, ref googleAppointment);

            googleAppointment = null;

            sync.SyncOption = SyncOption.GoogleToOutlookOnly;
            //load the same appointment from google.
            MatchAppointments(sync);
            AppointmentMatch match = FindMatch(outlookAppointment);

            Assert.IsNotNull(match);
            Assert.IsNotNull(match.GoogleAppointment);
            Assert.IsNotNull(match.OutlookAppointment);

            Outlook.AppointmentItem recreatedOutlookAppointment = Synchronizer.CreateOutlookAppointmentItem(Synchronizer.SyncAppointmentsFolder);
            sync.UpdateAppointment(ref match.GoogleAppointment, recreatedOutlookAppointment, match.GoogleAppointmentExceptions);
            Assert.IsNotNull(outlookAppointment);
            Assert.IsNotNull(recreatedOutlookAppointment);
            // match recreatedOutlookAppointment with outlookAppointment

            Assert.AreEqual(outlookAppointment.Subject, recreatedOutlookAppointment.Subject);

            Assert.AreEqual(outlookAppointment.Start, recreatedOutlookAppointment.Start);
            Assert.AreEqual(outlookAppointment.End, recreatedOutlookAppointment.End);
            Assert.AreEqual(outlookAppointment.AllDayEvent, recreatedOutlookAppointment.AllDayEvent);
            //ToDo: Check other properties

            DeleteTestAppointments(match);
            recreatedOutlookAppointment.Delete();
        }
Exemple #6
0
 private void DeleteTestAppointment(Outlook.AppointmentItem ola)
 {
     if (ola != null)
     {
         try
         {
             string name = ola.Subject;
             ola.Delete();
             Logger.Log("Deleted Outlook test appointment: " + name, EventType.Information);
         }
         finally
         {
             Marshal.ReleaseComObject(ola);
             ola = null;
         }
     }
 }
 private void DeleteTestAppointment(Outlook.AppointmentItem outlookAppointment)
 {
     if (outlookAppointment != null)
     {
         try
         {
             string name = outlookAppointment.Subject;
             outlookAppointment.Delete();
             Logger.Log("Deleted Outlook test appointment: " + name, EventType.Information);
         }
         finally
         {
             System.Runtime.InteropServices.Marshal.ReleaseComObject(outlookAppointment);
             outlookAppointment = null;
         }
     }
 }
        /// <summary>
        /// Deletes the appointment in the custom calendar
        /// </summary>
        /// <param name="syncID">SyncID of the appointment</param>
        /// <returns>returns true if successfull</returns>
        private bool DeleteAppointment(String syncID)
        {
            if (_customCalendar == null || String.IsNullOrEmpty(syncID))
            {
                return(false);
            }

            Outlook.AppointmentItem foundItem = _customCalendar.Items.Find(String.Format("[" + ITEM_PROPERTY_SYNC_ID + "] = '{0}'", syncID));
            if (foundItem != null)
            {
                foundItem.Delete();
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #9
0
 /// <summary>
 /// Sets recurrence exceptions in direction Google -> Outlook
 /// </summary>
 /// <param name="googleItem">Source Google event</param>
 /// <param name="outlookItem">Target Outlook event</param>
 private void SetRecurrenceExceptions(Event googleItem, object outlookItem)
 {
     //if (!this._googleExceptions.ContainsKey(googleItem.Id))
     //    return;
     ((Outlook.AppointmentItem)outlookItem).Save();
     Outlook.RecurrencePattern outlookRecurrence = ((Outlook.AppointmentItem)outlookItem).GetRecurrencePattern();
     try
     {
         if (this._googleExceptions.ContainsKey(googleItem.Id))
         {
             foreach (Event googleException in this._googleExceptions[googleItem.Id])
             {
                 /// If the exception is already in Outlook event this one is omited
                 //if (RecurrenceExceptionComparer.Contains(outlookRecurrence.Exceptions, googleException))
                 //    continue;
                 /// Get occurence of the recurrence and modify it. Thus new exception is created
                 Outlook.AppointmentItem outlookExceptionItem = outlookRecurrence.GetOccurrence(googleException.OriginalStartTime.DateTime.Value);
                 try
                 {
                     if (googleException.Status == "cancelled")
                     {
                         outlookExceptionItem.Delete();
                     }
                     else
                     {
                         this.SetSubject(googleException, outlookExceptionItem, Target.Outlook);
                         this.SetDescription(googleException, outlookExceptionItem, Target.Outlook);
                         this.SetLocation(googleException, outlookExceptionItem, Target.Outlook);
                         this.SetTime(googleException, outlookExceptionItem, Target.Outlook);
                         outlookExceptionItem.Save();
                     }
                 }
                 finally
                 {
                     Marshal.ReleaseComObject(outlookExceptionItem);
                 }
             }
         }
     }
     finally
     {
         Marshal.ReleaseComObject(outlookRecurrence);
     }
 }
        // <Snippet1>
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Outlook.MAPIFolder calendar =
                Application.Session.GetDefaultFolder(
                    Outlook.OlDefaultFolders.olFolderCalendar);

            Outlook.Items calendarItems = calendar.Items;

            Outlook.AppointmentItem item =
                calendarItems["Test Appointment"] as Outlook.AppointmentItem;

            Outlook.RecurrencePattern pattern =
                item.GetRecurrencePattern();
            Outlook.AppointmentItem itemDelete = pattern.
                                                 GetOccurrence(new DateTime(2006, 6, 28, 8, 0, 0));

            if (itemDelete != null)
            {
                itemDelete.Delete();
            }
        }
Exemple #11
0
        /// <summary>
        /// Función encargada de crear una nueva reunión, se conectará con el servidor y mostrará en un navegador dedicado la página de
        /// reserva de salas. A su vez, almacenará la reserva en la máquina cliente
        /// </summary>
        public void CreaReunion(WaitForm waitForm)
        {
            string   path = @"C:\Users\cifua\Desktop\salida\salida.txt";
            UserData data = new UserData();
            string   username, password, fullStartDate, fullEndDate, day, start, end, subject, location, id;
            bool     actualizado      = false;
            bool     existAppointment = false;

            //Guardamos en variables todos los datos de la reunión creada en outlook
            Outlook.AppointmentItem appointment = Globals.ThisAddIn.Application.ActiveInspector().CurrentItem;
            fullStartDate = appointment.Start.ToString();
            string[] date = fullStartDate.Split(' ');
            day         = date[0];
            start       = date[1];
            fullEndDate = appointment.End.ToString();
            date        = fullEndDate.Split(' ');
            end         = date[1];
            location    = appointment.Location;


            //Se necesita guardar ya que, en caso de que el usuario no haya salido del campo Asunto a la hora de escribirlo, este no será capturado a no ser que se guarde la reunión
            appointment.Save();
            id       = appointment.EntryID;
            subject  = appointment.Subject;
            username = data.GetUsername();
            password = data.GetPassword();
            string user = "******" + username + "," + password + ")";

            ArrayList userFinal        = Globals.ThisAddIn.encryptOutlook(user);
            var       resultAutenticar = AutenticarUsuarioOutlook("http://88.12.10.158:81/AutenticarUsuarioOutlook", userFinal);
            JObject   jsonAutenticar   = JObject.Parse(resultAutenticar.Result);
            string    errnoAutenticar  = (string)jsonAutenticar.SelectToken("errno");

            if (errnoAutenticar.Equals("0"))
            {
                var     resultReserva = GetURLCrearReservaOutlook("http://88.12.10.158:81/GetURLCrearReservaOutlook", userFinal, subject, day, start, end);
                JObject jsonReserva   = JObject.Parse(resultReserva.Result);
                string  errnoGetURL   = (string)jsonReserva.SelectToken("errno");
                if (errnoGetURL.Equals("0"))
                {
                    string url = "";
                    if (subject is null)
                    {
                        subject = " ";
                    }

                    if (data.AppointmentExists(id))
                    {
                        File.AppendAllText(path, "ACTUALIZACION DE REUNION \n");
                        ArrayList oldAppointment = data.GetAppointment(id);

                        url = "http://88.12.10.158:81/CrearReservaOutlook?user="******"&password="******"&accion=" + 2 + "&asuntoAnterior=" + oldAppointment.get(0).ToString() + "&asuntoNuevo=" + subject + "&fechaAnterior=" + oldAppointment.get(1).ToString() +
                              "&fechaNuevo=" + day + "&inicioAnterior=" + oldAppointment.get(2).ToString() + "&hInicioNuevo=" + start + "&hFinAnterior=" + oldAppointment.get(3).ToString() + "&hFinNuevo=" + end;
                        existAppointment = true;
                    }
                    else
                    {
                        url = "http://88.12.10.158:81/CrearReservaOutlook?user="******"&password="******"&accion=" + 1 + "&asuntoNuevo=" + subject + "&fechaNuevo=" + day + "&hInicioNuevo=" + start + "&hFinNuevo=" + end;
                    }

                    waitForm.Close();

                    //Creamos un nuevo hilo donde se abrirá el navegador con la web de reservas de salas
                    Thread thread = new Thread(() => StartBrowser(url));
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    Thread.Sleep(1000);

                    File.AppendAllText(path, "Primer Envio: " + subject + " " + day + " " + start + " " + end + "\n");
                    var err = GetDatosReserva(userFinal, subject, day, start, end);
                    Thread.Sleep(1000);
                    File.AppendAllText(path, "Primera Respuesta: " + JObject.Parse(err.Result) + "\n");

                    if (err.Result.Contains("\"errno\":\"1\""))
                    {
                        err = GetDatosReserva(userFinal, subject, day, start, end);
                    }
                    File.AppendAllText(path, "Segunda Respuesta: " + JObject.Parse(err.Result) + "\n");
                    //err = GetDatosReserva(userFinal, subject, day, start, end);
                    // File.AppendAllText(path, "RECIBO: " + err.Result+"\n");
                    //Mientras se nos devuelva que no existen datos de la reserva, se preguntará continuamente
                    if (err.Result.Contains("\"errno\":\"1\""))
                    {
                        while (err.Result.Contains("\"errno\":\"1\""))
                        {
                            if (!thread.IsAlive)
                            {
                                break;
                            }
                            err = GetDatosReserva(userFinal, subject, day, start, end);
                            //File.AppendAllText(path, "RECIBO: " + err.Result + "\n");
                        }
                    }
                    File.AppendAllText(path, "Respuesta FINAL: " + JObject.Parse(err.Result) + "\n");
                    //Si se nos devuelven datos de una reserva, primero tendremos que comprobar que, en el caso de estar actualizando una
                    //reunión ya existente, estos datos de respuesta son distintos
                    if (err.Result.Contains("\"errno\":\"0\""))
                    {
                        if (data.AppointmentExists(id))
                        {
                            File.AppendAllText(path, "REUNION EXISTE \n");
                            err = GetDatosReserva(userFinal, subject, day, start, end);
                            Thread.Sleep(1000);
                            err = GetDatosReserva(userFinal, subject, day, start, end);
                            File.AppendAllText(path, "PRIMEROS DATOS: " + JObject.Parse(err.Result) + "\n");


                            ArrayList oldAppointment = data.GetAppointment(id);
                            string    firstLocation  = location;
                            JObject   r         = JObject.Parse(err.Result);
                            string    fsede     = (string)r.SelectToken("error[0].sede");
                            string    fedificio = (string)r.SelectToken("error[0].edificio");
                            string    fplanta   = (string)r.SelectToken("error[0].planta");
                            string    fsala     = (string)r.SelectToken("error[0].sala");

                            while (oldAppointment.get(0).ToString().Equals((string)r.SelectToken("error[0].asunto")) & oldAppointment.get(1).ToString().Equals((string)r.SelectToken("error[0].fecha")) &
                                   oldAppointment.get(2).ToString().Equals((string)r.SelectToken("error[0].hInicio")) & oldAppointment.get(3).ToString().Equals((string)r.SelectToken("error[0].hFin")) &
                                   fsede.Equals((string)r.SelectToken("error[0].sede")) & fedificio.Equals((string)r.SelectToken("error[0].edificio"))
                                   & fplanta.Equals((string)r.SelectToken("error[0].planta")) & fsala.Equals((string)r.SelectToken("error[0].sala")))
                            {
                                if (!thread.IsAlive)
                                {
                                    break;
                                }
                                Thread.Sleep(2000);
                                err = GetDatosReserva(userFinal, subject, day, start, end);

                                r = JObject.Parse(err.Result);
                                File.AppendAllText(path, "RECIBO: " + r + "\n");
                            }
                        }
                        File.AppendAllText(path, "HE SALIDO: " + JObject.Parse(err.Result) + "\n");
                        //Actualizamos los datos de la reunión con lo generado en la web de reservas
                        err = GetDatosReserva(userFinal, subject, day, start, end);
                        File.AppendAllText(path, "HE SALIDO Y REACTUALIZADO: " + JObject.Parse(err.Result) + "\n");
                        JObject result     = JObject.Parse(err.Result);
                        string  newSubject = (string)result.SelectToken("error[0].asunto");
                        string  newDay     = (string)result.SelectToken("error[0].fecha");
                        string  newStart   = (string)result.SelectToken("error[0].hInicio");
                        string  newEnd     = (string)result.SelectToken("error[0].hFin");
                        string  sede       = (string)result.SelectToken("error[0].sede");
                        string  edificio   = (string)result.SelectToken("error[0].edificio");
                        string  planta     = (string)result.SelectToken("error[0].planta");
                        string  sala       = (string)result.SelectToken("error[0].sala");
                        appointment.Location = "Sede: " + sede + ", " + edificio + ", " + planta + ", sala: " + sala;
                        appointment.Subject  = newSubject;
                        string   sd        = newDay + " " + newStart;
                        DateTime startDate = DateTime.Parse(sd);
                        appointment.Start = startDate;
                        string   sd2     = newDay + " " + newEnd;
                        DateTime endDate = DateTime.Parse(sd2);
                        appointment.End = endDate;
                        appointment.Save();

                        thread.Abort();
                        thread.Join();
                        if (!subject.Equals(newSubject) | !newStart.Equals(start) | !day.Equals(newDay) | !newEnd.Equals(end))
                        {
                            MessageBox.Show("Los datos de la reunión han sido actualizados");
                        }
                        if (existAppointment == true)
                        {
                            data.UpdateAppointment(id, newSubject, newDay, newStart, newEnd);
                        }
                        else
                        {
                            //appointment.Save();
                            id = appointment.EntryID;
                            data.AddAppointment(id, newSubject, newDay, newStart, newEnd);
                        }
                    }
                    else
                    {
                        MessageBox.Show("No se han podido recopilar los datos de la reunion");
                        if (!existAppointment)
                        {
                            appointment.Delete();
                        }
                    }
                }
                else
                {
                    MessageBox.Show((string)jsonReserva.SelectToken("error"));
                }
            }
            else
            {
                MessageBox.Show((string)jsonAutenticar.SelectToken("error"));
            }
        }
        public bool                 CalendarItemConvertRecurrences()
        {
            try
            {
                bool ConvertedAny = false;
                #region var
                DateTime checkLast_At          = DateTime.Parse(sqlController.SettingRead(Settings.checkLast_At));
                double   checkPreSend_Hours    = double.Parse(sqlController.SettingRead(Settings.checkPreSend_Hours));
                double   checkRetrace_Hours    = double.Parse(sqlController.SettingRead(Settings.checkRetrace_Hours));
                int      checkEvery_Mins       = int.Parse(sqlController.SettingRead(Settings.checkEvery_Mins));
                bool     includeBlankLocations = bool.Parse(sqlController.SettingRead(Settings.includeBlankLocations));

                DateTime timeOfRun  = DateTime.Now;
                DateTime tLimitTo   = timeOfRun.AddHours(+checkPreSend_Hours);
                DateTime tLimitFrom = checkLast_At.AddHours(-checkRetrace_Hours);
                #endregion

                #region convert recurrences
                foreach (Outlook.AppointmentItem item in GetCalendarItems(tLimitTo, tLimitFrom))
                {
                    if (item.IsRecurring) //is recurring, otherwise ignore
                    {
                        #region location "planned"?
                        string location = item.Location;

                        if (location == null)
                        {
                            if (includeBlankLocations)
                            {
                                location = "planned";
                            }
                            else
                            {
                                location = "";
                            }
                        }

                        location = location.ToLower();
                        #endregion

                        if (location == "planned")
                        #region ...
                        {
                            Outlook.RecurrencePattern rp    = item.GetRecurrencePattern();
                            Outlook.AppointmentItem   recur = null;

                            DateTime startPoint = item.Start;
                            while (startPoint.AddYears(1) <= tLimitFrom)
                            {
                                startPoint = startPoint.AddYears(1);
                            }
                            while (startPoint.AddMonths(1) <= tLimitFrom)
                            {
                                startPoint = startPoint.AddMonths(1);
                            }
                            while (startPoint.AddDays(1) <= tLimitFrom)
                            {
                                startPoint = startPoint.AddDays(1);
                            }

                            for (DateTime testPoint = startPoint; testPoint <= tLimitTo; testPoint = testPoint.AddMinutes(checkEvery_Mins)) //KEY POINT
                            {
                                if (testPoint >= tLimitFrom)
                                {
                                    try
                                    {
                                        recur = rp.GetOccurrence(testPoint);

                                        try
                                        {
                                            Appointment appo_Dto = new Appointment(recur.GlobalAppointmentID, recur.Start, item.Duration, recur.Subject, recur.Location, recur.Body, t.Bool(sqlController.SettingRead(Settings.colorsRule)), false, sqlController.Lookup);
                                            appo_Dto = CreateAppointment(appo_Dto);
                                            recur.Delete();
                                            log.LogStandard("Not Specified", recur.GlobalAppointmentID + " / " + recur.Start + " converted to non-recurence appointment");
                                        }
                                        catch (Exception ex)
                                        {
                                            log.LogWarning("Not Specified", t.PrintException(t.GetMethodName() + " failed. The OutlookController will keep the Expection contained", ex));
                                        }
                                        ConvertedAny = true;
                                    }
                                    catch { }
                                }
                            }
                        }
                        #endregion
                    }
                }
                #endregion

                if (ConvertedAny)
                {
                    log.LogStandard("Not Specified", t.GetMethodName() + " completed + converted appointment(s)");
                }
                else
                {
                    log.LogEverything("Not Specified", t.GetMethodName() + " completed");
                }

                return(ConvertedAny);
            }
            catch (Exception ex)
            {
                throw new Exception(t.GetMethodName() + " failed", ex);
            }
        }
Exemple #13
0
 /// <summary>
 /// Delete all mail items in folder
 /// </summary>
 /// <param name="mapiFolder">The folder need to delete all mails</param>
 public static void DeleteAllItemInMAPIFolder(Outlook.MAPIFolder mapiFolder)
 {
     if (mapiFolder.Items != null)
     {
         int count = mapiFolder.Items.Count;
         if (count == 0)
         {
             return;
         }
         else
         {
             try
             {
                 do
                 {
                     if (mapiFolder.Items.GetFirst() is Outlook.MailItem)
                     {
                         Outlook.MailItem outlookMail = (Outlook.MailItem)mapiFolder.Items.GetFirst();
                         if (outlookMail != null)
                         {
                             outlookMail.Delete();
                             Marshal.ReleaseComObject(outlookMail);
                             count--;
                         }
                     }
                     else if (mapiFolder.Items.GetFirst() is Outlook.PostItem)
                     {
                         Outlook.PostItem outlookPost = (Outlook.PostItem)mapiFolder.Items.GetFirst();
                         if (outlookPost != null)
                         {
                             outlookPost.Delete();
                             Marshal.ReleaseComObject(outlookPost);
                             count--;
                         }
                     }
                     else if (mapiFolder.Items.GetFirst() is Outlook.MeetingItem)
                     {
                         Outlook.MeetingItem outlookMeeting = (Outlook.MeetingItem)mapiFolder.Items.GetFirst();
                         if (outlookMeeting != null)
                         {
                             outlookMeeting.Delete();
                             Marshal.ReleaseComObject(outlookMeeting);
                             count--;
                         }
                     }
                     else if (mapiFolder.Items.GetFirst() is Outlook.AppointmentItem)
                     {
                         Outlook.AppointmentItem outlookAppointment = (Outlook.AppointmentItem)mapiFolder.Items.GetFirst();
                         if (outlookAppointment != null)
                         {
                             outlookAppointment.Delete();
                             Marshal.ReleaseComObject(outlookAppointment);
                             count--;
                         }
                     }
                 }while (count > 0);
             }
             catch (Exception e)
             {
                 throw new Exception(e.Message);
             }
         }
     }
 }