static void Main(string[] args)
        {
            var url = "http://*****:*****@word1";
            var domain = (string)null; //"CONTOSO";

            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; // ignore certificate errors for HTTPS
            var exchange = new ExchangeService(ExchangeVersion.Exchange2007_SP1)
            {
                Url = new Uri(url),
                Credentials = new WebCredentials(username, password, domain),
            };

            // req#1: this succeeds
            Test("GetUserAvailability (FreeBusy only)",
                () => exchange.GetUserAvailability(new[]{new AttendeeInfo{SmtpAddress = username}}, new TimeWindow(DateTime.Today, DateTime.Today.AddDays(1)), AvailabilityData.FreeBusy));
            // req#2: this fails with an empty response
            Test("GetUserAvailability (FreeBusyAndSuggestions)",
                () => exchange.GetUserAvailability(new[]{new AttendeeInfo{SmtpAddress = username}}, new TimeWindow(DateTime.Today, DateTime.Today.AddDays(1)), AvailabilityData.FreeBusyAndSuggestions));
            // req#3: this fails because the ResponseMessages xml element is empty
            Test("CreateItem",
                () =>
                    {
                        var appointment = new Appointment(exchange);
                        appointment.Start = DateTime.Today.AddHours(10);
                        appointment.End = DateTime.Today.AddHours(12);
                        appointment.Subject = "Test appointment";
                        appointment.Save();
                    });
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Loads exchange appointment from exchange, filtered by related <paramref name="activityMetadata"/> to
        /// activity unique identifier.
        /// </summary>
        /// <param name="activityMetadata">Activity instance synchronization metadata.</param>
        /// <returns>If appointment with activity id found, returns <see cref="Exchange.Appointment"/> instance.
        /// Otherwise returns null.</returns>
        private Exchange.Appointment GetAppointmentByLocalIdProperty(SysSyncMetaData activityMetadata)
        {
            var localId             = activityMetadata.LocalId;
            var filters             = new Exchange.SearchFilter.SearchFilterCollection(Exchange.LogicalOperator.And);
            var customPropSetFilter = new Exchange.SearchFilter.IsEqualTo(ExchangeUtilityImpl.LocalIdProperty, localId.ToString());

            filters.Add(customPropSetFilter);
            foreach (var noteFolder in Folders)
            {
                Exchange.PropertySet idOnlyPropertySet = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly);
                var itemView = new Exchange.ItemView(1)
                {
                    PropertySet = idOnlyPropertySet
                };
                IEnumerable <Exchange.Item> itemCollection = GetCalendarItemsByFilter(noteFolder, filters, itemView);
                if (itemCollection == null)
                {
                    continue;
                }
                foreach (Exchange.Item item in itemCollection)
                {
                    Exchange.Appointment appointment = SafeBindItem <Exchange.Appointment>(Service, item.Id);
                    if (appointment != null)
                    {
                        return(appointment);
                    }
                }
            }
            return(null);
        }
        public static void CreateAppointment(ExchangeService service, string fechaInicio, string fechaFin, string lugar, string nombre, string dias)
        {
            Appointment app = new Appointment(service);
            app.Subject = nombre;
            app.Location = lugar;

            DateTime dateInicio = Convert.ToDateTime(fechaInicio);
            DateTime dateFin = Convert.ToDateTime(fechaFin);
            TimeSpan timeSpan = dateFin.Subtract(dateInicio);
            string timeFor = timeSpan.ToString(@"hh\:mm\:ss");
            var time = TimeSpan.Parse(timeFor);
            app.Start = dateInicio;
            app.End = dateInicio.Add(time);
            //-----
            if (dias != "")
            {
                DayOfTheWeek[] days = stringToDays(dias);
                app.Recurrence = new Recurrence.WeeklyPattern(app.Start.Date, 1, days);
                app.Recurrence.StartDate = app.Start.Date;
                app.Recurrence.EndDate = dateFin;
            }

            app.IsReminderSet = true;
            app.ReminderMinutesBeforeStart = 15;
            app.Save(SendInvitationsMode.SendToAllAndSaveCopy);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CalendarActionResults"/> class.
 /// </summary>
 /// <param name="items">Collection of items that were created or modified as a result of a calendar action.</param>
 internal CalendarActionResults(IEnumerable<Item> items)
 {
     this.appointment = EwsUtilities.FindFirstItemOfType<Appointment>(items);
     this.meetingRequest = EwsUtilities.FindFirstItemOfType<MeetingRequest>(items);
     this.meetingResponse = EwsUtilities.FindFirstItemOfType<MeetingResponse>(items);
     this.meetingCancellation = EwsUtilities.FindFirstItemOfType<MeetingCancellation>(items);
 }
Ejemplo n.º 5
0
        public static void CreateReservation(string roomAddress, int duration)
        {
            Appointment newApt = new Appointment(_exchangeService);
            newApt.Subject = "Walk up";
            newApt.Start = DateTime.Now;
            newApt.StartTimeZone = TimeZoneInfo.Local;
            newApt.End = DateTime.Now.AddMinutes(duration);
            newApt.EndTimeZone = TimeZoneInfo.Local;
            newApt.Resources.Add(roomAddress);

            newApt.Save(SendInvitationsMode.SendOnlyToAll);

            //set 'pending' item so that quick GetRoomAvailability calls
            //won't miss this appointment just because the meeting room
            //hasn't accepted yet. Since this only applies to  Walk Up
            //reservations (and you can only have one of those at a time)
            //we can store this in a single cached value
            _memoryCache.Add(GetRoomPendingEventKey(roomAddress),
                new CalendarEvent()
                {
                    Subject = newApt.Subject,
                    StartTime = newApt.Start,
                    EndTime = newApt.End,
                    Status = "Busy"
                },
                DateTime.Now.AddMinutes(2));

            _memoryCache.Remove(GetRoomEventsKey(roomAddress));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Returns the external data repository synchronization object by a unique foreign key from synchronization metadata.
        /// </summary>
        /// <param name="schema">Schema.</param>
        /// <param name="itemMetadata">Synchronization metadata.</param>
        /// <returns>Created instance of <see cref="IRemoteItem"/>.</returns>
        public override IRemoteItem LoadSyncItem(SyncItemSchema schema, ItemMetadata itemMetadata)
        {
            SysSyncMetaData syncItemMetadata = itemMetadata.FirstOrDefault(item => item.SyncSchemaName == "Activity");

            if (syncItemMetadata == null)
            {
                var notChangedAppointment = CreateExchangeAppointment(schema, null, string.Empty, TimeZone);
                notChangedAppointment.State = SyncState.None;
                return(notChangedAppointment);
            }
            string       itemId = GetRemoteId(syncItemMetadata);
            ExchangeBase remoteItem;
            var          appointment = SafeBindItem <Exchange.Appointment>(Service, new Exchange.ItemId(itemId));

            if (appointment == null && _userConnection.GetIsFeatureEnabled("SyncDeletedAppointments"))
            {
                appointment = GetAppointmentByLocalIdProperty(syncItemMetadata);
            }
            if (appointment != null)
            {
                remoteItem        = CreateExchangeAppointment(schema, appointment, TimeZone);
                remoteItem.Action = SyncAction.Update;
            }
            else
            {
                string itemRemoteId = syncItemMetadata.RemoteId;
                appointment       = new Exchange.Appointment(Service);
                remoteItem        = CreateExchangeAppointment(schema, appointment, itemRemoteId, TimeZone);
                remoteItem.State  = SyncState.Deleted;
                remoteItem.Action = SyncAction.Delete;
            }
            return(remoteItem);
        }
Ejemplo n.º 7
0
        /// <summary>In case of items with same remote ids, some new exchange items resolved as apply to remote.
        /// In case there is no activity metadata, conflict resolved as apply to local.</summary>
        /// <param name="syncItem">Sync entity instance.</param>
        /// <param name="itemMetaData">Metadata instance.</param>
        /// <param name="localStoreId">Local storage id.</param>
        /// <returns>Sync conflict resoluton for sync item.</returns>
        public override SyncConflictResolution ResolveConflict(IRemoteItem syncItem,
                                                               ItemMetadata itemMetaData, Guid localStoreId)
        {
            if (syncItem.Action == SyncAction.CreateRecurringMaster)
            {
                return(SyncConflictResolution.ApplyToLocal);
            }
            bool isActivityExists = itemMetaData.Any(item => item.SyncSchemaName == "Activity");

            if (!isActivityExists)
            {
                return(SyncConflictResolution.ApplyToLocal);
            }
            if (_userConnection.GetIsFeatureEnabled("ResolveConflictsByContent"))
            {
                var appointment = syncItem as ExchangeAppointment;
                if (appointment.Action == SyncAction.Delete)
                {
                    return(SyncConflictResolution.ApplyToRemote);
                }
                Exchange.Appointment remoteItem = appointment.Item as Exchange.Appointment;
                appointment.LoadItemProperties(remoteItem);
                string oldActivityHash = GetActivityHashFromMetadata(itemMetaData);
                if (!appointment.IsAppointmentChanged(remoteItem, oldActivityHash, _userConnection))
                {
                    return(SyncConflictResolution.ApplyToRemote);
                }
            }
            SyncConflictResolution result = base.ResolveConflict(syncItem, itemMetaData, localStoreId);

            return(result);
        }
Ejemplo n.º 8
0
        public ReserveRoomResponse Execute(ReserveRoomRequest request)
        {
            var response = new ReserveRoomResponse();

            try
            {
                // Get mailbox info
                var requestMailboxInfo = new GetMailboxInfo.GetMailboxInfoRequest(
                    email: request.MailboxEmail);
                var responseMailboxInfo = new GetMailboxInfo().Execute(requestMailboxInfo);
                if (!responseMailboxInfo.Success) {
                    response.ErrorMessage = responseMailboxInfo.ErrorMessage;
                    return response;
                }

                // Connect to Exchange
                var service = ExchangeServiceConnector.GetService(request.MailboxEmail);

                var mbx = new Mailbox(request.MailboxEmail);
                FolderId fid = new FolderId(WellKnownFolderName.Calendar, mbx);

                //CalendarFolder calendar = CalendarFolder.Bind(service, fid, new PropertySet(FolderSchema.ManagedFolderInformation, FolderSchema.ParentFolderId, FolderSchema.ExtendedProperties));

                // Create appointment
                var appointment = new Appointment(service);

                appointment.Subject = "Impromptu Meeting";
                appointment.Body = "Booked via Conference Room app.";
                appointment.Start = DateTime.Now;
                appointment.End = DateTime.Now.AddMinutes(request.BookMinutes);
                appointment.Location = responseMailboxInfo.DisplayName;
                appointment.Save(fid, SendInvitationsMode.SendToNone);

                // Verify saved
                Item item = Item.Bind(service, appointment.Id, new PropertySet(ItemSchema.Subject));
                if (item == null)
                {
                    response.ErrorMessage = "Error saving appointment to calendar.";
                    return response;
                }
                else
                {
                    response.AppointmentId = appointment.Id;
                    response.Success = true;
                }
            }
            catch (Exception e)
            {
                response.ErrorMessage = e.ToString();
                return response;
            }

            return response;
        }
Ejemplo n.º 9
0
 public Appointment GetAppointment(ExchangeService objService, string msg, DateTime startdate, DateTime enddate)
 {
     Appointment appointment = new Appointment(objService);
     appointment.Subject = msg;
     appointment.Location = "Office365";
     appointment.Start = startdate;          
     appointment.End = enddate;
     appointment.Body = msg;
     appointment.IsReminderSet = false;
     appointment.IsResponseRequested = false;
     return appointment;
 }
Ejemplo n.º 10
0
Archivo: Event.cs Proyecto: ozgend/hive
 public Event(Appointment a)
 {
     this.Title = a.Subject;
     this.Description = a.Body.Text;
     this.Location = a.Location;
     this.Start = a.Start;
     this.End = a.End;
     this.Type = a.GetType().Name;
     this.Invited = GetPersons(a);
     this.MyResponse = a.MyResponseType.ToString();
     this.Id = a.Id.UniqueId;
     this.ResponseRequired = a.MyResponseType == MeetingResponseType.NoResponseReceived;
 }
 public void CancelMeeting(string meetingId, string cancelMessage)
 {
     Microsoft.Exchange.WebServices.Data.Appointment meeting = Microsoft.Exchange.WebServices.Data.Appointment.Bind(m_Service, meetingId, new PropertySet(AppointmentSchema.MyResponseType));
     if (meeting.MyResponseType == MeetingResponseType.Organizer)
     {
         meeting.CancelMeeting(cancelMessage);
     }
     else if (meeting.MyResponseType == MeetingResponseType.Accept || meeting.MyResponseType == MeetingResponseType.NoResponseReceived || meeting.MyResponseType == MeetingResponseType.Tentative)
     {
         var declineMessage = meeting.CreateDeclineMessage();
         declineMessage.Body = new MessageBody(cancelMessage);
         declineMessage.SendAndSaveCopy();
     }
 }
        private Appointment MakeAppointment(ExchangeAppointment appointmentItem)
        {
            Appointment newAppointment = appointmentItem == null
                ? null
                : new Appointment(
                    appointmentItem.Id.UniqueId,
                    appointmentItem.Start,
                    appointmentItem.End,
                    appointmentItem.Subject,
                    appointmentItem.Location,
                    appointmentItem.Organizer.Name,
                    appointmentItem.RequiredAttendees.Union(appointmentItem.OptionalAttendees).Select(a => a.Name));

            return newAppointment;
        }
Ejemplo n.º 13
0
        private Appointment MakeAppointment(ExchangeAppointment appointmentItem)
        {
            Appointment newAppointment = appointmentItem == null
                ? null
                : new Appointment(
                appointmentItem.Id.UniqueId,
                appointmentItem.Start,
                appointmentItem.End,
                appointmentItem.Subject,
                appointmentItem.Location,
                appointmentItem.Organizer.Name,
                appointmentItem.RequiredAttendees.Union(appointmentItem.OptionalAttendees).Select(a => a.Name));

            return(newAppointment);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Checks if Appointment includes other participants in addition to the organizer.
        /// </summary>
        /// <param name="exchangeItem">Exchange appointment instance.</param>
        /// <param name="syncItem">Remote storage item.</param>
        protected virtual bool HasAnotherAttendees(Exchange.Appointment exchangeItem)
        {
            string organizerAddress    = exchangeItem.Organizer.Address;
            bool   hasAnotherAttendees = false;

            foreach (Exchange.Attendee attendee in exchangeItem.RequiredAttendees)
            {
                if (!string.Equals(organizerAddress, attendee.Address, StringComparison.OrdinalIgnoreCase))
                {
                    hasAnotherAttendees = true;
                    break;
                }
            }
            return(hasAnotherAttendees);
        }
Ejemplo n.º 15
0
        private static void Add_Meeting(Appointment apt, SqlConnection conn)
        {
            string ID_Meeting = ((apt as Appointment).Id).ToString();
            string Subject = (apt as Appointment).Subject;
            string Location = (apt as Appointment).Location;
            DateTime StartTime = (apt as Appointment).Start;
            DateTime EndTime = (apt as Appointment).End;
            string Organizer_info = (apt as Appointment).Organizer.ToString();

            //Parsing organizer username and email
            string Organizer__info_parse = Organizer_info.Replace("<SMTP:", "").Replace(">", "");
            string[] Username_email = Organizer__info_parse.Split(' ');

            try
            {
                SqlCommand organizer = new SqlCommand("IF NOT EXISTS (SELECT * FROM Users WHERE Username = '******' AND Email = '" + Username_email[1] + "') BEGIN INSERT INTO Users (Email, Username) VALUES (@Email, @Username) END", conn);
                organizer.Parameters.AddWithValue("@Email", Username_email[1]); //Username_email[1] contains email
                organizer.Parameters.AddWithValue("@Username", Username_email[0]); //Username_email[0] contains username
                organizer.ExecuteNonQuery();

                SqlCommand Add_Organizer_Meeting_Attenders_Table = new SqlCommand("IF NOT EXISTS (SELECT * FROM Meeting_attenders WHERE User_Username = '******'" + "AND ID_Meting = '" + ID_Meeting + "') BEGIN INSERT INTO Meeting_attenders (ID_Meting, User_Username, Is_Required, Have_Evaluated, Is_Organizer) VALUES ('" + ID_Meeting + "', '" + Username_email[0] + "', 1, 0, 1) END", conn);
                Add_Organizer_Meeting_Attenders_Table.ExecuteNonQuery();

                SqlCommand Organizer_ID = new SqlCommand("SELECT ID_Attender FROM Meeting_Attenders WHERE ID_Meting = '" + ID_Meeting + "' AND Is_Organizer = 1", conn);
                int result = ((int)Organizer_ID.ExecuteScalar());
                //Console.WriteLine(result);

                SqlCommand Meeting = new SqlCommand("IF NOT EXISTS (SELECT * FROM Meetings WHERE ID_Meeting = '" + ID_Meeting + "') BEGIN INSERT INTO Meetings (ID_Meeting, Subject, Location, Start_time, End_time, Organizer) VALUES (@ID_Meeting, @Subject, @Location, @Start_time, @End_time, @Organizer) END", conn);
                Meeting.Parameters.AddWithValue("@ID_Meeting", ID_Meeting);
                Meeting.Parameters.AddWithValue("@Subject", Subject);
                Meeting.Parameters.AddWithValue("@Location", Location);
                Meeting.Parameters.AddWithValue("@Start_time", StartTime);
                Meeting.Parameters.AddWithValue("@End_time", EndTime);
                Meeting.Parameters.AddWithValue("@Organizer", result);
                Meeting.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Output_exceptions(ex);
            }
        }
Ejemplo n.º 16
0
 public void CreateAndSaveMeeting(Meeting m)
 {
     try
     {
         Appointment a = new Appointment(service);
         a.Subject = m.Title;
         a.Body = m.Description;
         a.Start = DataHelper.StringToDate(m.Start, DataHelper.DateStringLong);
         a.End = DataHelper.StringToDate(m.End, DataHelper.DateStringLong);
         a.Location = m.Location;
         foreach (string email in m.Invited)
         {
             a.RequiredAttendees.Add(email);
         }
         a.Save(SendInvitationsMode.SendToAllAndSaveCopy);
     }
     catch (Exception e)
     {
         throw new ServiceException("Cannot create meeting", e);
     }
 }
Ejemplo n.º 17
0
        private OutlookAppointment GetOutlookAppointment(Microsoft.Exchange.WebServices.Data.Appointment appointment, ExchangeService service)
        {
            OutlookAppointment newAppointment = new OutlookAppointment();

            PropertySet props = new PropertySet();

            props.Add(AppointmentSchema.Body);
            props.Add(AppointmentSchema.Subject);

            newAppointment.IsEWS       = true;
            newAppointment.Service     = service;
            newAppointment.Id          = appointment.Id.UniqueId;
            newAppointment.Subject     = appointment.Subject;
            newAppointment.Start       = appointment.Start;
            newAppointment.End         = appointment.End;
            newAppointment.AllDayEvent = appointment.IsAllDayEvent;
            newAppointment.Location    = appointment.Location;
            newAppointment.Organizer   = appointment.Organizer.ToString();
            newAppointment.ReminderMinutesBeforeStart = appointment.ReminderMinutesBeforeStart;
            newAppointment.ReminderSet = appointment.IsReminderSet;
            return(newAppointment);
        }
Ejemplo n.º 18
0
        public  bool CreateCalendarEvent(ExchangeService service,Appointment objAppointment,string[] rqdAttendeelist,string[] optionalAttendeelist)
        {          
            try
            {             

                ItemView itemView = new ItemView(100);
                itemView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
                List<Appointment> ToCreate = new List<Appointment>();
                Appointment appointment = new Appointment(service);
                appointment.Subject = objAppointment.Subject;// "Calendar Request from Console App";
                appointment.Location = objAppointment.Location;// "Office365";
                appointment.Start = TimeZoneInfo.ConvertTimeToUtc(objAppointment.Start, TimeZoneInfo.Local);
                appointment.End = TimeZoneInfo.ConvertTimeToUtc(objAppointment.End, TimeZoneInfo.Local);// objAppointment.End;
                appointment.Body = objAppointment.Body;
                appointment.IsReminderSet = objAppointment.IsReminderSet;           
                appointment.IsResponseRequested = false;
                foreach(string req in rqdAttendeelist)
                {
                    appointment.RequiredAttendees.Add(req);
                }
                foreach (string opt in optionalAttendeelist)
                {
                    appointment.OptionalAttendees.Add(opt);
                }
                ToCreate.Add(appointment);
                ServiceResponseCollection<ServiceResponse> CreateResponse = service.CreateItems(ToCreate, WellKnownFolderName.Calendar, MessageDisposition.SaveOnly, SendInvitationsMode.SendOnlyToAll);
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                service = null;
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// <see cref="ExchangeSyncProvider.EnumerateChanges"/>
        /// </summary>
        public override IEnumerable <IRemoteItem> EnumerateChanges(SyncContext context)
        {
            base.EnumerateChanges(context);
            FillFoldersList(context);
            var result = new List <IRemoteItem>();

            if (!UserSettings.ImportActivities)
            {
                return(result);
            }
            Exchange.SearchFilter itemsFilter = GetItemsSearchFilters(context);
            SyncItemSchema        schema      = FindSchemaBySyncValueName(typeof(ExchangeAppointment).Name);
            var needGetRecurringAppointments  = NeedGetRecurringAppointments(context);

            Exchange.PropertySet properties = new Exchange.PropertySet(Exchange.BasePropertySet.IdOnly);
            properties.AddRange(new[] {
                Exchange.ItemSchema.Subject,
                Exchange.ItemSchema.LastModifiedTime,
                Exchange.AppointmentSchema.Recurrence,
                Exchange.AppointmentSchema.IsRecurring,
                Exchange.AppointmentSchema.AppointmentType,
                Exchange.AppointmentSchema.ICalUid,
                Exchange.AppointmentSchema.ICalRecurrenceId,
                Exchange.AppointmentSchema.Start
            });
            foreach (Exchange.Folder folder in Folders)
            {
                bool hasRecurence = false;
                if (!needGetRecurringAppointments)
                {
                    foreach (Exchange.Item item in GetCalendarItems(folder, itemsFilter))
                    {
                        Exchange.Appointment appointment = ExchangeUtility.SafeBindItem <Exchange.Appointment>(Service, item.Id, properties);
                        if (appointment != null)
                        {
                            var recurentAppointment = GetExchangeRecurringAppointmentsSupported(context.UserConnection) && appointment.Recurrence != null;
                            var isRecurringMaster   = appointment.AppointmentType == Exchange.AppointmentType.RecurringMaster;
                            if ((!recurentAppointment || isRecurringMaster) && CheckItemInSyncPeriod(context, appointment))
                            {
                                context?.LogInfo(SyncAction.None, SyncDirection.Download, "Adding single or master appoitment {0}", appointment.Subject);
                                var remoteItem = CreateExchangeAppointment(schema, appointment, TimeZone);
                                context?.LogInfo(SyncAction.None, SyncDirection.Download, "Created ExchangeAppointment with Id {0}", remoteItem.Id);
                                if (isRecurringMaster)
                                {
                                    context?.LogInfo(SyncAction.None, SyncDirection.Download, "Adding master appoitment {0}", appointment.Subject);
                                    remoteItem.Action = SyncAction.CreateRecurringMaster;
                                }
                                result.Add(remoteItem);
                            }
                            hasRecurence = hasRecurence || recurentAppointment;
                        }
                    }
                }
                if (hasRecurence || needGetRecurringAppointments)
                {
                    foreach (Exchange.Item item in GetAppointmentsForPeriod(context, folder))
                    {
                        context?.LogInfo(SyncAction.None, SyncDirection.Download, "Input item - Subject {0}, UniqueId - {1}", item.Subject, item.Id.UniqueId);
                        Exchange.Appointment appointment = ExchangeUtility.SafeBindItem <Exchange.Appointment>(Service, item.Id, properties);
                        context?.LogInfo(SyncAction.None, SyncDirection.Download, "Adding recurence appoitment {0}", appointment.Subject);
                        if (appointment != null)
                        {
                            var remoteItem = CreateExchangeAppointment(schema, appointment, TimeZone);
                            context?.LogInfo(SyncAction.None, SyncDirection.Download, "Created recurence ExchangeAppointment with Id {0}", remoteItem.Id);
                            result.Add(remoteItem);
                        }
                    }
                }
            }
            context?.LogInfo(SyncAction.None, SyncDirection.Download, "loaded {0} items from Exchange", result.Count);
            return(result);
        }
Ejemplo n.º 20
0
 protected bool CheckItemInSyncPeriod(SyncContext context, Exchange.Appointment appointment)
 {
     return(!GetExchangeRecurringAppointmentsSupported(context.UserConnection) ||
            appointment.SafeGetValue <DateTime>(Exchange.AppointmentSchema.Start) > UserSettings.ImportActivitiesFrom);
 }
Ejemplo n.º 21
0
        private void bindTasks(DateTime fromDate, DateTime toDate)
        {
            List <LeadTask> tasks = null;

            Expression <Func <CRM.Data.Entities.Task, bool> > predicate = PredicateBuilder.True <CRM.Data.Entities.Task>();

            if (roleID == (int)UserRole.Administrator)
            {
            }
            else if ((roleID == (int)UserRole.Client || roleID == (int)UserRole.SiteAdministrator) && clientID > 0)
            {
                // load all tasks for client (sort of admin)

                predicate = predicate.And(LeadTask => LeadTask.creator_id == clientID);

                predicate = predicate.And(LeadTask => LeadTask.start_date >= fromDate && LeadTask.end_date <= toDate);

                // get overdue task for client
                predicate = predicate.Or(LeadTask => LeadTask.status_id == 1 && LeadTask.end_date <= toDate && LeadTask.creator_id == clientID);
            }
            else
            {
                // regular users

                predicate = predicate.And(LeadTask => LeadTask.start_date >= fromDate && LeadTask.end_date <= toDate);

                predicate = predicate.And(LeadTask => LeadTask.owner_id == userID);
            }

            tasks = TasksManager.GetLeadTask(predicate, fromDate, toDate);

            if (rbOn.Checked)
            {
                userID = SessionHelper.getUserId();

                CRM.Data.Entities.SecUser secUser = SecUserManager.GetByUserId(userID);
                string emailaddress = secUser.Email;
                string password     = SecurityManager.Decrypt(secUser.emailPassword);
                string url          = "https://" + secUser.emailHost + "/EWS/Exchange.asmx";

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(emailaddress, password);
                service.Url         = new Uri(url);

                try
                {
                    TasksFolder tasksfolder = TasksFolder.Bind(service, WellKnownFolderName.Tasks);

                    ItemView view = new ItemView(int.MaxValue);
                    FindItemsResults <Item> OutlookTasks = tasksfolder.FindItems(view);

                    CalendarView calView = new CalendarView(fromDate, toDate);

                    FindItemsResults <Item> instanceResults = service.FindItems(WellKnownFolderName.Calendar, calView);

                    foreach (var item in instanceResults)
                    {
                        LeadTask newTask = new LeadTask();
                        Microsoft.Exchange.WebServices.Data.Appointment appointment = item as Microsoft.Exchange.WebServices.Data.Appointment;

                        newTask.creator_id = userID;
                        newTask.details    = appointment.Subject;
                        newTask.end_date   = appointment.End;
                        newTask.isAllDay   = appointment.IsRecurring;
                        newTask.text       = appointment.Subject;

                        newTask.priorityName = appointment.Importance.ToString();
                        newTask.owner_name   = appointment.Organizer.Name;
                        newTask.start_date   = appointment.Start;

                        tasks.Add(newTask);
                    }

                    foreach (var task in OutlookTasks)
                    {
                        task.Load();
                        Microsoft.Exchange.WebServices.Data.Task myTask = task as Microsoft.Exchange.WebServices.Data.Task;

                        LeadTask newTask = new LeadTask();
                        newTask.creator_id   = userID;
                        newTask.details      = ExtractHtmlInnerText(myTask.Body.Text);
                        newTask.end_date     = myTask.DueDate;
                        newTask.isAllDay     = myTask.IsRecurring;
                        newTask.text         = myTask.Subject;
                        newTask.statusName   = myTask.Status.ToString();
                        newTask.priorityName = myTask.Importance.ToString();
                        newTask.owner_name   = myTask.Owner;
                        if (myTask.StartDate == null)
                        {
                            newTask.start_date = myTask.DueDate;
                        }
                        else
                        {
                            newTask.start_date = myTask.StartDate;
                        }

                        tasks.Add(newTask);
                    }
                }
                catch (Exception ex)
                {
                }
            }
            // show tasks
            gvTasks.DataSource = tasks;
            gvTasks.DataBind();
        }
Ejemplo n.º 22
0
		public Task<bool> ReserveRoom(RoomInfo room, TimeSpan duration)
		{
			Appointment appointment = new Appointment(_service);

			// Set the properties on the appointment object to create the appointment.
			appointment.Subject = "Room reservation";
			appointment.Body = $"Automatically created by FindMeRoomOSS on {DateTime.Now}";
			appointment.Start = DateTime.Now;
			appointment.End = appointment.Start + duration;
			appointment.Location = room.RoomId;
			appointment.RequiredAttendees.Add(room.RoomId);

			// Save the appointment to your calendar.
			appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);

			PropertySet psPropSet = new PropertySet(BasePropertySet.FirstClassProperties);

			// Verify that the appointment was created by using the appointment's item ID.
			appointment = Item.Bind(_service, appointment.Id, psPropSet) as Appointment;
			if (appointment == null)
			{
				return Task.FromResult(false);
			}
			return Task.Run(async () =>
				{
					var finishTime = DateTime.Now + CreationTimeout;
					Attendee roomAttendee;
					// wait till the room accepts
					do
					{
						Debug.WriteLine("Waiting for response...");
						await Task.Delay(1000);

						// refresh appointment data
						appointment = Item.Bind(_service, appointment.Id, psPropSet) as Appointment;
						if (appointment == null)
						{
							Debug.WriteLine("Appointment has been deleted");
							return false;
						}
						roomAttendee = appointment.RequiredAttendees.FirstOrDefault(att => att.Address == room.RoomId);
						if (roomAttendee == null)
						{
							Debug.WriteLine("Someone is messing with our appointment");
							return false;
						}
					} while (DateTime.Now < finishTime && (
							!roomAttendee.ResponseType.HasValue ||
							roomAttendee.ResponseType == MeetingResponseType.Unknown ||
							roomAttendee.ResponseType == MeetingResponseType.NoResponseReceived
						));
					Debug.WriteLine($"Response is {roomAttendee.ResponseType}...");
					return roomAttendee.ResponseType.HasValue && roomAttendee.ResponseType.Value == MeetingResponseType.Accept;
				});
		}
Ejemplo n.º 23
0
        public string AddCalendar(string strOppID)
        {
            SLXapi.Opportunity slxOpp = SLXapi.Opportunity.GetByID(strOppID);

            if ((int)SLXapi.Helpers.Events.EventTypes.PSLevelTwoTraining == slxOpp.TypeID)
                return AddLevel2Calendar(strOppID);

            string strEntryID = slxOpp.OutlookID;

            ExchangeService service = GetExchangeService(EMAIL, PWD);
            //service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "*****@*****.**");

            var userMailbox = new Mailbox(CALENDAR_EMAIL);
            FolderId folderId = new FolderId(WellKnownFolderName.Calendar, userMailbox);

            //Folder calendarFolder = Folder.Bind(service, folderId);
            //var itemView = new ItemView(20);   // page size
            //var userItems = service.FindItems(folderId, itemView);

            bool apptExists = false;

            // Verify that the appointment was created by using the appointment's item ID.
            Appointment appt = null;
            try
            {
                ItemId idObj = new ItemId(strEntryID);
                appt = Appointment.Bind(service, idObj, new PropertySet(AppointmentSchema.Id, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End));
                if (appt.Id.UniqueId == strEntryID)
                    apptExists = true;
            }
            catch (Exception)
            {

            }

            //get the trainers initials
            string trainerInitials = string.Empty;
            try
            {
                List<SLXapi.Opportunity_Trainers> oppT = SLXapi.Opportunity_Trainers.GetByOpportunityID(slxOpp.OpportunityID);

                //create the opp trainer initial string

                if (oppT.Count > 0)
                    trainerInitials += "(";
                for (int i = 0; i < oppT.Count; ++i)
                {
                    SLXapi.Contact contact = SLXapi.Contact.GetByID(oppT[i].contactid);
                    if (contact != null)
                    {
                        string initials = contact.firstname[0].ToString().ToUpper() + contact.lastname[0].ToString().ToUpper();
                        trainerInitials += initials;
                        if (i + 1 < oppT.Count)
                            trainerInitials += ",";
                    }

                }
                if (oppT.Count > 0)
                    trainerInitials += ")";
            }
            catch (System.Exception e)
            {
                return "There was an exception adding the trainer initials " + e.Message;
            }
            if (appt == null)
                appt = new Appointment(service);

            if (!apptExists)
                slxOpp.OutlookBodyText = "http://fogbugz.askpri.org/default.asp?" + slxOpp.FogBugzMainTicket;
            appt.Subject = slxOpp.Type + " - " + slxOpp.Location + " " + trainerInitials;

            appt.Body = slxOpp.OutlookBodyText;
            appt.Location = slxOpp.Location;
            appt.Start = slxOpp.StartDate;

            appt.End = slxOpp.EndDate;
            appt.IsAllDayEvent = true;
            appt.IsReminderSet = false;
            appt.ReminderMinutesBeforeStart = 0;
            appt.Importance = Importance.Normal;
            appt.LegacyFreeBusyStatus = LegacyFreeBusyStatus.Free;
            try
            {
                if (apptExists)
                    appt.Update(ConflictResolutionMode.AutoResolve);
                else
                    appt.Save(folderId);
            }
            catch (COMException ex)
            {
                Console.WriteLine(ex.ToString());
                return "There was an exception when saving appointment " + ex.Message;
            }

            Item item = Item.Bind(service, appt.Id, new PropertySet(ItemSchema.Subject));
            Console.WriteLine("Retrieved Appointment: " + item.Subject + "\n");

            //save the outlook appointment id to SLX Opportunity
            slxOpp.OutlookID = appt.Id.UniqueId;
            SLXapi.Opportunity.Save(slxOpp);

            return "Successfully Added to Outlook Calendar";
        }
        public void StartNewMeeting(string roomAddress, string securityKey, string title, int minutes)
        {
            if (_securityRepository.GetSecurityRights(roomAddress, securityKey) != SecurityStatus.Granted)
            {
                throw new UnauthorizedAccessException();
            }
            var status = GetStatus(roomAddress);
            if (status.Status != RoomStatus.Free)
            {
                throw new Exception("Room is not free");
            }

            using (_concurrencyLimiter.StartOperation())
            {
                var calId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(roomAddress));

                var now = _dateTimeService.Now.TruncateToTheMinute();
                minutes = Math.Max(0, Math.Min(minutes, Math.Min(120, status.NextMeeting.ChainIfNotNull(m => (int?)m.Start.Subtract(now).TotalMinutes) ?? 120)));

                var appt = new Appointment(_exchangeService);
                appt.Start = now;
                appt.End = now.AddMinutes(minutes);
                appt.Subject = title;
                appt.Body = "Scheduled via conference room management system";
                appt.Save(calId, SendInvitationsMode.SendToNone);
                log.DebugFormat("Created {0} for {1}", appt.Id.UniqueId, roomAddress);

                _meetingRepository.StartMeeting(appt.Id.UniqueId);
                BroadcastUpdate(roomAddress);
            }
        }
Ejemplo n.º 25
0
        /**
         * Function Add the Holidays
         **/
        static void AddHolidays(ExchangeService service, List<string[]> holidays, List<string> mailboxes)
        {
            // Log file
            string datetimeString = DateTime.Now.ToString("MMddyyyy");
            string logfile = "../../logs/" + datetimeString + "_add_holiday_log.txt";

            //Initiate Error List
            List<string> mbs = new List<string>();

            using (System.IO.StreamWriter log = new System.IO.StreamWriter(@logfile, true))
            {

                // Loop through each email address in the passed in mailboxes List
                foreach (string mailbox in mailboxes)
                {

                    // Impersonate that User
                    service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailbox);
                    Console.WriteLine("Attempting to Add Holidays to: " + mailbox);

                    List<Appointment> uga_holidays = new List<Appointment>();

                    // Loop through all the holidays
                    foreach (string[] holiday in holidays)
                    {

                        //Create a new appointment
                        Appointment appointment = new Appointment(service);

                        // Set details
                        appointment.Subject = holiday[0];
                        appointment.Start = DateTime.Parse(holiday[1]);
                        appointment.End = appointment.Start.AddDays(1);
                        appointment.IsAllDayEvent = true;
                        StringList categories = new Microsoft.Exchange.WebServices.Data.StringList();
                        categories.Add("Holiday");
                        appointment.Categories = categories;
                        appointment.IsReminderSet = false;

                        uga_holidays.Add(appointment);

                    }

                    // Save and Send
                    try
                    {
                        service.CreateItems(uga_holidays, WellKnownFolderName.Calendar, MessageDisposition.SaveOnly, SendInvitationsMode.SendToNone);
                        Console.WriteLine("Added Holiday Successfully to: " + mailbox);

                        DateTime now = DateTime.Now;
                        log.WriteLine(now + " - Added holidays succesfully to Mailbox: " + mailbox);

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error During Initial Add - Mailbox: " + mailbox + "; Exception thrown: " + ex);
                        log.WriteLine("Error During Initial Add - Mailbox: " + mailbox + "; Exception thrown: " + ex);
                        mbs.Add(mailbox);

                    }

                    // Clear impersonation.
                    service.ImpersonatedUserId = null;

                }

                //Process Rerun List
                if (mbs.Count > 0)
                {
                    Console.WriteLine("Looping through re-run mailboxes.");

                    while (mbs.Count > 0)
                    {
                        // Current mailbox
                        string mb = mbs.ElementAt(0);
                        Console.WriteLine("On Mailbox: " + mb);

                        // Take the mailbox out of the first element slot
                        log.WriteLine("Removing mailbox " + mb + " from beginning of mbs.");
                        mbs.RemoveAt(0);
                        mbs.TrimExcess();

                        try
                        {
                            // Reruns: Removes
                            // Run search
                            // Impersonate that User
                            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mb);

                            // Search String
                            String category = "Holiday";
                            // Search Filter
                            SearchFilter.IsEqualTo filter = new SearchFilter.IsEqualTo(AppointmentSchema.Categories, category);

                            // Result Return Size, number of items
                            ItemView holidayView = new ItemView(100);
                            // Limit data to only necesary components
                            holidayView.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Categories);

                            FindItemsResults<Item> items = service.FindItems(WellKnownFolderName.Calendar, filter, holidayView);

                            if (items.TotalCount > 0)
                            {

                                Console.WriteLine("Removing " + items.TotalCount + " holidays from " + mb);
                                log.WriteLine("Found " + items.TotalCount + " holidays in the Calendar folder for " + mb + " to be removed.");

                                List<ItemId> ids = new List<ItemId>();
                                foreach (Item item in items)
                                {

                                    ids.Add(item.Id);

                                }

                                service.DeleteItems(ids, DeleteMode.MoveToDeletedItems, null, null);

                            }
                            else
                            {
                                log.WriteLine("Found no holidays in the Calendar folder for " + mb + " to be removed.");
                            }

                            // Rerun: Adds

                            List<Appointment> holidays = new List<Appointment>();

                            // Loop through all the holidays
                            foreach (string[] holiday in holidays)
                            {

                                //Create a new appointment
                                Appointment appointment = new Appointment(service);

                                // Set details
                                appointment.Subject = holiday[0];
                                appointment.Start = DateTime.Parse(holiday[1]);
                                appointment.End = appointment.Start.AddDays(1);
                                appointment.IsAllDayEvent = true;
                                StringList categories = new Microsoft.Exchange.WebServices.Data.StringList();
                                categories.Add("Holiday");
                                appointment.Categories = categories;
                                appointment.IsReminderSet = false;

                                holidays.Add(appointment);

                            }

                            service.CreateItems(holidays, null, null, SendInvitationsMode.SendToNone);
                            Console.WriteLine("Added Holiday Successfully to" + mb);
                            DateTime now = DateTime.Now;
                            log.WriteLine(now + " - Added holidays succesfully to Mailbox: " + mb);

                        }
                        catch
                        {
                            log.WriteLine("Fatal Mailbox Errored on Re-Run Removes: " + mb + "; Will not retry.");
                            Console.WriteLine("Fatal Mailbox Errored on Re-Run Removes: " + mb + "; Will not retry.");
                        }

                        // Clear impersonation.
                        service.ImpersonatedUserId = null;

                    }
                }
            }
        }
Ejemplo n.º 26
0
Archivo: Event.cs Proyecto: ozgend/hive
 private List<Person> GetPersons(Appointment a)
 {
     List<Person> list = new List<Person>();
     List<Attendee> all = new List<Attendee>(a.RequiredAttendees);
     all.AddRange(a.OptionalAttendees);
     foreach (Attendee at in all)
     {
         list.Add(new Person(at));
     }
     return list;
 }
 private void SendEmail(Appointment item, string subject, string body)
 {
     var msg = new EmailMessage(_exchangeService);
     msg.Subject = subject;
     msg.Body = body;
     log.DebugFormat("Address: {0}, MailboxType: {1}", item.Organizer.Address, item.Organizer.MailboxType);
     if (item.Organizer.MailboxType == MailboxType.Mailbox)
     {
         msg.ToRecipients.Add(item.Organizer);
     }
     foreach (var x in item.RequiredAttendees.Concat(item.OptionalAttendees))
     {
         log.DebugFormat("Address: {0}, MailboxType: {1}, RoutingType: {2}", x.Address, x.MailboxType, x.RoutingType);
         if (x.RoutingType == "SMTP" && x.Address.EndsWith("@rightpoint.com"))
         {
             log.DebugFormat("Also sending to {0} @ {1}", x.Name, x.Address);
             msg.CcRecipients.Add(x.Name, x.Address);
         }
     }
     msg.Send();
 }
        public IHttpActionResult Create(CreateAppointmentRequest request)
        {
            var service = ExchangeServer.Open();
            var appointment = new Appointment(service);

            // Set the properties on the appointment object to create the appointment.
            appointment.Subject = request.Subject;
            appointment.Body = request.Body;
            appointment.Start = DateTime.Parse(request.Start);
            //appointment.StartTimeZone = TimeZoneInfo.Local;
            appointment.End = DateTime.Parse(request.End);
            //appointment.EndTimeZone = TimeZoneInfo.Local;
            appointment.Location = request.Location;
            //appointment.ReminderDueBy = DateTime.Now;

            foreach(var email in request.Recipients)
            {
                appointment.RequiredAttendees.Add(email);
            }

            // Save the appointment to your calendar.
            appointment.Save(SendInvitationsMode.SendOnlyToAll);

            // Verify that the appointment was created by using the appointment's item ID.
            Item item = Item.Bind(service, appointment.Id, new PropertySet(ItemSchema.Subject));

            var response = new CreateAppointmentResponse
            {
                Message = "Appointment created: " + item.Subject,
                AppointId = appointment.Id.ToString()
            };

            return Ok(response);
        }
        public string CreateNewAppointmentE(string subject_, string StartDate_,string finisDate_,string body_,string location_, List<string> attendees_)
        {
            string errorAppointment = "";
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.UseDefaultCredentials = true;
                service.Credentials = new WebCredentials("XXXXXXXXX", "XXXXX", "XXXX");//@uanl.mx
                service.AutodiscoverUrl("*****@*****.**");

                Appointment appointment = new Appointment(service);
                appointment.Subject = subject_;
                appointment.Body = body_;
                appointment.Start = Convert.ToDateTime(StartDate_);
                appointment.End = Convert.ToDateTime(finisDate_);
                appointment.Location = location_;

                foreach (string attendee in attendees_)
                appointment.RequiredAttendees.Add(attendee);

                appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);

                return errorAppointment;
            }
            catch
            {
                return errorAppointment = "an error trying to send the appoitment happend" ;
            }
        }
Ejemplo n.º 30
0
        private Appointment CreateExchangeCalendarEvent(string subject, string body, DateTime start, DateTime end)
        {
            var userCredential = GetExchangeUserCredential();
            var exchangeService = _microsoftExchangeServiceProvider.GetMicrosoftExchangeService(userCredential);
            var isDefaultCalendarExist = false;
            var defaultCalendar = DependencyResolver.Resolve<IExchangeCalendarEventSyncDataService>().GetDefaultCalendarFolder(userCredential, out isDefaultCalendarExist);

            Appointment appointment = new Appointment(exchangeService);

            appointment.Subject = subject;
            appointment.Body = new MessageBody(BodyType.Text, body);
            appointment.Start = start;
            appointment.End = end;

            appointment.Save(defaultCalendar.Id);

            appointment = GetExchangeCalendarEvent(appointment.Id.UniqueId);

            return appointment;
        }
Ejemplo n.º 31
0
 private void AssertTaskAndExchangeCalendarEventAreEqual(CooperTask cooperTask, Appointment appointment)
 {
     MicrosoftAssert.AreEqual(cooperTask.Subject, appointment.Subject);
     MicrosoftAssert.AreEqual(BodyType.Text, appointment.Body.BodyType);
     MicrosoftAssert.AreEqual(cooperTask.Body, appointment.Body.Text);
     MicrosoftAssert.AreEqual(cooperTask.DueTime.Value.Date, appointment.End.Date);
     MicrosoftAssert.AreEqual(FormatTime(cooperTask.LastUpdateTime), FormatTime(appointment.LastModifiedTime));
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Returns true if <see cref="Microsoft.Exchange.WebServices.Data.Appointment"/> must be saved
        /// without participants notifications.</summary>
        /// <param name="exchangeAppointment">Exchange appointment instance.</param>
        /// <param name="exchangeItem">Exchange item instance.</param>
        /// <returns>Dont send notifications flag.</returns>
        public bool GetDontSendNotifications(ExchangeAppointment exchangeAppointment, Exchange.Appointment exchangeItem)
        {
            SyncAction action = exchangeAppointment.Action;

            return(!(exchangeAppointment.SendNotifications &&
                     (action == SyncAction.Create || HasAnotherAttendees(exchangeItem))
                     ));
        }
 private static Meeting BuildMeeting(Appointment i, MeetingInfo meetingInfo)
 {
     return new Meeting
     {
         UniqueId = i.Id.UniqueId,
         Subject = i.Sensitivity != Sensitivity.Normal ? i.Sensitivity.ToString() :
             i.Subject.Trim() == i.Organizer.Name.Trim() ? null : i.Subject,
         Start = i.Start,
         End = i.End,
         Organizer = i.Organizer.Name,
         IsStarted = meetingInfo.IsStarted,
         IsEndedEarly = meetingInfo.IsEndedEarly,
         IsCancelled = meetingInfo.IsCancelled,
         IsNotManaged = i.IsAllDayEvent || Math.Abs(i.End.Subtract(i.Start).TotalHours) > 6, // all day events and events longer than 6 hours won't be auto-cancelled
     };
 }
 public void ResetAppointmentObject()
 {
     appt = new Appointment(service);
 }
 public ExchangeCalendarEventSyncData(Appointment exchangeCalendarEvent)
 {
     ExchangeCalendarEvent = exchangeCalendarEvent;
     IsFromDefault = true;
 }
Ejemplo n.º 36
0
        /**
         * Function: CreateNewAppointment
         * Creates a new appointment.
         * Returns the AppID (appointment id) for future changes
         **/
        static string CreateNewAppointment(ExchangeService service, string subject, string body, DateTime date, int duration, string status)
        {
            Console.WriteLine("Creating a New Item: " + subject);

            // Create an appointmet and identify the Exchange service.
            Appointment appointment = new Appointment(service);

            // Set details
            appointment.Subject = subject;
            appointment.Body = body;
            appointment.Start = date;
            appointment.End = appointment.Start.AddHours(duration);
            StringList categories = new Microsoft.Exchange.WebServices.Data.StringList();
            categories.Add(status);
            appointment.Categories = categories;
            appointment.IsReminderSet = false;

            // Save and Send
            appointment.Save(SendInvitationsMode.SendToNone);

            // Get ItemId for future updates
            return ""+appointment.Id+"";
        }
        /// <summary>
        /// Copy an Exchange appointment into an iCal event.
        /// </summary>
        /// <param name="ExchangeAppointment">Exchange appointment object to copy</param>
        public void AddEventToCalendar(Appointment ExchangeAppointment)
        {
            // Create a new event
            Event iCalEvent = miCalObject.Create<Event>();

            // Set the event properties
            iCalEvent.Summary = ExchangeAppointment.Subject.Replace("–", "-");      //Note: the replace replaces Word's "long dash"
            iCalEvent.Description = ExchangeAppointment.Subject.Replace("–", "-");  //      with a normal dash
            iCalEvent.Start = new iCalDateTime(ExchangeAppointment.Start);
            iCalEvent.End = new iCalDateTime(ExchangeAppointment.End);
            iCalEvent.Duration = ExchangeAppointment.Duration;
            iCalEvent.Location = ExchangeAppointment.Location;

            // TODO : Set Timezone

            // Output details for debug purposes
            //Console.WriteLine(string.Format("Subject: {0}\n Start Date: {1}\tEnd Date: {2}\nDuration: {3}\nLocation: {4}\n\n",
            //                ExchangeAppointment.Subject, ExchangeAppointment.Start, ExchangeAppointment.End, ExchangeAppointment.Duration,
            //                ExchangeAppointment.Location ?? "Not Set"));

            //Console.WriteLine();
        }