Exemplo n.º 1
0
        /// <summary>
        /// Loads all of today's sticky entries.
        /// </summary>
        /// <seealso cref="FetchUpcomingEvents"/>
        /// <seealso cref="IsSticky"/>
        private void FetchStickyEntries()
        {
            CalendarFolder calendar = CalendarFolder.Bind(_exchange, WellKnownFolderName.Calendar);
            CalendarView   view     = new CalendarView(DateTime.Today, DateTime.Today.Add(_latestEndForStickyEvents))
            {
                PropertySet = new PropertySet(ItemSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Location, AppointmentSchema.MyResponseType, AppointmentSchema.IsAllDayEvent)
            };
            FindItemsResults <Appointment> appointments = calendar.FindAppointments(view);

            StickyEvents = appointments
                           .Where(IsSticky)
                           .Select(ConvertToEvent)
                           .Where(x => x.ZoomId != default)
                           .OrderBy(x => x.Subject)
                           .ThenBy(x => x.MeetingResponseOrder)
                           .ThenBy(x => x.Start)
                           .ThenBy(x => x.End)
                           .ToList()
                           .AsReadOnly();
        }
Exemplo n.º 2
0
        public AppointmentRepository()
        {
            var _service = new ExchangeService
            {
                UseDefaultCredentials = true
            };

            _service.AutodiscoverUrl(_userToImpersonate);

            var folderId = new FolderId(WellKnownFolderName.Calendar, _userWhoSharedCalendar);

            _calendarFolder = CalendarFolder.Bind(_service, folderId);
            _calendarView   = new CalendarView(_daysBefore, _daysAfter)
            {
                PropertySet = new PropertySet(
                    AppointmentSchema.Subject,
                    AppointmentSchema.Start,
                    AppointmentSchema.Duration)
            };
        }
Exemplo n.º 3
0
        public Calendar(ExchangeService instance, DateTime start, DateTime end)
        {
            _currentView    = new CalendarView(start, end);
            _calendarFolder = CalendarFolder.Bind(instance, WellKnownFolderName.Calendar);

            Events = new List <ExistingCalendarEvent>();

            var events       = _calendarFolder.FindAppointments(_currentView);
            var meetings     = new List <Appointment>();
            var appointments = new List <Appointment>();

            var propertySet = new PropertySet(BasePropertySet.FirstClassProperties);

            propertySet.RequestedBodyType = BodyType.Text;

            foreach (var item in events)
            {
                item.Load(propertySet);
                Events.Add(new ExistingCalendarEvent(item));
            }
        }
Exemplo n.º 4
0
        private void btnGetMeetingList_Click(object sender, EventArgs e)
        {
            initialMeetingList();
            CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar);
            CalendarView   cView    = new CalendarView(DateTime.Now.AddMonths(-6), DateTime.Now.AddYears(1), int.MaxValue);

            FindItemsResults <Appointment> appointments = calendar.FindAppointments(cView);
            var items = appointments.Items.OrderByDescending(x => x.DateTimeReceived);

            this.listViewMeeting.View = View.Details;
            this.listViewMeeting.Items.Clear();
            foreach (Appointment item in items)
            {
                var listViewItem = new ListViewItem(new[] { item.Id.UniqueId, item.Organizer.Name, item.DisplayTo, item.Subject, item.DateTimeReceived.ToString(), item.MyResponseType.ToString() });
                this.listViewMeeting.Items.Add(listViewItem);
            }

            GetReminders();
            this.txtLogForMeeting.Text = "Get meeting list success\r\nEWS API:CalendarFolder.Bind\r\nLocation:..\\EWS\\EWS\\Form1.cs line(112, 116, 132, 136)\r\n" +
                                         "EWS API:FindAppointments\r\nLocation:..\\EWS\\EWS\\Form1.cs line(112, 116, 132, 136)\r\n\r\n";
        }
Exemplo n.º 5
0
        public IHttpActionResult GetDetails(GetAppointmentsRequest request)
        {
            var startDate = DateTime.Parse(request.Start);
            var endDate   = DateTime.Parse(request.End);
            // Assuming 8 max per day * 5 (days/week) * 4 (weeks/month)
            const int NUM_APPTS = 160;
            var       calendar  = CalendarFolder.Bind(ExchangeServer.Open(), WellKnownFolderName.Calendar, new PropertySet());
            var       cView     = new CalendarView(startDate, endDate, NUM_APPTS);

            cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.TimeZone);



            FindItemsResults <Appointment> appointments = calendar.FindAppointments(cView);

            var response = new GetAppointmentsResponse();
            var list     = new List <Interview>();

            foreach (var app in appointments)
            {
                var appointment = Appointment.Bind(ExchangeServer.Open(), app.Id);

                var attendees = new List <RequiredAttendees>();
                foreach (var required in appointment.RequiredAttendees)
                {
                    attendees.Add(new RequiredAttendees
                    {
                        Name     = required.Name,
                        Email    = required.Address,
                        Response = required.ResponseType.ToString()
                    });
                }

                list.Add(new Interview {
                    Start = app.Start, End = app.End, TimeZone = app.TimeZone, Attendees = attendees, Subject = app.Subject
                });
            }
            response.Appointments = list;
            return(Ok(response));
        }
        public IEnumerable <Meeting> GetUpcomingAppointmentsForRoom(string roomAddress)
        {
            var isTracked = _changeNotificationService.IsTrackedForChanges(roomAddress);

            using (_concurrencyLimiter.StartOperation())
            {
                return(_meetingCacheService.GetUpcomingAppointmentsForRoom(roomAddress, isTracked, () =>
                {
                    return Task.Run(() =>
                    {
                        try
                        {
                            var calId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(roomAddress));
                            var cal = CalendarFolder.Bind(_exchangeService, calId);
                            var apt = cal.FindAppointments(new CalendarView(_dateTimeService.Now.Date, _dateTimeService.Now.Date.AddDays(2))).ToList();
                            log.DebugFormat("Got {0} appointments for {1} via {2} with {3}", apt.Count, roomAddress, _exchangeService.GetHashCode(), _exchangeService.CookieContainer.GetCookieHeader(_exchangeService.Url));
                            if (_ignoreFree)
                            {
                                apt = apt.Where(i => i.LegacyFreeBusyStatus != LegacyFreeBusyStatus.Free).ToList();
                            }
                            var meetings = _meetingRepository.GetMeetingInfo(apt.Select(i => i.Id.UniqueId).ToArray()).ToDictionary(i => i.Id);
                            return apt.Select(i => BuildMeeting(i, meetings.TryGetValue(i.Id.UniqueId) ?? new MeetingInfo()
                            {
                                Id = i.Id.UniqueId
                            })).ToArray().AsEnumerable();
                        }
                        catch (ServiceResponseException ex)
                        {
                            if (ex.ErrorCode == ServiceError.ErrorFolderNotFound || ex.ErrorCode == ServiceError.ErrorNonExistentMailbox || ex.ErrorCode == ServiceError.ErrorAccessDenied)
                            {
                                log.DebugFormat("Access denied ({0}) getting appointments for {1}", ex.ErrorCode, roomAddress);
                                throw new AccessDeniedException("Folder/mailbox not found or access denied", ex);
                            }
                            log.DebugFormat("Unexpected error ({0}) getting appointments for {1}", ex.ErrorCode, roomAddress);
                            throw;
                        }
                    });
                }).Result);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Sucht alle Termine von Heute bis 31.12. nächstes Jahr die die Kategorie "autogenerated by Arges IT"
        /// und im Subject entweder "Geburtstag von " oder "Jahrestag von " + übergebener Name stehen haben und löscht diese.
        /// </summary>
        /// <param name="name">Der Name des Kontaktes, dessen Geburtstag und Jahrestag gesucht wird.</param>
        public void deleteName(string name)
        {
            // Initialize values for the start and end times, and the number of appointments to retrieve.
            DateTime startDate = DateTime.Now;
            var      yearStr   = startDate.AddYears(1);
            var      yearStr2  = "12/31/" + yearStr.Year.ToString();
            DateTime endDate   = DateTime.ParseExact(yearStr2, "MM/dd/yyyy", CultureInfo.InvariantCulture);
            // Initialize the calendar folder object with only the folder ID.
            CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
            // Set the start and end time and number of appointments to retrieve.
            CalendarView cView = new CalendarView(startDate, endDate, 500);

            // Limit the properties returned to the appointment's subject, start time, and end time.
            cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Categories);
            // Retrieve a collection of appointments by using the calendar view.
            //FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);

            //Läuft über alle Kalendereinträge
            FindItemsResults <Appointment> appointments;
            var total = 0;

            do
            {
                appointments = calendar.FindAppointments(cView);

                //Läuft über alle Kalendereinträge
                foreach (Appointment a in appointments)
                {
                    if (a.Categories.Contains("autogenerated by Arges IT") && (a.Subject.Contains("Geburtstag von " + name) || a.Subject.Contains("Jahrestag von " + name)))
                    {
                        a.Delete(DeleteMode.HardDelete);
                    }
                }

                cView.StartDate = appointments.Items[appointments.Items.Count - 1].Start;
                total          += appointments.Items.Count;
            } while (appointments.MoreAvailable);

            //ExchangeSync.writeLog(SMTPAdresse + " - Geburtstage und Jahrestage von " + name + " wegen löschung in PublicFolder gelöscht");
        }
Exemplo n.º 8
0
        /// <summary>
        /// Rechaza un Appointment
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="password"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="id"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public string DeclineAppointment(string userId, string password, string id, string mess)
        {
            try
            {
                Console.WriteLine("Init");
                service             = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                credentials         = new WebCredentials(userId, password);
                service.Credentials = credentials;
                service.Url         = new Uri("https://mail.migesa.com.mx/ews/exchange.asmx");

                DateTime startDate = DateTime.Now.AddMonths(-6);
                DateTime endDate   = DateTime.Now.AddMonths(6);
                // Initialize the calendar folder object with only the folder ID.
                CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());

                // Set the start and end time and number of appointments to retrieve.
                CalendarView cView = new CalendarView(startDate, endDate);

                // Limit the properties returned to the appointment's subject, start time, and end time.
                cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);

                // Retrieve a collection of appointments by using the calendar view.
                FindItemsResults <Microsoft.Exchange.WebServices.Data.Appointment> appointments = calendar.FindAppointments(cView);
                negocio.Entidades.Appointment appoint = null;
                foreach (Microsoft.Exchange.WebServices.Data.Appointment a in appointments)
                {
                    a.Load();
                    if (a.Id.ToString() == id)
                    {
                        a.Decline(true);
                    }
                }
                return("");
            }
            catch (Exception ex)
            {
                exchangeInitialized = false;
                return(ex.Message);
            }
        }
Exemplo n.º 9
0
 // Token: 0x06002FD2 RID: 12242 RVA: 0x00116930 File Offset: 0x00114B30
 private static void GetConflictingAppointments(Infobar infobar, CalendarItemBase calendarItemBase, UserContext userContext)
 {
     if (Utilities.IsPublic(calendarItemBase))
     {
         return;
     }
     using (CalendarFolder calendarFolder = CalendarFolder.Bind(calendarItemBase.Session as MailboxSession, DefaultFolderType.Calendar))
     {
         AdjacencyOrConflictInfo[] adjacentOrConflictingItems = calendarFolder.GetAdjacentOrConflictingItems(calendarItemBase);
         if (adjacentOrConflictingItems != null && adjacentOrConflictingItems.Length != 0)
         {
             if (Utilities.IsOtherMailbox(calendarItemBase))
             {
                 CalendarUtilities.AddConflictingAppointmentsInfobarMessage(infobar, adjacentOrConflictingItems, userContext, calendarItemBase.CalendarItemType, Utilities.GetMailboxOwnerDisplayName((MailboxSession)calendarItemBase.Session), OwaStoreObjectId.CreateFromStoreObject(calendarFolder));
             }
             else
             {
                 CalendarUtilities.AddConflictingAppointmentsInfobarMessage(infobar, adjacentOrConflictingItems, userContext, calendarItemBase.CalendarItemType);
             }
         }
     }
 }
Exemplo n.º 10
0
        private bool MasterMessageArrived(MailboxSession session, MeetingSeriesMessageOrderingAgent.SeriesHeadersData headersData, out StoreId instanceCalendarItemId)
        {
            OrFilter seekFilter = new OrFilter(new QueryFilter[]
            {
                new ComparisonFilter(ComparisonOperator.Equal, CalendarItemBaseSchema.GlobalObjectId, headersData.InstanceGoid),
                new ComparisonFilter(ComparisonOperator.Equal, CalendarItemBaseSchema.GlobalObjectId, headersData.MasterGoid)
            });

            instanceCalendarItemId = null;
            bool flag = false;

            using (CalendarFolder calendarFolder = CalendarFolder.Bind(session, DefaultFolderType.Calendar))
            {
                using (QueryResult queryResult = calendarFolder.ItemQuery(ItemQueryType.None, null, MeetingSeriesMessageOrderingAgent.SortByGoid, MeetingSeriesMessageOrderingAgent.AdditionalQueryProperties))
                {
                    bool flag2 = true;
                    while (queryResult.SeekToCondition(flag2 ? SeekReference.OriginBeginning : SeekReference.OriginCurrent, seekFilter, SeekToConditionFlags.AllowExtendedFilters))
                    {
                        flag2 = false;
                        IStorePropertyBag[] propertyBags = queryResult.GetPropertyBags(1);
                        if (propertyBags.Length == 1)
                        {
                            IStorePropertyBag storePropertyBag = propertyBags[0];
                            if (ObjectClass.IsCalendarItemSeries(storePropertyBag.GetValueOrDefault <string>(StoreObjectSchema.ItemClass, null)))
                            {
                                int valueOrDefault = storePropertyBag.GetValueOrDefault <int>(CalendarItemBaseSchema.AppointmentSequenceNumber, -1);
                                flag = (headersData.SeriesSequenceNumber <= valueOrDefault);
                                MeetingSeriesMessageOrderingAgent.tracer.TraceDebug <int, int, bool>((long)this.GetHashCode(), "Message SSN: {0}, Master SSN: {1} => Master message arrived: {2}.", headersData.SeriesSequenceNumber, valueOrDefault, flag);
                            }
                            else
                            {
                                instanceCalendarItemId = storePropertyBag.GetValueOrDefault <StoreId>(ItemSchema.Id, null);
                            }
                        }
                    }
                }
            }
            return(flag);
        }
Exemplo n.º 11
0
        public static void DisableBirthdayCalendar(MailboxSession session)
        {
            ExTraceGlobals.BirthdayCalendarTracer.TraceDebug <Guid>(0L, "BirthdayCalendar::DisableBirthdayCalendar. MailboxGuid:{0}", session.MailboxGuid);
            StoreObjectId birthdayCalendarFolderId = BirthdayCalendar.GetBirthdayCalendarFolderId(session);

            if (birthdayCalendarFolderId == null)
            {
                ExTraceGlobals.BirthdayCalendarTracer.TraceDebug <Guid>(0L, "BirthdayCalendar::DisableBirthdayCalendar. Folder doesn't exist. MailboxGuid:{0}", session.MailboxGuid);
                return;
            }
            try
            {
                ExTraceGlobals.BirthdayCalendarTracer.TraceDebug <Guid>(0L, "BirthdayCalendar::DisableBirthdayCalendar. Set IsHidden. MailboxGuid:{0}", session.MailboxGuid);
                using (CalendarFolder calendarFolder = CalendarFolder.Bind(session, birthdayCalendarFolderId))
                {
                    BirthdayCalendar.SetBirthdayCalendarHiddenValue(calendarFolder, true);
                }
            }
            catch (ObjectNotFoundException)
            {
                ExTraceGlobals.BirthdayCalendarTracer.TraceDebug <Guid>(0L, "BirthdayCalendar::DisableBirthdayCalendar. ObjectNotFoundException. MailboxGuid:{0}", session.MailboxGuid);
            }
        }
Exemplo n.º 12
0
 internal List <MeetingValidationResult> Run()
 {
     CalendarValidator.< > c__DisplayClass6 CS$ < > 8__locals1 = new CalendarValidator.< > c__DisplayClass6();
     CS$ < > 8__locals1.< > 4__this = this;
     CS$ < > 8__locals1.results     = new List <MeetingValidationResult>();
     using (SessionManager sessionManager = this.independentSession ? new SessionManager(this.mailboxUser.ExchangePrincipal, "Client=ResourceHealth;Action=Meeting Validator") : new SessionManager(this.mailboxSession))
     {
         if (sessionManager.PrimarySession.Session.GetDefaultFolderId(DefaultFolderType.Calendar) == null)
         {
             CS$ < > 8__locals1.meetings = new List <MeetingData>();
         }
         else
         {
             using (CalendarFolder calendarFolder = CalendarFolder.Bind(sessionManager.PrimarySession.Session, DefaultFolderType.Calendar))
             {
                 if (this.validatingRange)
                 {
                     CS$ < > 8__locals1.meetings = CalendarQuery.GetMeetingsInRange(sessionManager.PrimarySession.Session, this.mailboxUser, calendarFolder, this.rangeStart, this.rangeEnd, this.locationToFilterWith, this.subjectToFilterWith, CS$ < > 8__locals1.results);
                 }
                 else
                 {
                     CS$ < > 8__locals1.meetings = CalendarQuery.GetCorrelatedMeetings(sessionManager.PrimarySession.Session, this.mailboxUser, this.meetingToValidate);
                 }
                 if (CS$ < > 8__locals1.meetings.Count > 0)
                 {
                     try
                     {
                         CS$ < > 8__locals1.meetings.Sort();
                         if (CS$ < > 8__locals1.meetings.Count > Configuration.MaxMeetingsToProcessIncludingDuplicates)
                         {
                             CS$ < > 8__locals1.meetings = CS$ < > 8__locals1.meetings.GetRange(0, Configuration.MaxMeetingsToProcessIncludingDuplicates);
                         }
                         Util.CoreCatchMeIfYouCan(delegate
                         {
                             CS$ < > 8__locals1.results.AddRange(CS$ < > 8__locals1.< > 4__this.RemoveDuplicates(sessionManager.PrimarySession.Session, CS$ < > 8__locals1.meetings));
                         }, "CalendarValidator");
                     }
Exemplo n.º 13
0
        public void FindCalendarFolder()
        {
            var service = GetAuthenticatedEWSInstance();


            CalendarFolder calendarFolder = CalendarFolder.Bind(service, WellKnownFolderName.Calendar);

            var result = calendarFolder.FindAppointments(new CalendarView(DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)));


            foreach (Appointment appointment in result)
            {
                appointment.Load(new PropertySet(BasePropertySet.FirstClassProperties)
                {
                    RequestedBodyType = BodyType.Text
                });

                var body  = appointment.Body;
                var sub   = appointment.Subject;
                var con   = appointment.UniqueBody;
                var start = appointment.Start;
                var end   = appointment.End;
            }
        }
Exemplo n.º 14
0
        private ExchangeVersion GetBestSuitedExchangeVersion()
        {
            var enumList = Enum.GetValues(typeof(ExchangeVersion)).Cast <ExchangeVersion>().Reverse();

            IWebProxy proxy = WebRequest.DefaultWebProxy;

            proxy.Credentials = CredentialCache.DefaultNetworkCredentials;


            var exchangeVersions = enumList as ExchangeVersion[] ?? enumList.ToArray();

            foreach (ExchangeVersion exchangeVersion in exchangeVersions)
            {
                var service = new ExchangeService(exchangeVersion)
                {
                    UseDefaultCredentials = true,
                    WebProxy = proxy
                };

                try
                {
                    service.TraceEnabled = true;
                    service.AutodiscoverUrl("*****@*****.**", ValidateRedirectionUrlCallback);
                    CalendarFolder calendarFolder = CalendarFolder.Bind(service, WellKnownFolderName.Calendar);

                    var result = calendarFolder.FindAppointments(new CalendarView(DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)));

                    return(exchangeVersion);
                }
                catch (Exception exception)
                {
                    continue;
                }
            }
            return(exchangeVersions.ElementAtOrDefault((exchangeVersions.Count() - 1)));
        }
Exemplo n.º 15
0
 // Token: 0x06000B8D RID: 2957 RVA: 0x0004C6E4 File Offset: 0x0004A8E4
 public static bool CheckCalendarConflict(MailboxSession itemStore, CalendarItemBase request, ExDateTime?endOfBookingWindow, out List <AdjacencyOrConflictInfo> conflictList)
 {
     conflictList = new List <AdjacencyOrConflictInfo>();
     if (endOfBookingWindow != null && endOfBookingWindow < request.StartTime)
     {
         endOfBookingWindow = null;
     }
     using (CalendarFolder calendarFolder = CalendarFolder.Bind(itemStore, DefaultFolderType.Calendar))
     {
         AdjacencyOrConflictInfo[] adjacentOrConflictingItems = calendarFolder.GetAdjacentOrConflictingItems(request, endOfBookingWindow);
         if (adjacentOrConflictingItems != null)
         {
             ExDateTime now = ExDateTime.Now;
             foreach (AdjacencyOrConflictInfo adjacencyOrConflictInfo in adjacentOrConflictingItems)
             {
                 if ((adjacencyOrConflictInfo.AdjacencyOrConflictType & AdjacencyOrConflictType.Conflicts) == AdjacencyOrConflictType.Conflicts && adjacencyOrConflictInfo.FreeBusyStatus != BusyType.Free && !(adjacencyOrConflictInfo.OccurrenceInfo.EndTime <= now))
                 {
                     conflictList.Add(adjacencyOrConflictInfo);
                 }
             }
         }
     }
     return(conflictList.Count != 0);
 }
Exemplo n.º 16
0
 private void ThrowIfCopyMovePrereqsFail(MailboxSession destinationSession, StoreObjectId destinationFolderId, bool isCopy)
 {
     Util.ThrowOnNullArgument(destinationFolderId, "destinationFolderId");
     if (destinationFolderId.ObjectType != StoreObjectType.CalendarFolder)
     {
         throw new ArgumentException("Destination folder must be a calendar folder", "destinationFolderId");
     }
     if (!(base.Session is MailboxSession))
     {
         throw new InvalidOperationException("Only mailbox sessions are supported");
     }
     if (base.ParentId.Equals(destinationFolderId))
     {
         throw new ArgumentException("The destination folder must be different from the source folder.", "destinationFolderId");
     }
     if (!this.IsInThePast)
     {
         throw new FutureMeetingException("Only meetings in the past can be copied or moved");
     }
     if (isCopy)
     {
         StoreObjectId defaultFolderId = ((MailboxSession)base.Session).GetDefaultFolderId(DefaultFolderType.Calendar);
         if (base.ParentId.Equals(defaultFolderId) || destinationFolderId.Equals(defaultFolderId))
         {
             throw new PrimaryCalendarFolderException("Copy is not allowed to/from the primary calendar");
         }
     }
     using (CalendarFolder calendarFolder = CalendarFolder.Bind(destinationSession, destinationFolderId))
     {
         IList list = CalendarCorrelationMatch.FindMatches(calendarFolder, base.GlobalObjectId, null);
         if (list.Count > 0)
         {
             throw new CalendarItemExistsException("There is already a calendar item with this GOID in the destination folder");
         }
     }
 }
        internal override CalendarItemBase GetCorrelatedItemInternal(bool cache, bool shouldDetectDuplicateIds, out IEnumerable <VersionedId> detectedDuplicatesIds)
        {
            ExTraceGlobals.MeetingMessageTracer.Information <GlobalObjectId, bool>((long)this.GetHashCode(), "Storage.MeetingMessage.GetCorrelatedItem: GOID={0}; cache={1}", this.GlobalObjectId, cache);
            if (!(base.Session is MailboxSession))
            {
                detectedDuplicatesIds = null;
                return(null);
            }
            if (this.cachedCorrelatedItem != null)
            {
                if (!shouldDetectDuplicateIds)
                {
                    ExTraceGlobals.MeetingMessageTracer.Information <GlobalObjectId>((long)this.GetHashCode(), "Storage.MeetingMessage.GetCorrelatedItemInternal: GOID={0}. Returning cached correlated item.", this.GlobalObjectId);
                    CalendarItemBase result = this.cachedCorrelatedItem;
                    if (!cache)
                    {
                        this.cachedCorrelatedItem.SetDisposeTrackerStacktraceToCurrentLocation();
                        this.cachedCorrelatedItem = null;
                    }
                    detectedDuplicatesIds = Array <VersionedId> .Empty;
                    return(result);
                }
                ExTraceGlobals.MeetingMessageTracer.Information <GlobalObjectId>((long)this.GetHashCode(), "Storage.MeetingMessage.GetCorrelatedItemInternal: GOID={0}. Clearing cached item.", this.GlobalObjectId);
                this.cachedCorrelatedItem.Dispose();
                this.cachedCorrelatedItem = null;
            }
            MailboxSession calendarMailboxSession;

            try
            {
                calendarMailboxSession = MeetingMessage.GetCalendarMailboxSession(this);
            }
            catch (NotSupportedWithServerVersionException ex)
            {
                ExTraceGlobals.MeetingMessageTracer.Information((long)this.GetHashCode(), "MeetingMessage::GetCorrelatedItemInternal. Calendar mailbox session failed to open due to not supported server version.");
                throw new CorrelationFailedException(ex.LocalizedString, ex);
            }
            catch (AdUserNotFoundException ex2)
            {
                ExTraceGlobals.MeetingMessageTracer.Information((long)this.GetHashCode(), "MeetingMessage::GetCorrelatedItemInternal. Calendar mailbox session failed to open due to not being able to find the owner's mailbox.");
                throw new CorrelationFailedException(ex2.LocalizedString, ex2);
            }
            StoreObjectId defaultFolderId = calendarMailboxSession.GetDefaultFolderId(DefaultFolderType.Calendar);

            if (defaultFolderId == null)
            {
                ExTraceGlobals.MeetingMessageTracer.Information((long)this.GetHashCode(), "MeetingMessage::GetCorrelatedItemInternal. Calendar folder is not found. We treat it as correlated calendar item has been deleted.");
                detectedDuplicatesIds = null;
                return(null);
            }
            CalendarItemBase calendarItemBase = null;
            bool             flag             = false;

            try
            {
                using (CalendarFolder calendarFolder = CalendarFolder.Bind(calendarMailboxSession, defaultFolderId))
                {
                    int i = 0;
                    while (i < 2)
                    {
                        ExTraceGlobals.MeetingMessageTracer.Information <GlobalObjectId, int>((long)this.GetHashCode(), "Storage.MeetingMessage.GetCorrelatedItemInternal: GOID={0}. Retrying fetch count={1}", this.GlobalObjectId, i);
                        this.FetchCorrelatedItemId(calendarFolder, shouldDetectDuplicateIds, out detectedDuplicatesIds);
                        if (this.correlatedItemId != null)
                        {
                            try
                            {
                                calendarItemBase = CalendarItemBase.Bind(calendarMailboxSession, this.correlatedItemId.ObjectId);
                            }
                            catch (OccurrenceNotFoundException)
                            {
                                ExTraceGlobals.MeetingMessageTracer.Information <GlobalObjectId>((long)this.GetHashCode(), "Storage.MeetingMessage.GetCorrelatedItemInternal: GOID={0}. Occurrence not found.", this.GlobalObjectId);
                                this.possibleDeletedOccurrenceId = this.correlatedItemId.ObjectId;
                                this.correlatedItemId            = null;
                                break;
                            }
                            catch (ObjectNotFoundException)
                            {
                                ExTraceGlobals.MeetingMessageTracer.Information <GlobalObjectId>((long)this.GetHashCode(), "Storage.MeetingMessage.GetCorrelatedItemInternal: GOID={0}. Calendar item id was found but calendar item got deleted.", this.GlobalObjectId);
                                this.correlatedItemId = null;
                                goto IL_259;
                            }
                            catch (WrongObjectTypeException innerException)
                            {
                                throw new CorruptDataException(ServerStrings.ExNonCalendarItemReturned("Unknown"), innerException);
                            }
                            catch (ArgumentException)
                            {
                                throw new CorruptDataException(ServerStrings.ExNonCalendarItemReturned("Unknown"));
                            }
                            goto IL_20D;
IL_259:
                            i++;
                            continue;
IL_20D:
                            calendarItemBase.OpenAsReadWrite();
                            if (base.Id != null)
                            {
                                calendarItemBase.AssociatedItemId = base.Id;
                            }
                            if (cache)
                            {
                                ExTraceGlobals.MeetingMessageTracer.Information <GlobalObjectId>((long)this.GetHashCode(), "Storage.MeetingMessage.GetCorrelatedItemInternal: GOID={0}. Caching correlated calendar item.", this.GlobalObjectId);
                                this.cachedCorrelatedItem = calendarItemBase;
                            }
                            flag = true;
                            return(calendarItemBase);
                        }
                        break;
                    }
                }
            }
            finally
            {
                if (!flag)
                {
                    Util.DisposeIfPresent(calendarItemBase);
                }
            }
            detectedDuplicatesIds = null;
            return(null);
        }
Exemplo n.º 18
0
        static void Main(string[] args)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);

            // service.UseDefaultCredentials = true;
            //service.Credentials = new WebCredentials(CredentialCache.DefaultNetworkCredentials);
            //service.TraceEnabled = true;

            service.Credentials = new WebCredentials("*****@*****.**", "denim@123");
            service.Url         = new Uri("https://exchange-server.exchange.bluejeansdev.com/EWS/Exchange.asmx");

            //Certification bypass
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            DateTime startDate = DateTime.Now;
            DateTime endDate   = startDate.AddDays(30);
            //Specify number of meetings to see
            const int NUM_APPTS = 5;

            /* Code to show all calendars of a user */
            Folder rootfolder = Folder.Bind(service, WellKnownFolderName.Calendar);

            Console.WriteLine("The " + rootfolder.DisplayName + " has " + rootfolder.ChildFolderCount + " child folders.");
            // A GetFolder operation has been performed.
            // Now do something with the folder, such as display each child folder's name and ID.
            rootfolder.Load();
            foreach (Folder folder in rootfolder.FindFolders(new FolderView(100)))
            {
                Console.WriteLine("\nName: " + folder.DisplayName + "\n  Id: " + folder.Id);
                // Initialize the calendar folder object with only the folder ID.
                CalendarFolder calendar = CalendarFolder.Bind(service, folder.Id, new PropertySet());

                // Set the start and end time and number of appointments to retrieve.
                CalendarView cView = new CalendarView(startDate, endDate, NUM_APPTS);

                // Limit the properties returned to the appointment's subject, start time, and end time.
                cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End);

                // Retrieve a collection of appointments by using the calendar view.
                FindItemsResults <Appointment> appointments = calendar.FindAppointments(cView);

                Console.WriteLine("\nThe first " + NUM_APPTS + " appointments on your calendar from " + startDate.Date.ToShortDateString() +
                                  " to " + endDate.Date.ToShortDateString() + " are: \n");
                Console.WriteLine(appointments.TotalCount);
                foreach (Appointment a in appointments)
                {
                    Console.Write("Subject: " + a.Subject.ToString() + " ");
                    Console.Write("Start: " + a.Start.ToString() + " ");
                    Console.Write("End: " + a.End.ToString());
                    Console.WriteLine();
                }
            }


            Console.WriteLine("Get all shared calendars");

            /*Code to get meetings from all rooms*/
            Dictionary <string, string> result = GetSharedCalendarFolders(service, "*****@*****.**");

            foreach (KeyValuePair <string, string> kvp in result)
            {
                Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);

                FolderId te = new FolderId(WellKnownFolderName.Calendar, kvp.Value);

                DateTime start = DateTime.Now;
                DateTime end   = DateTime.Now.AddDays(30);

                CalendarView view = new CalendarView(start, end);

                foreach (Appointment a in service.FindAppointments(te, view))
                {
                    Console.Write("Subject: " + a.Subject.ToString() + " ");
                    Console.Write("Start: " + a.Start.ToString() + " ");
                    Console.Write("End: " + a.End.ToString());
                    Console.WriteLine();
                }
            }


            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Exemplo n.º 19
0
        static void MyTest()
        {
            // IMPORTANT: ExchangeService is NOT thread safe, so one should create an instance of
            // ExchangeService whenever one needs it.
            ExchangeService myService = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

            myService.Credentials = new NetworkCredential("*****@*****.**", "myPassword00");
            myService.Url         = new Uri("http://mailwebsvc-t.services.local/ews/exchange.asmx");
            // next line is very practical during development phase or for debugging
            myService.TraceEnabled = true;

            Folder myPublicFoldersRoot = Folder.Bind(myService, WellKnownFolderName.PublicFoldersRoot);
            string myPublicFolderPath  = @"OK soft GmbH (DE)\Gruppenpostfächer\_Template - Gruppenpostfach\_Template - Kalender";

            string[] folderPath = myPublicFolderPath.Split('\\');
            FolderId fId        = myPublicFoldersRoot.Id;

            foreach (string subFolderName in folderPath)
            {
                fId = FindPublicFolder(myService, fId, subFolderName);
                if (fId == null)
                {
                    Console.WriteLine("ERROR: Can't find public folder {0}", myPublicFolderPath);
                    return;
                }
            }

            // verify that we found
            Folder folderFound = Folder.Bind(myService, fId);

            if (String.Compare(folderFound.FolderClass, "IPF.Appointment", StringComparison.Ordinal) != 0)
            {
                Console.WriteLine("ERROR: Public folder {0} is not a Calendar", myPublicFolderPath);
                return;
            }

            CalendarFolder myPublicFolder = CalendarFolder.Bind(myService,
                                                                //WellKnownFolderName.Calendar,
                                                                fId,
                                                                PropertySet.FirstClassProperties);

            if (myPublicFolder.TotalCount == 0)
            {
                Console.WriteLine("Warning: Public folder {0} has no appointment. We try to create one.", myPublicFolderPath);

                Appointment app = new Appointment(myService);
                app.Subject = "Writing a code example";
                app.Start   = new DateTime(2010, 9, 9);
                app.End     = new DateTime(2010, 9, 10);
                app.RequiredAttendees.Add("*****@*****.**");
                app.Culture = "de-DE";
                app.Save(myPublicFolder.Id, SendInvitationsMode.SendToNone);
            }

            // We will search using paging. We will use page size 10
            ItemView viewCalendar = new ItemView(10);

            // we can include all properties which we need in the view
            // If we comment the next line then ALL properties will be
            // read from the server. We can see there in the debug output
            viewCalendar.PropertySet     = new PropertySet(ItemSchema.Subject);
            viewCalendar.Offset          = 0;
            viewCalendar.OffsetBasePoint = OffsetBasePoint.Beginning;
            viewCalendar.OrderBy.Add(ContactSchema.DateTimeCreated, SortDirection.Descending);

            FindItemsResults <Item> findResultsCalendar;

            do
            {
                findResultsCalendar = myPublicFolder.FindItems(viewCalendar);

                foreach (Item item in findResultsCalendar)
                {
                    if (item is Appointment)
                    {
                        Appointment appoint = item as Appointment;
                        Console.WriteLine("Subject: \"{0}\"", appoint.Subject);
                    }
                }

                if (findResultsCalendar.NextPageOffset.HasValue)
                {
                    // go to the next page
                    viewCalendar.Offset = findResultsCalendar.NextPageOffset.Value;
                }
            }while (findResultsCalendar.MoreAvailable);
        }
        //function to send email for calender event subscription
        public void sendEmailForCalenderEvent(DBCalendar calObj, string pstrRecipientsEmailId, string pstrCCRecipientsEmailId, string pstrSubject, string pstrMessageBody, string pstrMessage, DateTime startTime, DateTime endTime, string actionToBeTaken)
        {
            ExchangeService objExchangeService = new ExchangeService(ExchangeVersion.Exchange2013);

            objExchangeService.Credentials           = new WebCredentials("wse\\centraluser", "$abcd1234");
            objExchangeService.UseDefaultCredentials = false;
            objExchangeService.Url = new Uri("https://mail.winshuttle.in/EWS/Exchange.asmx");
            EmailMessage objMessage = new EmailMessage(objExchangeService);

            objMessage.ToRecipients.Add(pstrRecipientsEmailId);
            if (pstrCCRecipientsEmailId != null)
            {
                objMessage.CcRecipients.Add(pstrCCRecipientsEmailId);
            }
            objMessage.Subject = pstrSubject;
            objMessage.ReplyTo.Add(new EmailAddress("*****@*****.**"));
            objMessage.Body          = new MessageBody(pstrMessageBody);
            objMessage.Body.BodyType = BodyType.HTML;


            Appointment appObj;

            if (actionToBeTaken == "Update")
            {
                WinMonitorEntityModelContext contextObj = new WinMonitorEntityModelContext();
                DateTime endDateLimit = contextObj.Database.SqlQuery <DateTime>("select DBEventEndTime from DBCalendar").Last();

                CalendarFolder folder = CalendarFolder.Bind(objExchangeService, WellKnownFolderName.Calendar);
                CalendarView   view   = new CalendarView(DateTime.UtcNow, endDateLimit);

                FindItemsResults <Appointment> results = folder.FindAppointments(view);

                foreach (Appointment appointment in  results)
                {
                    if ((appointment.Subject == calObj.DBEventTitle) || (appointment.Start == calObj.DBEventStartTime) || (appointment.End == calObj.DBEventEndTime))
                    {
                        appObj         = Appointment.Bind(objExchangeService, appointment.Id, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Body, AppointmentSchema.Start, AppointmentSchema.End));
                        appObj.Subject = pstrSubject;
                        appObj.Body    = pstrMessage;
                        appObj.Start   = startTime;
                        appObj.End     = endTime;
                        appObj.RequiredAttendees.Add(pstrRecipientsEmailId);
                        appObj.Update(ConflictResolutionMode.AlwaysOverwrite, SendInvitationsOrCancellationsMode.SendToAllAndSaveCopy);
                    }
                }
            }
            else
            if (actionToBeTaken == "CreateNew")
            {
                appObj         = new Appointment(objExchangeService);
                appObj.Subject = calObj.DBEventTitle;
                appObj.Body    = calObj.DBEventDetails;
                appObj.Start   = calObj.DBEventStartTime;
                appObj.End     = calObj.DBEventEndTime;
                appObj.RequiredAttendees.Add(pstrRecipientsEmailId);
                appObj.Save(SendInvitationsMode.SendToAllAndSaveCopy);
            }
            else
            {
                WinMonitorEntityModelContext contextObj = new WinMonitorEntityModelContext();
                DateTime endDateLimit = DateTime.Parse(contextObj.Database.SqlQuery <string>("select DBEventEndTime from DBCalendar").Last());

                CalendarFolder folder = CalendarFolder.Bind(objExchangeService, WellKnownFolderName.Calendar);
                CalendarView   view   = new CalendarView(DateTime.UtcNow, endDateLimit);

                FindItemsResults <Appointment> results = folder.FindAppointments(view);

                foreach (Appointment appointment in results)
                {
                    if ((appointment.Subject == calObj.DBEventTitle) || (appointment.Start == calObj.DBEventStartTime) || (appointment.End == calObj.DBEventEndTime))
                    {
                        appObj = Appointment.Bind(objExchangeService, appointment.Id, new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Body, AppointmentSchema.Start, AppointmentSchema.End));
                        appObj.Delete(DeleteMode.HardDelete);
                    }
                }
            }

            objMessage.Send();
        }
Exemplo n.º 21
0
            private static void initFromFrame(OutlookData data, Outlook outlook, Location location)
            {
                DateTime
                    locationTime  = location.LocationTime,
                    locationToday = new DateTime(locationTime.Year, locationTime.Month, locationTime.Day),
                    windowBeg     = locationToday, //locationTime,
                    windowEnd     = locationToday.AddDays(1).AddMilliseconds(-1)
                ;

                // EWS: create connection point
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;

                ExchangeService service = new ExchangeService(outlook.EwsVersion)
                {
                    Credentials = new WebCredentials(
                        outlook.Account,
                        RsaUtil.Decrypt(outlook.Password)
                        ),
                };

                // EWS: get URL
                if (!string.IsNullOrWhiteSpace(outlook.URL))
                {
                    service.Url = new Uri(outlook.URL);
                }
                else
                {
                    service.Url = HttpRuntime.Cache.GetOrAddSliding(
                        string.Format("exchange_account_{0}", outlook.Account),
                        () =>
                    {
                        service.AutodiscoverUrl(outlook.Account, RedirectionUrlValidationCallback);
                        return(service.Url);
                    },
                        TimeSpan.FromMinutes(60)
                        );
                }

                // mailbox: get display name
                data.DisplayName = outlook.Name;
                if (string.IsNullOrWhiteSpace(data.DisplayName))
                {
                    var match = service.ResolveName(outlook.Mailbox);
                    if (match.Count > 0)
                    {
                        if (match[0].Contact != null)
                        {
                            data.DisplayName =
                                match[0].Contact.CompleteName.FullName
                                ?? match[0].Contact.DisplayName
                                ?? data.DisplayName
                            ;
                        }

                        else if (match[0].Mailbox != null)
                        {
                            data.DisplayName =
                                match[0].Mailbox.Name
                                ?? data.DisplayName
                            ;
                        }
                    }
                    //else
                    //    throw new ApplicationException(string.Format("Mailbox {0} not found", mailbox));
                }

                // mailbox: get availability
                GetUserAvailabilityResults uars = service.GetUserAvailability(
                    new AttendeeInfo[] { new AttendeeInfo(outlook.Mailbox, MeetingAttendeeType.Required, true) },
                    new TimeWindow(locationToday, locationToday.AddDays(1)),
                    AvailabilityData.FreeBusy
                    );
                var u = uars.AttendeesAvailability[0];

                if (u.WorkingHours != null)
                {
                    data.startTime = u.WorkingHours.StartTime;
                    data.endTime   = u.WorkingHours.EndTime;
                    data.timeZone  = u.WorkingHours.TimeZone;
                }

                // events: prep filter
                FolderId       folderId = new FolderId(WellKnownFolderName.Calendar, new Mailbox(outlook.Mailbox));
                CalendarFolder calendar = CalendarFolder.Bind(service, folderId, new PropertySet());
                CalendarView   cView    = new CalendarView(windowBeg, windowEnd)
                {
                    PropertySet = new PropertySet(
                        AppointmentSchema.Subject,
                        AppointmentSchema.DateTimeCreated,
                        AppointmentSchema.Start,
                        AppointmentSchema.End,
                        AppointmentSchema.Duration
                        )
                };

                // events: get list
                data.events = calendar
                              .FindAppointments(cView)
                              .OrderBy(i => i.Start)
                              .ThenBy(i => i.DateTimeCreated)
                              .ThenBy(i => i.Subject)
                              //.Take(Math.Max(1, outlook.ShowEvents))
                              .Select(a => new EventEntry
                {
                    Subject   = a.Subject,
                    CreatedOn = a.DateTimeCreated,
                    Starts    = a.Start,
                    Ends      = a.End,
                    Duration  = a.Duration,
                    Today     = locationToday,
                })
                              //.ToList()
                ;
            }
Exemplo n.º 22
0
        static Dictionary <string, string> GetSharedCalendarFolders(ExchangeService service, String mbMailboxname)
        {
            Dictionary <String, String> rtList = new System.Collections.Generic.Dictionary <string, String>();

            FolderId           rfRootFolderid = new FolderId(WellKnownFolderName.Root, mbMailboxname);
            FolderView         fvFolderView   = new FolderView(int.MaxValue);
            SearchFilter       sfSearchFilter = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, "Common Views");
            FindFoldersResults ffoldres       = service.FindFolders(rfRootFolderid, sfSearchFilter, fvFolderView);

            if (ffoldres.Folders.Count >= 1)
            {
                PropertySet psPropset = new PropertySet(BasePropertySet.FirstClassProperties);
                ExtendedPropertyDefinition PidTagWlinkAddressBookEID = new ExtendedPropertyDefinition(0x6854, MapiPropertyType.Binary);
                ExtendedPropertyDefinition PidTagWlinkGroupName      = new ExtendedPropertyDefinition(0x6851, MapiPropertyType.String);

                psPropset.Add(PidTagWlinkAddressBookEID);
                ItemView iv = new ItemView(1000);
                iv.PropertySet = psPropset;
                iv.Traversal   = ItemTraversal.Associated;

                SearchFilter cntSearch = new SearchFilter.IsEqualTo(PidTagWlinkGroupName, "People's Calendars");
                // Can also find this using PidTagWlinkType = wblSharedFolder
                FindItemsResults <Item> fiResults = ffoldres.Folders[0].FindItems(cntSearch, iv);
                foreach (Item itItem in fiResults.Items)
                {
                    try
                    {
                        object GroupName           = null;
                        object WlinkAddressBookEID = null;

                        if (itItem.TryGetProperty(PidTagWlinkAddressBookEID, out WlinkAddressBookEID))
                        {
                            byte[] ssStoreID    = (byte[])WlinkAddressBookEID;
                            int    leLegDnStart = 0;

                            String lnLegDN = "";
                            for (int ssArraynum = (ssStoreID.Length - 2); ssArraynum != 0; ssArraynum--)
                            {
                                if (ssStoreID[ssArraynum] == 0)
                                {
                                    leLegDnStart = ssArraynum;
                                    lnLegDN      = System.Text.ASCIIEncoding.ASCII.GetString(ssStoreID, leLegDnStart + 1, (ssStoreID.Length - (leLegDnStart + 2)));
                                    ssArraynum   = 1;
                                }
                            }
                            NameResolutionCollection ncCol = service.ResolveName(lnLegDN, ResolveNameSearchLocation.DirectoryOnly, true);
                            if (ncCol.Count > 0)
                            {
                                //Console.WriteLine(ncCol[0].Contact.DisplayName);
                                FolderId SharedCalendarId = new FolderId(WellKnownFolderName.Calendar, ncCol[0].Mailbox.Address);
                                // Folder SharedCalendaFolder = Folder.Bind(service, SharedCalendarId);
                                CalendarFolder calendar = CalendarFolder.Bind(service, new FolderId(WellKnownFolderName.Calendar, ncCol[0].Mailbox.Address), new PropertySet());
                                rtList.Add(ncCol[0].Contact.DisplayName, ncCol[0].Mailbox.Address);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        Console.WriteLine(exception.Message);
                    }
                }
            }
            return(rtList);
        }
Exemplo n.º 23
0
 public static CalendarFolder Bind(MailboxSession session)
 {
     return(CalendarFolder.Bind(session, DefaultFolderType.BirthdayCalendar));
 }
Exemplo n.º 24
0
        // Token: 0x06002432 RID: 9266 RVA: 0x000D1148 File Offset: 0x000CF348
        protected void RenderSecondaryNavigation(TextWriter output, bool showContacts)
        {
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }
            output.Write("<div id=\"{0}\" class=\"secNvPaneCont\">", this.lastModuleName);
            switch (this.navigationModule)
            {
            case NavigationModule.Mail:
                NavigationHost.RenderMailSecondaryNavigation(output, base.UserContext);
                goto IL_229;

            case NavigationModule.Calendar:
            {
                PropertyDefinition[] propsToReturn = new PropertyDefinition[]
                {
                    ViewStateProperties.CalendarViewType,
                    ViewStateProperties.DailyViewDays
                };
                using (CalendarFolder calendarFolder = CalendarFolder.Bind(base.UserContext.MailboxSession, DefaultFolderType.Calendar, propsToReturn))
                {
                    DailyView.RenderSecondaryNavigation(output, calendarFolder, base.UserContext);
                    goto IL_229;
                }
                break;
            }

            case NavigationModule.Contacts:
                break;

            case NavigationModule.Tasks:
                TaskView.RenderSecondaryNavigation(output, base.UserContext);
                goto IL_229;

            case NavigationModule.Options:
                goto IL_21D;

            case NavigationModule.AddressBook:
                this.recipientBlockType = ((AddressBook)this).RecipientBlockType;
                if (base.UserContext.IsFeatureEnabled(Feature.GlobalAddressList))
                {
                    bool isRoomPicker = ((AddressBook)this).IsRoomPicker && DirectoryAssistance.IsRoomsAddressListAvailable(base.UserContext);
                    output.Write("<div class=\"abNavPane\" style=\"height:");
                    output.Write(showContacts ? "30" : "100");
                    output.Write("%;top:0px;\"><div id=\"divMdNmAD\">");
                    output.Write(LocalizedStrings.GetHtmlEncoded(346766088));
                    output.Write("</div><div id=\"divSecNvAD\">");
                    DirectoryView.RenderSecondaryNavigation(output, base.UserContext, isRoomPicker);
                    output.Write("</div></div>");
                }
                if (showContacts)
                {
                    output.Write("<div class=\"abNavPane\" style=\"height:");
                    output.Write(base.UserContext.IsFeatureEnabled(Feature.GlobalAddressList) ? "70" : "100");
                    output.Write("%;bottom:0px;\"><div id=\"divMdNmC\">");
                    output.Write(LocalizedStrings.GetHtmlEncoded(-1165546057));
                    output.Write("</div><div id=\"divSecNvC\"");
                    bool isPicker = ((AddressBook)this).IsPicker;
                    if (isPicker)
                    {
                        output.Write(" class=\"noFltrsCntRg\"");
                    }
                    output.Write(">");
                    ContactView.RenderSecondaryNavigation(output, base.UserContext, isPicker);
                    output.Write("</div></div>");
                    goto IL_229;
                }
                goto IL_229;

            case NavigationModule.Documents:
                DocumentLibraryUtilities.RenderSecondaryNavigation(output, base.UserContext);
                goto IL_229;

            case NavigationModule.PublicFolders:
                NavigationHost.RenderPublicFolderSecondaryNavigation(output, base.UserContext);
                goto IL_229;

            default:
                goto IL_21D;
            }
            ContactView.RenderSecondaryNavigation(output, base.UserContext, false);
            goto IL_229;
IL_21D:
            NavigationHost.RenderMailSecondaryNavigation(output, base.UserContext);
IL_229:
            output.Write("</div>");
        }
Exemplo n.º 25
0
        public void GetExchangeWebServicesAppointments()
        {
            ExchangeService _service = CreateExchangeService();

            if (_service.Url != null)
            {
                // Initialize values for the start and end times, and the number of appointments to retrieve.
                DateTime  startDate = DateTime.Now;
                DateTime  endDate   = startDate.AddYears(1);
                const int NUM_APPTS = 6;

                // Initialize the calendar folder object with only the folder ID.
                CalendarFolder calendar = CalendarFolder.Bind(_service, WellKnownFolderName.Calendar, new PropertySet());

                // Set the start and end time and number of appointments to retrieve.
                CalendarView cView = new CalendarView(startDate, endDate, NUM_APPTS);

                // Limit the properties returned to the appointment's subject, start time, and end time.
                cView.PropertySet = new PropertySet(AppointmentSchema.Subject,
                                                    AppointmentSchema.Start,
                                                    AppointmentSchema.End);

                // Retrieve a collection of appointments by using the calendar view.
                FindItemsResults <Appointment> appointments = calendar.FindAppointments(cView);

                //Check if there are appointments
                if (appointments != null)
                {
                    // Find current meeting in database
                    Meeting currentMeeting = db.Meetings.Where(m => m.MeetingID == 0 && m.RoomID == room.RoomID).FirstOrDefault();

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

                    // If meetings exist in the database
                    if (currentMeeting != null)
                    {
                        // Find appointments that are not activated
                        foreach (var a in appointments)
                        {
                            // If the selected appointment does not match the current meeting
                            if (!a.Id.Equals(currentMeeting.MeetingID))
                            {
                                inactivatedMeetings.Add(a);
                            }
                        }

                        // Suggestion Counter
                        int index = 1;

                        //first delete the meeting suggestions (ID's > 0) already in database
                        foreach (var m in db.Meetings.Where(m => m.RoomID == room.RoomID && m.MeetingID != 0))
                        {
                            db.Meetings.Remove(m);
                        }

                        // Add the inactivated meetings to the Meetings database
                        foreach (var a in inactivatedMeetings)
                        {
                            try
                            {
                                // Add meeting using appointment details
                                AddMeetingToDB(new Meeting
                                {
                                    MeetingID  = index,
                                    Name       = TruncateMyLongString(a.Subject, 50),
                                    StartTime  = a.Start,
                                    EndTime    = a.End,
                                    CalendarID = a.Id.ToString(),
                                    RoomID     = room.RoomID
                                });

                                // Save database changes
                                db.SaveChanges();
                            }
                            // Catch errors adding meetings to database from EWS
                            catch (Exception ex)
                            {
                                nowMeetingNameLabel.Text      = ex.ToString();
                                nowMeetingNameLabel.Font.Size = 10;
                            }
                            // Increment index
                            index += 1;
                        }
                    }
                }
                // If no appointments are returned from EWS write out error in Now Div
                if (appointments == null)
                {
                    nowInfoBoxDescriptionLabel.Text = "Could not access Exchange Calendar";
                }
            }
        }
Exemplo n.º 26
0
        public static void ExportCalendar(Stream outputStream, string charset, OutboundConversionOptions options, MailboxSession session, StoreObjectId folderId, ExDateTime windowStart, ExDateTime windowEnd, DetailLevelEnumType detailType)
        {
            EnumValidator.ThrowIfInvalid <DetailLevelEnumType>(detailType, "detailType");
            PropertyDefinition[] array = InternetCalendarSchema.FromDetailLevel(detailType);
            Array.IndexOf <PropertyDefinition>(array, CalendarItemBaseSchema.FreeBusyStatus);
            int num = Array.IndexOf <PropertyDefinition>(array, InternalSchema.ItemId);

            using (CalendarFolder calendarFolder = CalendarFolder.Bind(session, folderId))
            {
                object[][] array2 = calendarFolder.InternalGetCalendarView(windowStart, windowEnd, detailType == DetailLevelEnumType.AvailabilityOnly, true, true, RecurrenceExpansionOption.IncludeMaster | RecurrenceExpansionOption.TruncateMaster, array);
                Item[]     items  = new Item[array2.Length];
                try
                {
                    for (int i = 0; i < array2.Length; i++)
                    {
                        items[i] = MessageItem.CreateInMemory(StoreObjectSchema.ContentConversionProperties);
                        for (int j = 0; j < array.Length; j++)
                        {
                            StorePropertyDefinition storePropertyDefinition = array[j] as StorePropertyDefinition;
                            if (storePropertyDefinition != null && (storePropertyDefinition.PropertyFlags & PropertyFlags.ReadOnly) != PropertyFlags.ReadOnly)
                            {
                                object obj = array2[i][j];
                                if (!PropertyError.IsPropertyError(obj))
                                {
                                    items[i][storePropertyDefinition] = obj;
                                }
                            }
                        }
                        if (detailType == DetailLevelEnumType.FullDetails && array2[i][num] is VersionedId)
                        {
                            using (CoreItem coreItem = CoreItem.Bind(session, (VersionedId)array2[i][num], new PropertyDefinition[]
                            {
                                ItemSchema.TextBody,
                                ItemSchema.HtmlBody,
                                ItemSchema.RtfBody
                            }))
                            {
                                using (TextReader textReader = coreItem.Body.OpenTextReader(BodyFormat.TextPlain))
                                {
                                    items[i][ItemSchema.TextBody] = textReader.ReadToEnd();
                                }
                            }
                        }
                    }
                    OutboundAddressCache   addressCache = new OutboundAddressCache(options, new ConversionLimitsTracker(options.Limits));
                    List <LocalizedString> errorStream  = new List <LocalizedString>();
                    ConvertUtils.CallCts(ExTraceGlobals.ICalTracer, "ICalSharingHelper::ExportCalendar", ServerStrings.ConversionCorruptContent, delegate
                    {
                        CalendarDocument.InternalItemsToICal(calendarFolder.DisplayName, items, null, addressCache, true, outputStream, errorStream, charset, options);
                    });
                    if (errorStream.Count > 0)
                    {
                        ExTraceGlobals.ICalTracer.TraceError <int>(0L, "{0} errors found during outbound iCal content conversion.", errorStream.Count);
                        AnonymousSharingLog.LogEntries(session, errorStream);
                    }
                }
                finally
                {
                    foreach (Item item in items)
                    {
                        if (item != null)
                        {
                            item.Dispose();
                        }
                    }
                }
            }
        }
Exemplo n.º 27
0
        //main EWS entry
        protected void EWS(object source, System.Timers.ElapsedEventArgs e)
        {
            writeLog("Start EWS Operation");


            Stopwatch s_watch = new Stopwatch();

            s_watch.Start();



            //clean the mid-transfer DB table
            string     str_delete = "delete  from Meeting_Status_Loop";
            SqlCommand sql_delete = new SqlCommand(str_delete, sql_conn());

            sql_delete.ExecuteNonQuery();

            sql_conn().Close();


            //check the credential in the DB whether it still works or not.
            string str_credential = "select * from credential ";

            DataSet ds = new DataSet();

            ds = db_do(str_credential);
            if (ds.Tables[0].Rows.Count < 1)
            {
                string     str_err     = "insert into err_msg values ('The credential information was not found','" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "')";
                SqlCommand cmd_str_err = new SqlCommand(str_err, sql_conn());

                cmd_str_err.ExecuteNonQuery();
                sql_conn().Close();
            }


            //stopwatch
            s_watch.Stop();
            writeLog(s_watch.ElapsedMilliseconds.ToString());
            s_watch.Start();


            //start to connect EWS and get the ews data
            ExchangeService es = new ExchangeService(ExchangeVersion.Exchange2013);

            es.Credentials = new WebCredentials(ds.Tables[0].Rows[0][0].ToString(), ds.Tables[0].Rows[0][1].ToString(), "Your Domian");

            string u_name = ds.Tables[0].Rows[0][0].ToString();
            string pwd    = ds.Tables[0].Rows[0][1].ToString();


            //insert your own ews uri
            es.Url = new Uri("Your EWS Uri");

            try { es.GetRoomLists(); }
            catch (Exception et)
            {
                string     str_err     = "insert into err_msg values ('Please update the credential!!','" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "')";
                SqlCommand cmd_str_err = new SqlCommand(str_err, sql_conn());

                cmd_str_err.ExecuteNonQuery();

                sql_conn().Close();
            }

            EmailAddressCollection myRoomLists = es.GetRoomLists();

            //stopwatch
            s_watch.Stop();
            writeLog("the time of get roomlits is:" + s_watch.ElapsedMilliseconds.ToString());

            DataTable dt_sql = new DataTable();

            dt_sql.Columns.Add("RoomName", typeof(string));
            dt_sql.Columns.Add("StartTime", typeof(string));
            dt_sql.Columns.Add("EndTime", typeof(string));
            dt_sql.Columns.Add("Organzier", typeof(string));
            dt_sql.Columns.Add("Location", typeof(string));
            dt_sql.Columns.Add("TimeStamp", typeof(string));
            dt_sql.Columns.Add("Subject", typeof(string));
            dt_sql.Columns.Add("Opt_att", typeof(string));
            dt_sql.Columns.Add("Req_att", typeof(string));

            EmailAddress address = new EmailAddress();

            foreach (EmailAddress address_list in myRoomLists)
            {
                if (address_list.ToString().Contains("SSMR"))
                {
                    address = address_list;
                }
            }

            System.Collections.ObjectModel.Collection <EmailAddress> room_addresses = es.GetRooms(address);

            aTimer.Stop();
            writeLog("  now we stop the timer");

            int room_count = room_addresses.Count;

            for (int i = 0; i < room_count; i++)
            {
                string str_mailbox   = room_addresses[i].Address.ToString();
                string str_room_name = room_addresses[i].Name.ToString();

                if (str_mailbox.Contains("internal"))
                {
                    str_mailbox = str_mailbox.Replace("internal.", "");
                }


                try
                {
                    Stopwatch sw_dt = new Stopwatch();
                    sw_dt.Start();


                    FolderId       fid     = new FolderId(WellKnownFolderName.Calendar, str_mailbox);
                    CalendarFolder cfolder = CalendarFolder.Bind(es, fid);

                    CalendarView cview = new CalendarView(DateTime.Now, DateTime.Now.AddDays(1));
                    cview.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Organizer, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.IsMeeting, AppointmentSchema.Location, AppointmentSchema.LegacyFreeBusyStatus, AppointmentSchema.DisplayTo, AppointmentSchema.DisplayCc);


                    FindItemsResults <Appointment> appo = cfolder.FindAppointments(cview);

                    if (appo != null)
                    {
                        foreach (Appointment appoi in appo.ToList())
                        {
                            string str_sub = "";
                            if (appoi.Subject is null)
                            {
                                str_sub = "";
                            }
                            else
                            {
                                str_sub = appoi.Subject.ToString().Replace("'", " ");
                            }


                            dt_sql.Rows.Add(str_room_name, appoi.Start.ToString("yyyy-MM-dd HH:mm:ss.ffff"), appoi.End.ToString("yyyy-MM-dd HH:mm:ss.ffff"), null_replace(appoi.Organizer.Name),
                                            null_replace(appoi.Location), System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), str_sub, null_replace(appoi.DisplayCc), null_replace(appoi.DisplayTo));
                        }
                    }
                    sw_dt.Stop();
                    writeLog("Insert room:" + str_room_name + "cost time: " + sw_dt.ElapsedMilliseconds.ToString());
                }
                catch (Exception et)
                {
                    // Create an email message and provide it with connection
                    // configuration information by using an ExchangeService object named service.
                    //EmailMessage message = new EmailMessage(es);
                    //// Set properties on the email message.
                    //message.Subject = "EWS Monitor Service Error!!";
                    //message.Body = "Dears, there is an error when monitor " + str_mailbox + " the exchange server <br><br><br>  the error is:" + et.ToString();
                    //message.ToRecipients.Add("email address");


                    // Send the email message and save a copy.
                    // This method call results in a CreateItem call to EWS.
                    //message.SendAndSaveCopy();
                }

                if (i == room_count - 1)
                {
                    aTimer.Start();
                    writeLog(aTimer.ToString() + "  now we restart the timer");
                }
            }

            writeLog("all rooms operation finsihed");

            Stopwatch sw_dt_sql = new Stopwatch();

            sw_dt_sql.Start();

            try
            {
                SqlBulkCopy sql_dt_insert = new SqlBulkCopy(sql_conn());
                sql_dt_insert.BatchSize       = 10000;
                sql_dt_insert.BulkCopyTimeout = 60;

                sql_dt_insert.DestinationTableName = "Meeting_Status_Loop";

                for (int c = 0; c < dt_sql.Columns.Count; c++)
                {
                    sql_dt_insert.ColumnMappings.Add(c, c + 1);
                }
                sql_dt_insert.WriteToServer(dt_sql);

                sql_conn().Close();

                string     str_insert = "insert into Meeting_Status_Loop values ('end','end','end','end','end','" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "','end','end','end')";
                SqlCommand sql_cmd    = new SqlCommand(str_insert, sql_conn());
                sql_cmd.ExecuteNonQuery();


                //writeLog("get the final one: No." + i + " of meeting room" + str_room_name);

                dt_sql.Clear();
                sql_conn().Close();
            }
            catch (Exception et)
            {
                writeLog("\r\n" + "error when insert end to DB" + et);
            }

            sw_dt_sql.Stop();
            writeLog("\r\n" + " time cost of dt insert is:" + sw_dt_sql.ElapsedMilliseconds.ToString());
        }
Exemplo n.º 28
0
        //use mutilable process
        //protected void GetData_EWS(string username, string pwd, Mailbox mailbox, string RoomName)
        protected void GetData_EWS(object obj)
        {
            //List<string> par_get = obj as List<string>;

            DataTable dt_get = obj as DataTable;

            string username = dt_get.Rows[0][0].ToString();
            string pwd      = dt_get.Rows[0][1].ToString();
            string mailbox  = dt_get.Rows[0][2].ToString();
            string RoomName = dt_get.Rows[0][3].ToString();

            ExchangeService es = new ExchangeService(ExchangeVersion.Exchange2013);

            es.Credentials = new WebCredentials(username, pwd, "Your Domain");


            es.Url = new Uri("Your own EWS uri");

            Stopwatch sw = new Stopwatch();


            try
            {
                sw.Start();


                FolderId       fid     = new FolderId(WellKnownFolderName.Calendar, mailbox);
                CalendarFolder cfolder = CalendarFolder.Bind(es, fid);

                CalendarView cview = new CalendarView(DateTime.Now, DateTime.Now.AddDays(1));
                cview.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Organizer, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.IsMeeting, AppointmentSchema.Location, AppointmentSchema.LegacyFreeBusyStatus, AppointmentSchema.DisplayTo, AppointmentSchema.DisplayCc);


                FindItemsResults <Appointment> appo = cfolder.FindAppointments(cview);


                sw.Stop();
                writeLog("time cost of get appointments list for" + RoomName + "is :" + sw.ElapsedMilliseconds.ToString());
                sw.Restart();


                foreach (Appointment appoi in appo.ToList())
                {
                    string str_sub = "";
                    if (appoi.Subject is null)
                    {
                        str_sub = "";
                    }
                    else
                    {
                        str_sub = appoi.Subject.ToString().Replace("'", " ");
                    }



                    if (string.IsNullOrEmpty(appoi.DisplayTo) is false)
                    {
                    }

                    //MessageBox.Show(appoi.Subject + appoi.Organizer + appoi.Location);
                    string str_insert = "insert into Meeting_Status_Loop values ('" + RoomName + "','" + appoi.Start.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "','" +
                                        appoi.End.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "','" + null_replace(appoi.Organizer.Name) + "','" + null_replace(appoi.Location) + "','" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff") + "',N'" +
                                        (str_sub) + "','" + null_replace(appoi.DisplayCc) + "','" + null_replace(appoi.DisplayTo) + "')";

                    SqlCommand sqlCommand = new SqlCommand(str_insert, sql_conn());

                    try
                    {
                        sqlCommand.ExecuteNonQuery();
                        //MessageBox.Show("loop start");

                        writeLog(" sql operation for ." + mailbox + "was successfully finished");
                        sql_conn().Close();

                        //EmailMessage message = new EmailMessage(service);
                        //// Set properties on the email message.
                        //message.Subject = "EWS Monitor Service Sql Operaction successed";
                        //message.Body = "Dears, finished the tasks for sql operation";
                        //message.ToRecipients.Add("Your email address ");
                        //// Send the email message and save a copy.
                        //// This method call results in a CreateItem call to EWS.
                        //message.SendAndSaveCopy();
                    }
                    catch (Exception et)
                    {
                        // Create an email message and provide it with connection
                        // configuration information by using an ExchangeService object named service.
                        EmailMessage message = new EmailMessage(es);
                        // Set properties on the email message.
                        message.Subject = "EWS Monitor Service Error!!";
                        message.Body    = "Dears, there is an error when monitor " + mailbox + " the exchange server <br><br><br>  the error is:" + et.ToString();
                        message.ToRecipients.Add("Your Email address");


                        // Send the email message and save a copy.
                        // This method call results in a CreateItem call to EWS.
                        message.SendAndSaveCopy();
                    }
                    //}
                }

                sw.Stop();
                writeLog("the time cost of SQL operate for" + RoomName + "is : " + sw.ElapsedMilliseconds.ToString());
            }

            catch (Exception et)
            {
                writeLog("there is an error when operate at" + RoomName + " the error is:\r\n" + et);
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Durchsucht alle Termine der nächsten zwei Jahre nach der übergebenen Kategorie + " - Arges Intern" oder " - Arges Kontakte" und löscht diese.
        /// </summary>
        /// <param name="cat">Der name der Kategorie</param>
        public void deleteWithCategorie(string cat)
        {
            // Initialize values for the start and end times, and the number of appointments to retrieve.
            DateTime startDate = DateTime.Now;
            DateTime endDate   = startDate.AddYears(2);
            // Initialize the calendar folder object with only the folder ID.
            CalendarFolder calendar = CalendarFolder.Bind(service, WellKnownFolderName.Calendar, new PropertySet());
            // Set the start and end time and number of appointments to retrieve.
            CalendarView cView = new CalendarView(startDate, endDate, 500);

            // Limit the properties returned to the appointment's subject, start time, and end time.
            cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Categories);

            FindItemsResults <Appointment> appointments;
            var total = 0;
            var tDel  = 0;

            do
            {
                appointments = calendar.FindAppointments(cView);

                //Läuft über alle Kalendereinträge
                foreach (Appointment a in appointments)
                {
                    //Prüft ob Kalendereintrag ein Categorie enthält
                    if (a.Categories.Contains(cat + " - Arges Intern") || a.Categories.Contains(cat + " - Arges Kontakte"))
                    {
                        a.Delete(DeleteMode.HardDelete);
                        tDel++;
                    }
                }

                cView.StartDate = appointments.Items[appointments.Items.Count - 1].Start;
                total          += appointments.Items.Count;
            } while (appointments.MoreAvailable);
            ExchangeSync.writeLog(SMTPAdresse + " - " + total + " Termine gefunder, " + tDel + " mit Kategorie \"" + cat + "\" gefunden");



            //int pageSize = 500;
            //int offset = 0;

            //ItemView _cView = new ItemView(pageSize + 1, offset);
            //FolderId _folderID = new FolderId(WellKnownFolderName.Calendar);
            //CalendarFolder _calendar = CalendarFolder.Bind(service, _folderID);

            //_cView.PropertySet = new PropertySet(AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.End, AppointmentSchema.Categories);

            //var moreItems = true;
            //var index = 0;
            //while (moreItems)
            //{
            //    var result = _calendar.FindItems(_cView);
            //    moreItems = result.MoreAvailable;

            //    foreach (var item in result)
            //    {
            //        index++;
            //        Console.WriteLine(index + " - " + item.Subject);
            //        if (item.Categories.Contains(cat + " - Arges Intern") || item.Categories.Contains(cat + " - Arges Kontakte"))
            //        {
            //            item.Delete(DeleteMode.HardDelete);

            //        }
            //    }

            //    if (moreItems)
            //    {
            //        _cView.Offset += pageSize;
            //    }
            //}
        }
Exemplo n.º 30
0
 public ICalendarFolder BindToCalendarFolder(IStoreSession session, StoreId id)
 {
     return(CalendarFolder.Bind((StoreSession)session, id));
 }