/// <summary>
        /// Build search filter from options.
        /// </summary>
        /// <param name="options">Options.</param>
        /// <returns>Search filter collection.</returns>
        private static SearchFilter.SearchFilterCollection BuildFilterCollection(ExchangeOptions options)
        {
            // Create search filter collection.
            var searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And);

            // Construct rest of search filter based on options
            if (options.GetOnlyEmailsWithAttachments)
            {
                searchFilter.Add(new SearchFilter.IsEqualTo(ItemSchema.HasAttachments, true));
            }

            if (options.GetOnlyUnreadEmails)
            {
                searchFilter.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            }

            if (!string.IsNullOrEmpty(options.EmailSenderFilter))
            {
                searchFilter.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.Sender, options.EmailSenderFilter));
            }

            if (!string.IsNullOrEmpty(options.EmailSubjectFilter))
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, options.EmailSubjectFilter));
            }

            return(searchFilter);
        }
Beispiel #2
0
        private SearchFilter.SearchFilterCollection setupReadMailFilter()
        {
            SearchFilter.SearchFilterCollection EmailfilterCollection    = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            SearchFilter.SearchFilterCollection readMailFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.Or);
            if (readMailFilter.HasValue)
            {
                switch (readMailFilter.Value)
                {
                case readMailFilterOptions.All:

                    readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
                    readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                    break;

                case readMailFilterOptions.Unread:
                default:
                    readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                    break;

                case readMailFilterOptions.Read:
                    readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
                    break;
                }
            }
            else
            {
                readMailFilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
            }
            EmailfilterCollection.Add(readMailFilterCollection);
            return(EmailfilterCollection);
        }
Beispiel #3
0
        public List <string> CopyEmails(Folder pFolderFrom, Folder pFolderTo)
        {
            List <string> result = new List <string>();

            try
            {
                int pageSize = 100;
                int total    = pFolderFrom.TotalCount;
                int pos      = 0;

                do
                {
                    ItemView vw = new ItemView(pageSize);
                    vw.Offset = pos;
                    FindItemsResults <Item> items = pFolderFrom.FindItems(vw);
                    foreach (EmailMessage item in items)
                    {
                        ItemView vwTo = new ItemView(10);
                        SearchFilter.SearchFilterCollection filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
                        filter.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, item.Subject));
                        filter.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.InternetMessageId, item.InternetMessageId));
                        filter.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.Size, item.Size));
                        filter.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.From, item.From));
                        filter.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.DisplayTo, item.DisplayTo));

                        var teste = pFolderTo.FindItems(filter, vwTo);
                        if (teste.Count() == 0)
                        {
                            item.Copy(pFolderTo.Id);
                            result.Add(item.Subject + " adicionado.");
                            Logging.Logger.Log(item.Subject + " adicionado.");
                        }
                        else
                        {
                            result.Add(item.Subject + " já presente.");
                            Logging.Logger.Log(item.Subject + " já presente.");
                        }
                    }
                    pos += pageSize;
                }while (pos <= total);

                return(result);
            }
            catch (Exception ex)
            {
                result.Add(string.Format("Erro copiando de {0} para {1}: {2}", pFolderFrom.DisplayName, pFolderTo.DisplayName, ex.Message));
                Logging.Logger.Log(string.Format("Erro copiando de {0} para {1}: {2}", pFolderFrom.DisplayName, pFolderTo.DisplayName, ex.Message));
                return(result);
            }
        }
        /// <summary>
        /// This method gets the contacts that have the special DisplayName and property
        /// definitions in the special folder.
        /// </summary>
        private static List <Contact> GetContacts(Folder contactsFolder, String name,
                                                  params PropertyDefinition[] schemas)
        {
            if (contactsFolder == null)
            {
                return(null);
            }

            List <Contact> contacts = new List <Contact>();

            SearchFilter.SearchFilterCollection filters =
                new SearchFilter.SearchFilterCollection(LogicalOperator.And);

            if (!String.IsNullOrWhiteSpace(name))
            {
                SearchFilter searchFilter = new SearchFilter.ContainsSubstring(ContactSchema.DisplayName, name);
                filters.Add(searchFilter);
            }

            if (schemas != null)
            {
                foreach (PropertyDefinition schema in schemas)
                {
                    SearchFilter searchFilter = new SearchFilter.Exists(schema);
                    filters.Add(searchFilter);
                }
            }

            const Int32 pageSize    = 10;
            ItemView    itemView    = new ItemView(pageSize);
            PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly, schemas);

            propertySet.Add(ContactSchema.DisplayName);
            itemView.PropertySet = propertySet;

            FindItemsResults <Item> findResults = null;

            do
            {
                findResults      = contactsFolder.FindItems(filters, itemView);
                itemView.Offset += pageSize;

                contacts.AddRange(findResults.Cast <Contact>());
            } while (findResults.MoreAvailable);


            return(contacts);
        }
Beispiel #5
0
        internal List<Item> GetItem(Folder folder, ItemView iView, DateTime startDate, DateTime endDate, string subjectToSearch)
        {
            SearchFilter.SearchFilterCollection searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            searchFilterCollection.Add(new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, startDate));
            searchFilterCollection.Add(new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, endDate));

            if (!String.IsNullOrEmpty(subjectToSearch))
            {
                searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, subjectToSearch));
            }

            SearchFilter searchFilter = searchFilterCollection;
            FindItemsResults<Item> findResult = folder.FindItems(searchFilter, iView);

            return this.GetListItem(findResult);
        }
Beispiel #6
0
        public bool FetchMeetingRequestbyUniqueId(string uniqueId, out MeetingRequest mr)
        {
            bool result = false;

            mr = null;

            try
            {
                SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
                searchFilter.Add(new SearchFilter.ContainsSubstring(MeetingRequestSchema.Subject, uniqueId));
                ItemView view = new ItemView(500);
                //view.PropertySet = new PropertySet(BasePropertySet.IdOnly, MeetingRequestSchema.Subject, MeetingRequestSchema.Start);
                FindItemsResults <Item> findResults = _service.FindItems(WellKnownFolderName.Inbox, searchFilter, view);

                if (findResults.Items.Count > 0)
                {
                    mr = findResults.Items[0] as MeetingRequest;
                    //mr.Load();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                string msg = String.Format("FetchMeetingRequestbyUniqueId\n{0}\n{1}", ex.Message, ex.StackTrace);
                System.Diagnostics.EventLog.WriteEntry("ExchangeWebServices", msg, System.Diagnostics.EventLogEntryType.Error);
            }


            return(result);
        }
Beispiel #7
0
        public bool FetchAppointmentbyUniqueId(string uniqueId, out Appointment appt, int occurrance = 1)
        {
            bool result = false;

            appt = null;

            try
            {
                SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
                searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, uniqueId));
                ItemView view = new ItemView(500);
                view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType);
                FindItemsResults <Item> findResults = _service.FindItems(WellKnownFolderName.Calendar, searchFilter, view);

                if (findResults.Items.Count > 0)
                {
                    int index = occurrance - 1;
                    if (findResults.Items[index] == null)
                    {
                        index = 0;
                    }
                    appt = findResults.Items[index] as Appointment;
                    appt.Load();
                    result = true;
                }
            }
            catch (Exception ex)
            {
                string msg = String.Format("FetchAppintmentbyUniqueId\n{0}\n{1}", ex.Message, ex.StackTrace);
                System.Diagnostics.EventLog.WriteEntry("ExchangeWebServices", msg, System.Diagnostics.EventLogEntryType.Error);
            }

            return(result);
        }
Beispiel #8
0
        public List <EmailMessage> RetrieveEmailMessage(string monitorAddress, DateTime start, DateTime end)
        {
            //Folder inbox = Folder.Bind(_service, WellKnownFolderName.Inbox, _propSet);

            SearchFilter.SearchFilterCollection sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            sf.Add(new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeReceived, start));
            sf.Add(new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeReceived, end));
            //Ignore email sent by monitor account. Those emails may already send by EmailSender;
            sf.Add(new SearchFilter.IsNotEqualTo(EmailMessageSchema.Sender, _address));

            sf.Add(new SearchFilter.SearchFilterCollection(LogicalOperator.Or,
                                                           new SearchFilter.ContainsSubstring(EmailMessageSchema.ToRecipients, monitorAddress),
                                                           new SearchFilter.ContainsSubstring(EmailMessageSchema.CcRecipients, monitorAddress)
                                                           ));

            ItemView view = new ItemView(Int32.MaxValue);

            view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);

            FindItemsResults <Item> findResults = _service.FindItems(WellKnownFolderName.Inbox, sf, view);

            Logger.Debug("Server return " + findResults.TotalCount + " records.");

            List <EmailMessage> result = new List <EmailMessage>();

            foreach (Item item in findResults)
            {
                if (item is EmailMessage)
                {
                    EmailMessage emailMessage = EmailMessage.Bind(_service, item.Id);
                    if (emailMessage.DateTimeReceived > start && emailMessage.DateTimeReceived <= end)
                    {
                        result.Add(emailMessage);
                    }
                    else
                    {
                        Logger.Debug(string.Format(@"Exchange server filter error. Find mail subject:{0} received {1:s} is not filted by DatetimeReceived from {2:s} to {3:s}",
                                                   emailMessage.Subject, emailMessage.DateTimeReceived, start, end));
                    }
                }
            }

            return(result);
        }
        public IFolderItem OpenFolder(string path, int?pageSize = null, string from = "", string subject = "")
        {
            Queue <string> folderNames = new Queue <string>(path.Split('.'));

            // string folderKey = "FindFoldersOpenFolder" + path + (pageSize.HasValue ? pageSize.Value.ToString() : string.Empty) + from.ToString();

            FindFoldersResults folderResults = FindSubFolder(folderNames);

            if (!folderResults.Any())
            {
                throw new ApplicationException("Errore nel percorso " + path);
            }

            if (folderResults.Folders.Count > 1)
            {
                throw new ApplicationException("Trovati più risultati nel percorso " + path);
            }

            Folder folder = folderResults.Folders.Single();

            ItemView issueVitaItemView = new ItemView(pageSize ?? int.MaxValue);

            issueVitaItemView.PropertySet = new PropertySet(BasePropertySet.FirstClassProperties);

            SearchFilter.SearchFilterCollection collection =
                new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            collection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, subject, ContainmentMode.Substring, ComparisonMode.IgnoreCase));
            collection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.From, from, ContainmentMode.Substring, ComparisonMode.IgnoreCase));

            collection.Add(new SearchFilter.Not(new SearchFilter.Exists(PidTagFlagStatus)));

            //collection.Add(new SearchFilter.IsNotEqualTo(PidTagFlagStatus, (short)MailFlag.Flagged));
            //collection.Add(new SearchFilter.IsNotEqualTo(PidTagFlagStatus, (short)MailFlag.Complete));

            FindItemsResults <Item> issueVitaItems = Service.FindItems(folder.Id, collection, issueVitaItemView);

            return(Factory.ToFolderItem(folder, issueVitaItems));
        }
Beispiel #10
0
        /*
         * public static bool SetProperty(EmailMessage message, PropertyDefinition propertyDefinition, object value)
         * {
         *  if (message == null)
         *      return false;
         *  // get value of PropertyBag property — that is wrapper
         *  // over dictionary of inner message’s properties
         *  var members = message.GetType().FindMembers(MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance, PartialName, "PropertyBag");
         *  if (members.Length < 1)
         *      return false;
         *
         *  var propertyInfo = members[0] as PropertyInfo;
         *  if (propertyInfo == null)
         *      return false;
         *
         *  var bag = propertyInfo.GetValue(message, null);
         *  members = bag.GetType().FindMembers(MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, PartialName, "Properties");
         *
         *  if (members.Length < 1)
         *      return false;
         *
         *  // get dictionary of properties values
         *  var properties = ((PropertyInfo)members[0]).GetMethod.Invoke(bag, null);
         *  var dictionary = properties as Dictionary<PropertyDefinition, object>;
         *  if (dictionary == null)
         *      return false;
         *  dictionary[propertyDefinition] = value;
         *
         *  return true;
         * }
         */

        // Get a summary of all the folders
        public static void GetFolderSummary(ExchangeService service, List <ExchangeFolder> folderStore, DateTime startDate, DateTime endDate, bool purgeIgnored = true)
        {
            SearchFilter.SearchFilterCollection filter = new SearchFilter.SearchFilterCollection();
            filter.LogicalOperator = LogicalOperator.And;
            Logger.Debug("Getting mails from " + startDate + " to " + endDate);
            filter.Add(new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, startDate));
            filter.Add(new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, endDate));
            var view = new ItemView(20, 0, OffsetBasePoint.Beginning)
            {
                PropertySet = PropertySet.IdOnly
            };
            var ignoredFolders = new List <ExchangeFolder>();

            foreach (var exchangeFolder in folderStore)
            {
                var destinationFolder = FolderMapping.ApplyMappings(exchangeFolder.FolderPath, MailProvider.Exchange);
                if (!String.IsNullOrWhiteSpace(destinationFolder))
                {
                    exchangeFolder.MappedDestination = destinationFolder;
                    var findResults = service.FindItems(exchangeFolder.FolderId, filter, view);
                    Logger.Debug(exchangeFolder.FolderPath + " => " + exchangeFolder.MappedDestination + ", " +
                                 findResults.TotalCount + " messages.");
                    exchangeFolder.MessageCount = findResults.TotalCount;
                }
                else
                {
                    ignoredFolders.Add(exchangeFolder);
                }
            }
            if (purgeIgnored)
            {
                foreach (var exchangeFolder in ignoredFolders)
                {
                    folderStore.Remove(exchangeFolder);
                }
            }
        }
        //check if return itemid != "0"
        public static ItemId FindContact(Microsoft.Exchange.WebServices.Data.ExchangeService service, string achternaam, string voornaam, string tussenvoegsel)
        {
            var returnID = new ItemId("0");
            var folders  = new List <FolderId>(1);
            var f_id     = FindFolder(service);

            // Only use the Contacts folder.
            //NameResolutionCollection resolvedNames = service.ResolveName(surnameCommaGivenname,folders , ResolveNameSearchLocation.ContactsOnly, true);
            var contactView = new ItemView(1);
            var filterCol   = new SearchFilter.SearchFilterCollection();

            if (!String.IsNullOrEmpty(achternaam))
            {
                var filterSurname = new SearchFilter.IsEqualTo(ContactSchema.Surname, achternaam);
                filterCol.Add(filterSurname);
            }
            if (!String.IsNullOrEmpty(voornaam))
            {
                var filterGivenName = new SearchFilter.IsEqualTo(ContactSchema.GivenName, voornaam);
                filterCol.Add(filterGivenName);
            }
            if (!String.IsNullOrEmpty(tussenvoegsel))
            {
                var filterTussenvoegsel = new SearchFilter.IsEqualTo(ContactSchema.MiddleName, tussenvoegsel);
                filterCol.Add(filterTussenvoegsel);
            }
            var contacts = service.FindItems(f_id, filterCol, contactView);

            if (contacts != null && contacts.Count() > 0 && contacts.First() != null)
            {
                Console.WriteLine("Contact Found");
                returnID = (contacts.First() as Contact).Id;
            }

            return(returnID);
        }
        public List <IMailItem> OpenInbox(int?pageSize = null, bool?read = null)
        {
            ItemView itemView = new ItemView(pageSize ?? int.MaxValue);

            SearchFilter.SearchFilterCollection collection =
                new SearchFilter.SearchFilterCollection(LogicalOperator.And);

            if (read.HasValue)
            {
                collection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, read.Value));
            }

            FindItemsResults <Item> homeItems = Service.FindItems(WellKnownFolderName.Inbox, collection, itemView);

            return(new List <IMailItem>(
                       homeItems.Select(i => Factory.ToMailItem(i as EmailMessage)
                                        )));
        }
Beispiel #13
0
        Folder getFolderByName(string folderName)
        {
            ExtendedPropertyDefinition allFoldersType =
                new ExtendedPropertyDefinition(13825, MapiPropertyType.Integer);

            FolderId rootFolderId = new FolderId(WellKnownFolderName.MsgFolderRoot);
            //SearchFilter searchFilter1 = new SearchFilter.IsEqualTo(allFoldersType, "2");
            SearchFilter searchFilter2 = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, folderName);

            SearchFilter.SearchFilterCollection searchFilterCollection =
                new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            //searchFilterCollection.Add(searchFilter1);
            searchFilterCollection.Add(searchFilter2);

            FindFoldersResults folders = service.FindFolders(rootFolderId, searchFilterCollection,
                                                             new FolderView(int.MaxValue)
            {
                Traversal = FolderTraversal.Shallow
            });

            return(folders.FirstOrDefault((f) => { return f.DisplayName.Equals(folderName, StringComparison.CurrentCultureIgnoreCase); }));
        }
Beispiel #14
0
        public void Process()
        {
            Progress = new SIMSExchange.Service.Progress()
            {
                Finished = false, Value = ""
            };
            string logpath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Covererror.log");

            File.WriteAllText(logpath, "");
            StreamWriter sr = new StreamWriter(File.Open(logpath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read));

            sr.AutoFlush = true;
            sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Wait 5s before start for SIMS to complete it's writing");
            Thread.Sleep(new TimeSpan(0, 0, 5));
            sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Starting Cover Processing");
            try
            {
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword);
                if (string.IsNullOrEmpty(Properties.Settings.Default.ExchangeUri))
                {
                    service.AutodiscoverUrl(Properties.Settings.Default.EXIMPUser, RedirectionUrlValidationCallback);
                }
                else
                {
                    service.Url = new Uri(Properties.Settings.Default.ExchangeUri + "/ews/exchange.asmx");
                }

                List <Appointment> Appointments = new List <Appointment>();
                int count = 0;
                for (var i = 0; i <= Properties.Settings.Default.AdditionalCoverDays; i++)
                {
                    XmlDocument doc = new XmlDocument();
                    //try
                    //{
                    DateTime dt = DateTime.Now.AddDays(i).DayOfWeek == DayOfWeek.Saturday ? DateTime.Now.AddDays(i + 2) : DateTime.Now.AddDays(i).DayOfWeek == DayOfWeek.Sunday ? DateTime.Now.AddDays(i + 1) : DateTime.Now.AddDays(i);
                    doc.Load(Path.Combine(Properties.Settings.Default.CoverUNC, "CV" + dt.ToString("ddMMyy") + ".htm"));
                    XmlDocument doc1 = new XmlDocument();
                    doc1.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "staffmapping.xml"));
                    count += doc.SelectNodes("/html/body/table/tr[@bgcolor='#f1f1f1']").Count;
                    sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Found " + doc.SelectNodes("/html/body/table/tr[@bgcolor='#f1f1f1']").Count + " cover entries in " + Path.Combine(Properties.Settings.Default.CoverUNC, "CV" + dt.ToString("ddMMyy") + ".htm"));
                }
                Progress.Total              = count;
                Progress.Current            = 0;
                sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Found " + count + " cover entries in total to process");
                for (var i = 0; i <= Properties.Settings.Default.AdditionalCoverDays; i++)
                {
                    XmlDocument doc = new XmlDocument();
                    //try
                    //{
                    DateTime dt = DateTime.Now.AddDays(i).DayOfWeek == DayOfWeek.Saturday ? DateTime.Now.AddDays(i + 2) : DateTime.Now.AddDays(i).DayOfWeek == DayOfWeek.Sunday ? DateTime.Now.AddDays(i + 1) : DateTime.Now.AddDays(i);
                    doc.Load(Path.Combine(Properties.Settings.Default.CoverUNC, "CV" + dt.ToString("ddMMyy") + ".htm"));
                    sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Processing " + Path.Combine(Properties.Settings.Default.CoverUNC, "CV" + dt.ToString("ddMMyy") + ".htm"));
                    XmlDocument doc1 = new XmlDocument();
                    doc1.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "staffmapping.xml"));
                    List <string> clearedaccounts = new List <string>();
                    foreach (XmlNode n in doc.SelectNodes("/html/body/table/tr[@bgcolor='#f1f1f1']"))
                    {
                        sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Processing entry " + Progress.Current + " - Current File: " + Path.Combine(Properties.Settings.Default.CoverUNC, "CV" + dt.ToString("ddMMyy") + ".htm"));
                        try
                        {
                            CoverRow r = CoverRow.Parse(n);
                            if (r.Cover != "No Cover Reqd")
                            {
                                string email = "";
                                foreach (XmlNode c in doc1.SelectNodes("/staffmappings/staff[@last=\"" + r.Cover.Split(new char[] { ',' })[0] + "\"]"))
                                {
                                    if (r.Cover.ToLower().EndsWith(c.Attributes["first"].Value.ToLower().ToCharArray()[0].ToString()))
                                    {
                                        email = c.Attributes["email"].Value;
                                        sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Found matched staff mapping " + email);
                                        break;
                                    }
                                }
                                if (!string.IsNullOrEmpty(email))
                                {
                                    service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, email);
                                    if (!clearedaccounts.Contains(email))
                                    {
                                        SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
                                        searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, dt.Date));
                                        searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, "Cover:"));
                                        ItemView view = new ItemView(999);
                                        view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType);
                                        FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view);
                                        sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Deleting any existing cover");
                                        foreach (Item item in findResults.Items)
                                        {
                                            ((Appointment)item).Delete(DeleteMode.HardDelete);
                                        }
                                        clearedaccounts.Add(email);
                                    }
                                    sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Creating cover Cover: " + r.Class);
                                    Appointment a = CreateApp(r, dt, service);
                                    if (a != null)
                                    {
                                        a.Save();
                                    }
                                }
                            }
                            Progress.Current++;
                        }
                        catch (Exception ex)
                        {
                            sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Error - " + ex.Message);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Error - " + e.Message);
            }
            finally
            {
                sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Cover Done");
                sr.Close();
                this.Progress.Finished = true;
            }
        }
Beispiel #15
0
        public void Process()
        {
            Progress = new SIMSExchange.Service.Progress()
            {
                Finished = false, Value = ""
            };
            string logpath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Staff.log");

            File.WriteAllText(logpath, "");
            StreamWriter sr = new StreamWriter(File.Open(logpath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite));

            sr.AutoFlush = true;
            sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Wait 10s before start for SIMS to complete it's writing");
            Thread.Sleep(new TimeSpan(0, 0, 10));
            sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Starting Staff Processing");
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "report.xml"));
                XmlNodeList nodes = doc.SelectNodes("/SuperStarReport/Record");
                this.Progress.Total = 0;
                List <Staff> staff = new List <Staff>();

                foreach (XmlNode node in nodes)
                {
                    this.Progress.Total++;
                    if (node.SelectSingleNode("Class") != null || (node.SelectSingleNode("ShortName") != null))
                    {
                        Staff cs = null;
                        foreach (Staff s in staff)
                        {
                            if (s.FirstName == (node.SelectSingleNode("Preferred_x0020_Forename") == null ? node.SelectSingleNode("ChosenName") : node.SelectSingleNode("Preferred_x0020_Forename")).InnerText && s.Surname == (node.SelectSingleNode("Legal_x0020_Surname") == null ? node.SelectSingleNode("LegalSurname") : node.SelectSingleNode("Legal_x0020_Surname")).InnerText)
                            {
                                cs = s; break;
                            }
                        }
                        if (cs == null)
                        {
                            cs = new Staff(node); staff.Add(cs);
                        }
                        cs.Lessons.Add(new Lesson(node));

                        sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Found " + cs.Title + " " + cs.FirstName + " " + cs.Surname + " " + cs.Lessons.Last().Day + " " + cs.Lessons.Last().Start + " " + cs.Lessons.Last().Class);
                    }
                }
                sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Found " + this.Progress.Total + " staff events");

                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                if (string.IsNullOrEmpty(Properties.Settings.Default.Domain))
                {
                    service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword);
                }
                else
                {
                    service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword, Properties.Settings.Default.Domain);
                }
                if (string.IsNullOrEmpty(Properties.Settings.Default.ExchangeUri))
                {
                    service.AutodiscoverUrl(Properties.Settings.Default.EXIMPUser, RedirectionUrlValidationCallback);
                }
                else
                {
                    service.Url = new Uri(Properties.Settings.Default.ExchangeUri + "/ews/exchange.asmx");
                }
                Terms terms = new Terms();
                List <Appointment> Appointments = new List <Appointment>();

                this.Progress.Current = 0;

                sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Loading Staff Mappings");
                XmlDocument doc2 = new XmlDocument();
                doc2.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "staffmapping.xml"));


                foreach (Staff s in staff)
                {
                    try
                    {
                        if (doc.SelectSingleNode("/staffmappings/staff[@first=\"" + s.FirstName + "\" and @last=\"" + s.Surname + "\"]") != null)
                        {
                            sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Removing previous appointments for " + s.Title + " " + s.FirstName + " " + s.Surname);
                            service.ImpersonatedUserId       = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, doc.SelectSingleNode("/staffmappings/staff[@first=\"" + s.FirstName + "\" and @last=\"" + s.Surname + "\"]").Attributes["email"].Value);


                            SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
                            searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, terms[0].StartDate));
                            searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, "Lesson:"));
                            bool removecompleted = false;
                            while (!removecompleted)
                            {
                                ItemView view = new ItemView(1000);
                                view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType);
                                FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view);
                                Console.WriteLine(findResults.TotalCount + " " + findResults.Items.Count);
                                var appsids = new List <ItemId>();
                                foreach (Item item in findResults.Items)
                                {
                                    Appointment appt = item as Appointment;
                                    if (appt.AppointmentType == AppointmentType.RecurringMaster)
                                    {
                                        appsids.Add(appt.Id);
                                    }
                                }
                                sr.WriteLine("Removing " + appsids.Count);
                                if (appsids.Count > 0)
                                {
                                    service.DeleteItems(appsids, DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences, true);
                                }
                                var c = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view).TotalCount;
                                removecompleted = c == 0;
                                if (!removecompleted)
                                {
                                    removecompleted = c == 1;
                                }
                                if (!removecompleted)
                                {
                                    sr.WriteLine("Remove not completed, still " + c + " to remove"); System.Threading.Thread.Sleep(5000);
                                }
                            }
                            sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + "Creating appointments for " + s.Title + " " + s.FirstName + " " + s.Surname);
                            var apps = new List <Appointment>();
                            foreach (Lesson l in s.Lessons)
                            {
                                foreach (Term t in terms)
                                {
                                    if (t.HalfTerm.HasValue)
                                    {
                                        DateTime hts = t.HalfTerm.Value.StartDate;
                                        if (hts.DayOfWeek == DayOfWeek.Monday)
                                        {
                                            hts = hts.AddDays(-3);
                                        }
                                        DateTime hte = t.HalfTerm.Value.EndDate;
                                        if (hte.DayOfWeek == DayOfWeek.Friday)
                                        {
                                            hte = hte.AddDays(3);
                                        }
                                        if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, hts))) == 0)
                                        {
                                            apps.Add(CreateApp(l, t.StartDate, hts, t.StartWeekNum == 2, service));
                                        }
                                        if (hte < t.EndDate)
                                        {
                                            if (apps.Count(f => f.Body.Text.Contains(GenBody(l, hte, t.EndDate))) == 0)
                                            {
                                                apps.Add(CreateApp(l, hte, t.EndDate, t.WeekNum(hte) == 2, service));
                                            }
                                        }
                                    }
                                    else if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, t.EndDate))) == 0)
                                    {
                                        apps.Add(CreateApp(l, t.StartDate, t.EndDate, t.StartWeekNum == 2, service));
                                    }
                                }
                            }
                            Console.WriteLine("Creating " + apps.Count + " appointments");
                            service.CreateItems(apps, null, MessageDisposition.SaveOnly, SendInvitationsMode.SendToNone);
                        }
                    }
                    catch (Exception ex)
                    {
                        sr.WriteLine(DateTime.Now.ToString() + " Error " + ex.Message);
                        sr.WriteLine(DateTime.Now.ToString() + " Error " + ex.Source);
                        sr.WriteLine(DateTime.Now.ToString() + " Error " + ex);
                    }
                    this.Progress.Current++;
                }
            }
            catch (Exception e)
            {
                sr.WriteLine(DateTime.Now.ToString() + " Error " + e.Message);
                sr.WriteLine(DateTime.Now.ToString() + " Error " + e.Source);
                sr.WriteLine(DateTime.Now.ToString() + " Error " + e);
            }
            finally
            {
                sr.Close();
                this.Progress.Finished = true;
            }
        }
Beispiel #16
0
        private void setupSchemaFiltering(SearchFilter.SearchFilterCollection EmailfilterCollection)
        {
            if (SearchAlgorithm.HasValue)
            {
                SearchFilter EmailFilter;
                switch (SearchAlgorithm)
                {
                case SearchAlgorithmOptions.Equals:
                    switch (SearchField)
                    {
                    case SearchFieldOptions.Body:
                        EmailFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.Body, SearchString);
                        break;

                    case SearchFieldOptions.From:
                        EmailFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.From, SearchString);
                        break;

                    case SearchFieldOptions.Subject:
                    default:
                        EmailFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, SearchString);
                        break;
                    }
                    break;

                case SearchAlgorithmOptions.DoesNotEqual:
                    switch (SearchField)
                    {
                    case SearchFieldOptions.Body:
                        EmailFilter = new SearchFilter.IsNotEqualTo(EmailMessageSchema.Body, SearchString);
                        break;

                    case SearchFieldOptions.From:
                        EmailFilter = new SearchFilter.IsNotEqualTo(EmailMessageSchema.From, SearchString);
                        break;

                    case SearchFieldOptions.Subject:
                    default:
                        EmailFilter = new SearchFilter.IsNotEqualTo(EmailMessageSchema.Subject, SearchString);
                        break;
                    }
                    break;

                case SearchAlgorithmOptions.ContainsString:
                default:
                    switch (SearchField)
                    {
                    case SearchFieldOptions.Body:
                        EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.Body, SearchString);
                        break;

                    case SearchFieldOptions.From:
                        EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.From, SearchString);
                        break;

                    case SearchFieldOptions.Subject:
                    default:
                        EmailFilter = new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, SearchString);
                        break;
                    }
                    break;
                }
                EmailfilterCollection.Add(EmailFilter);
            }
        }
        /// <summary>
        /// This method creates and sets the search folder.
        /// </summary>
        private static SearchFolder CreateSearchFolder(ExchangeService service,
                                                       Dictionary <PropertyDefinition, String> filters, String displayName)
        {
            if (service == null)
            {
                return(null);
            }

            SearchFilter.SearchFilterCollection filterCollection =
                new SearchFilter.SearchFilterCollection(LogicalOperator.And);

            // We only search the nearest 30 days emails.
            DateTime     startDate       = DateTime.Now.AddDays(-30);
            DateTime     endDate         = DateTime.Now;
            SearchFilter startDateFilter =
                new SearchFilter.IsGreaterThanOrEqualTo(EmailMessageSchema.DateTimeCreated, startDate);
            SearchFilter endDateFilter =
                new SearchFilter.IsLessThanOrEqualTo(EmailMessageSchema.DateTimeCreated, endDate);

            filterCollection.Add(startDateFilter);
            filterCollection.Add(endDateFilter);

            SearchFilter itemClassFilter =
                new SearchFilter.IsEqualTo(EmailMessageSchema.ItemClass, "IPM.Note");

            filterCollection.Add(itemClassFilter);

            // Set the other filters.
            if (filters != null)
            {
                foreach (PropertyDefinition property in filters.Keys)
                {
                    SearchFilter searchFilter =
                        new SearchFilter.ContainsSubstring(property, filters[property]);
                    filterCollection.Add(searchFilter);
                }
            }

            FolderId folderId = new FolderId(WellKnownFolderName.Inbox);

            Boolean      isDuplicateFoler = true;
            SearchFilter duplicateFilter  = new SearchFilter.IsEqualTo(FolderSchema.DisplayName, displayName);
            SearchFolder searchFolder     =
                GetFolder(service, duplicateFilter, WellKnownFolderName.SearchFolders) as SearchFolder;

            // If there isn't the specific search folder, we create a new one.
            if (searchFolder == null)
            {
                searchFolder     = new SearchFolder(service);
                isDuplicateFoler = false;
            }
            searchFolder.SearchParameters.RootFolderIds.Add(folderId);
            searchFolder.SearchParameters.Traversal    = SearchFolderTraversal.Shallow;
            searchFolder.SearchParameters.SearchFilter = filterCollection;

            if (isDuplicateFoler)
            {
                searchFolder.Update();
            }
            else
            {
                searchFolder.DisplayName = displayName;

                searchFolder.Save(WellKnownFolderName.SearchFolders);
            }

            return(searchFolder);
        }
        public static bool LoadCalendarMaster(ExchangeService oExchangeService, ref ListView oListView, FolderTag oFolderTag, DateTime oSeedDateTime)
        {
            bool bRet = true;

            oListView.Clear();
            oListView.View      = View.Details;
            oListView.GridLines = true;
            oListView.Dock      = DockStyle.Fill;

            oListView.Columns.Add("Start", 150, HorizontalAlignment.Left);
            oListView.Columns.Add("End", 150, HorizontalAlignment.Left);
            oListView.Columns.Add("Subject", 250, HorizontalAlignment.Left);
            oListView.Columns.Add("AppointmentType", 100, HorizontalAlignment.Left);
            oListView.Columns.Add("ItemClass", 100, HorizontalAlignment.Left);
            oListView.Columns.Add("ICalUid", 50, HorizontalAlignment.Left);
            oListView.Columns.Add("UniqueId", 250, HorizontalAlignment.Left);
            oListView.Columns.Add("ChangeKey", 250, HorizontalAlignment.Left);
            SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
            searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, new DateTime(2000, 1, 1)));
            ItemView view = new ItemView(2000);

            view.PropertySet = new PropertySet(BasePropertySet.IdOnly,
                                               AppointmentSchema.Subject,
                                               AppointmentSchema.Start,
                                               AppointmentSchema.End,
                                               AppointmentSchema.AppointmentType,
                                               AppointmentSchema.IsRecurring,
                                               AppointmentSchema.ItemClass,
                                               AppointmentSchema.ICalUid

                                               );

            try
            {
                oExchangeService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
                FindItemsResults <Item> findResults = oExchangeService.FindItems(oFolderTag.Id, view);
                ListViewItem            oListItem   = null;
                foreach (Item item in findResults.Items)
                {
                    Appointment appt = item as Appointment;
                    if (appt != null)
                    {
                        oListItem = new ListViewItem(appt.Start.ToString() + " - " + appt.End.ToShortTimeString(), 0);
                        oListItem.SubItems.Add(appt.End.ToString());
                        oListItem.SubItems.Add(appt.Subject);
                        oListItem.SubItems.Add(appt.AppointmentType.ToString());
                        oListItem.SubItems.Add(appt.ItemClass);
                        oListItem.SubItems.Add(appt.ICalUid);
                        oListItem.SubItems.Add(appt.Id.UniqueId);
                        oListItem.SubItems.Add(appt.Id.ChangeKey);
                        //oListItem.SubItems.Add(appt.IsRecurring.ToString());

                        oListItem.Tag = new ItemTag(appt.Id, appt.ItemClass);

                        //if (appt.AppointmentType == AppointmentType.RecurringMaster)
                        //{
                        //    oListItem.Tag = new CalendarItemTag(appt.Id, true);
                        //}
                        //else
                        //{
                        //    oListItem.Tag = new CalendarItemTag(appt.Id, false);
                        //}
                        oListView.Items.AddRange(new ListViewItem[] { oListItem });

                        oListItem = null;
                    }
                }
                oListItem = null;
                bRet      = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                bRet = false;
            }

            return(bRet);
        }
Beispiel #19
0
        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            userName        = settings.UserName;
            password        = settings.Password;
            domain          = settings.Domain;
            serviceURL      = settings.ServiceUrl;
            exchangeVersion = settings.ExchangeVersion;

            folderName        = request.Inputs["Folder Name"].AsString();
            maxNumberOfEmails = request.Inputs["Max Number of Emails"].AsString();
            if (request.Inputs.Contains("Body Format"))
            {
                bodyFormat = request.Inputs["Body Format"].AsString();
            }
            if (request.Inputs.Contains("Read Mail Filter"))
            {
                readMailFilter = request.Inputs["Read Mail Filter"].AsString();
            }

            string alternateMailbox = string.Empty;

            if (request.Inputs.Contains("Alternate Mailbox"))
            {
                alternateMailbox = request.Inputs["Alternate Mailbox"].AsString();
            }

            try
            {
                Convert.ToInt32(maxNumberOfEmails);
            }
            catch
            {
                maxNumberOfEmails = "100";
            }

            ExchangeService service = new ExchangeService();

            switch (exchangeVersion)
            {
            case "Exchange2007_SP1":
                service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                break;

            case "Exchange2010":
                service = new ExchangeService(ExchangeVersion.Exchange2010);
                break;

            case "Exchange2010_SP1":
                service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                break;

            default:
                service = new ExchangeService();
                break;
            }

            service.Credentials = new WebCredentials(userName, password, domain);
            String AccountUrl = userName + "@" + domain;

            if (serviceURL.Equals("Autodiscover"))
            {
                service.AutodiscoverUrl(AccountUrl, (a) => { return(true); });
            }
            else
            {
                service.Url = new Uri(serviceURL);
            }

            if (!alternateMailbox.Equals(String.Empty))
            {
                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, alternateMailbox);
            }

            SearchFilter.SearchFilterCollection FolderfilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            SearchFilter.SearchFilterCollection EmailfilterCollection  = new SearchFilter.SearchFilterCollection(LogicalOperator.Or);

            FolderfilterCollection.Add(new SearchFilter.IsEqualTo(FolderSchema.DisplayName, folderName));

            switch (readMailFilter)
            {
            case "All Email":
                EmailfilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
                EmailfilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                break;

            case "Unread Only":
                EmailfilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                break;

            case "Read Only":
                EmailfilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
                break;

            default:
                EmailfilterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                break;
            }

            FolderView view = new FolderView(int.MaxValue);

            view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
            view.PropertySet.Add(FolderSchema.DisplayName);
            view.Traversal = FolderTraversal.Deep;
            FindFoldersResults results = service.FindFolders(WellKnownFolderName.MsgFolderRoot, FolderfilterCollection, view);

            foreach (Folder folder in results)
            {
                folderID = folder.Id;
                break;
            }

            FindItemsResults <Item> findResults = service.FindItems(folderID, EmailfilterCollection, new ItemView(Convert.ToInt32(maxNumberOfEmails)));

            response.Publish("Number of Emails", findResults.Items.Count.ToString());
            response.WithFiltering().PublishRange(getMail(findResults, service));
        }
Beispiel #20
0
        public void Start(object o)
        {
            string logpath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Covererror.log");

            if (File.Exists(logpath))
            {
                File.Delete(logpath);
            }
            StreamWriter sr = new StreamWriter(logpath);

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                if (string.IsNullOrEmpty(Properties.Settings.Default.Domain))
                {
                    service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword);
                }
                else
                {
                    service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword, Properties.Settings.Default.Domain);
                }
                if (string.IsNullOrEmpty(Properties.Settings.Default.ExchangeUri))
                {
                    service.AutodiscoverUrl(Properties.Settings.Default.EXIMPUser, RedirectionUrlValidationCallback);
                }
                else
                {
                    service.Url = new Uri(Properties.Settings.Default.ExchangeUri + "/ews/exchange.asmx");
                }

                List <Appointment> Appointments = new List <Appointment>();
                int count = 0;
                for (var i = 0; i <= Properties.Settings.Default.AdditionalCoverDays; i++)
                {
                    XmlDocument doc = new XmlDocument();
                    //try
                    //{
                    DateTime dt = DateTime.Now.AddDays(i).DayOfWeek == DayOfWeek.Saturday ? DateTime.Now.AddDays(i + 2) : DateTime.Now.AddDays(i).DayOfWeek == DayOfWeek.Sunday ? DateTime.Now.AddDays(i + 1) : DateTime.Now.AddDays(i);
                    doc.Load(Path.Combine(Properties.Settings.Default.CoverUNC, "CV" + dt.ToString("ddMMyy") + ".htm"));
                    XmlDocument doc1 = new XmlDocument();
                    doc1.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "staffmapping.xml"));
                    count += doc.SelectNodes("/html/body/table/tr[@bgcolor='#f1f1f1']").Count;
                }
                if (Initialized != null)
                {
                    Initialized(count);
                }
                for (var i = 0; i <= Properties.Settings.Default.AdditionalCoverDays; i++)
                {
                    XmlDocument doc = new XmlDocument();
                    //try
                    //{
                    DateTime dt = DateTime.Now.AddDays(i).DayOfWeek == DayOfWeek.Saturday ? DateTime.Now.AddDays(i + 2) : DateTime.Now.AddDays(i).DayOfWeek == DayOfWeek.Sunday ? DateTime.Now.AddDays(i + 1) : DateTime.Now.AddDays(i);
                    doc.Load(Path.Combine(Properties.Settings.Default.CoverUNC, "CV" + dt.ToString("ddMMyy") + ".htm"));
                    XmlDocument doc1 = new XmlDocument();
                    doc1.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "staffmapping.xml"));
                    List <string> clearedaccounts = new List <string>();
                    foreach (XmlNode n in doc.SelectNodes("/html/body/table/tr[@bgcolor='#f1f1f1']"))
                    {
                        try
                        {
                            CoverRow r = CoverRow.Parse(n);
                            if (r.Cover != "No Cover Reqd")
                            {
                                string email = "";
                                foreach (XmlNode c in doc1.SelectNodes("/staffmappings/staff[@last=\"" + r.Cover.Split(new char[] { ',' })[0] + "\"]"))
                                {
                                    if (r.Cover.ToLower().EndsWith(c.Attributes["first"].Value.ToLower().ToCharArray()[0].ToString()))
                                    {
                                        email = c.Attributes["email"].Value;
                                        break;
                                    }
                                }
                                if (!string.IsNullOrEmpty(email))
                                {
                                    service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, email);
                                    if (!clearedaccounts.Contains(email))
                                    {
                                        SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
                                        searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, dt.Date));
                                        searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, "Cover:"));
                                        ItemView view = new ItemView(999);
                                        view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType);
                                        FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view);
                                        foreach (Item item in findResults.Items)
                                        {
                                            ((Appointment)item).Delete(DeleteMode.HardDelete);
                                        }
                                        clearedaccounts.Add(email);
                                    }
                                    Appointment a = CreateApp(r, dt, service);
                                    if (a != null)
                                    {
                                        a.Save();
                                    }
                                }
                            }
                            this.Progress++;
                            if (Updated != null)
                            {
                                Updated();
                            }
                        }
                        catch (Exception ex)
                        {
                            sr.WriteLine(ex.Message);
                            sr.WriteLine(ex.Source);
                            sr.WriteLine(ex);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                sr.WriteLine(e.Message);
                sr.WriteLine(e.Source);
                sr.WriteLine(e);
            }
            finally
            {
                sr.Close();
            }

            if (Done != null)
            {
                Done();
            }
        }
Beispiel #21
0
        public void Process()
        {
            Progress = new SIMSExchange.Service.Progress()
            {
                Finished = false, Value = ""
            };
            string logpath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Rooms.log");

            File.WriteAllText(logpath, "");
            StreamWriter sr = new StreamWriter(File.Open(logpath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read));

            sr.AutoFlush = true;
            sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Wait 10s before start for SIMS to complete it's writing");
            Thread.Sleep(new TimeSpan(0, 0, 10));
            sr.WriteLine(Progress.Value = DateTime.Now.ToString() + " Starting Room Processing");
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "rooms.xml"));
                XmlNodeList nodes = doc.SelectNodes("/SuperStarReport/Record");
                List <Room> room  = new List <Room>();
                this.Progress.Total = 0;
                foreach (XmlNode node in nodes)
                {
                    this.Progress.Total++;
                    if (node.SelectSingleNode("Class") != null || (node.SelectSingleNode("Name") != null))
                    {
                        Room cr = null;
                        foreach (Room s in room)
                        {
                            if (s.Name == node.SelectSingleNode("Name").InnerText)
                            {
                                cr = s; break;
                            }
                        }
                        if (cr == null)
                        {
                            cr = new Room(node.SelectSingleNode("Name").InnerText); room.Add(cr);
                        }
                        cr.Add(new Lesson(node));

                        sr.WriteLine(this.Progress.Value = this.Progress.Value = DateTime.Now.ToString() + "Parsing " + cr.Name + " " + cr.Last().Day + " " + cr.Last().Start + " " + cr.Last().Class);
                    }
                }
                sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Found " + this.Progress.Total + " room events");

                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword);
                if (string.IsNullOrEmpty(Properties.Settings.Default.ExchangeUri))
                {
                    service.AutodiscoverUrl(Properties.Settings.Default.EXIMPUser, RedirectionUrlValidationCallback);
                }
                else
                {
                    service.Url = new Uri(Properties.Settings.Default.ExchangeUri + "/ews/exchange.asmx");
                }
                Terms terms = new Terms();

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

                XmlDocument doc2 = new XmlDocument();
                doc2.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "roommapping.xml"));
                sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Loading Room Mappings");
                this.Progress.Current            = 0;
                foreach (Room r in room)
                {
                    try
                    {
                        if (doc2.SelectSingleNode("/RoomMaps/Room[@name=\"" + r.Name + "\"]") != null)
                        {
                            sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Processing " + r.Name + " room events");
                            service.ImpersonatedUserId       = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, doc2.SelectSingleNode("/RoomMaps/Room[@name=\"" + r.Name + "\"]").Attributes["email"].Value);


                            SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
                            searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, terms[0].StartDate));
                            searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, "Lesson:"));
                            ItemView view = new ItemView(999);
                            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType);
                            FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view);
                            foreach (Item item in findResults.Items)
                            {
                                Appointment appt = item as Appointment;
                                if (appt.AppointmentType == AppointmentType.RecurringMaster)
                                {
                                    sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Removing previous appointments for " + r.Name + " " + appt.Subject);
                                    appt.Delete(DeleteMode.HardDelete);
                                }
                            }
                            foreach (Lesson l in r)
                            {
                                sr.WriteLine(this.Progress.Value = DateTime.Now.ToString() + " Creating appointments for " + r.Name + " - " + l.Class + " on Day " + l.Day);
                                foreach (Term t in terms)
                                {
                                    DateTime hts = t.HalfTerm.Value.StartDate;
                                    if (hts.DayOfWeek == DayOfWeek.Monday)
                                    {
                                        hts = hts.AddDays(-3);
                                    }
                                    DateTime hte = t.HalfTerm.Value.EndDate;
                                    if (hte.DayOfWeek == DayOfWeek.Friday)
                                    {
                                        hte = hte.AddDays(3);
                                    }
                                    CreateApp(l, t.StartDate, hts, t.StartWeekNum == 2, service).Save();
                                    CreateApp(l, hte, t.EndDate, t.WeekNum(hte) == 2, service).Save();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        sr.WriteLine(DateTime.Now.ToString() + " Error " + ex.Message);
                        sr.WriteLine(DateTime.Now.ToString() + " Error " + ex.Source);
                        sr.WriteLine(DateTime.Now.ToString() + " Error " + ex);
                    }
                    this.Progress.Current++;
                }
            }
            catch (Exception e)
            {
                sr.WriteLine(DateTime.Now.ToString() + " Error " + e.Message);
                sr.WriteLine(DateTime.Now.ToString() + " Error " + e.Source);
                sr.WriteLine(DateTime.Now.ToString() + " Error " + e);
            }
            finally
            {
                sr.Close();
                this.Progress.Finished = true;
            }
        }
Beispiel #22
0
 private void Run()
 {
     try
     {
         Status = MessageProcessorStatus.Started;
         var fullPropertySet = new PropertySet(PropertySet.FirstClassProperties)
         {
             EmailMessageSchema.IsRead,
             EmailMessageSchema.IsReadReceiptRequested,
             EmailMessageSchema.IsDeliveryReceiptRequested,
             ItemSchema.DateTimeSent,
             ItemSchema.DateTimeReceived,
             ItemSchema.DateTimeCreated,
             ItemSchema.ItemClass,
             ItemSchema.MimeContent,
             ItemSchema.Categories,
             ItemSchema.Importance,
             ItemSchema.InReplyTo,
             ItemSchema.IsFromMe,
             ItemSchema.IsReminderSet,
             ItemSchema.IsResend,
             ItemSchema.IsDraft,
             ItemSchema.ReminderDueBy,
             ItemSchema.Sensitivity,
             ItemSchema.Subject,
             ItemSchema.Id,
             ExchangeHelper.MsgPropertyContentType,
             ExchangeHelper.PidTagFollowupIcon,
         };
         if (service.RequestedServerVersion != ExchangeVersion.Exchange2007_SP1)
         {
             fullPropertySet.Add(ItemSchema.ConversationId);
             fullPropertySet.Add(ItemSchema.IsAssociated);
         }
         if (service.RequestedServerVersion == ExchangeVersion.Exchange2013)
         {
             fullPropertySet.Add(ItemSchema.ArchiveTag);
             fullPropertySet.Add(ItemSchema.Flag);
             fullPropertySet.Add(ItemSchema.IconIndex);
         }
         SearchFilter.SearchFilterCollection filter = new SearchFilter.SearchFilterCollection();
         filter.LogicalOperator = LogicalOperator.And;
         if (_startDate != null)
         {
             Logger.Debug("Getting mails from " + _startDate);
             filter.Add(new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, _startDate));
         }
         if (_endDate != null)
         {
             Logger.Debug("Getting mails up until " + _endDate);
             filter.Add(new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, _endDate));
         }
         foreach (var exchangeFolder in folders)
         {
             ItemView view = new ItemView(_pageSize, 0, OffsetBasePoint.Beginning);
             view.PropertySet = PropertySet.IdOnly;
             List <EmailMessage> emails = new List <EmailMessage>();
             Boolean             more   = true;
             while (more)
             {
                 try
                 {
                     more = FindExchangeMessages(exchangeFolder, filter, view, emails, fullPropertySet);
                     if (emails.Count > 0)
                     {
                         try
                         {
                             foreach (var emailMessage in emails)
                             {
                                 try
                                 {
                                     String subject;
                                     if (!emailMessage.TryGetProperty(ItemSchema.Subject, out subject) ||
                                         subject == null)
                                     {
                                         Logger.Warn("Item " + emailMessage.Id.UniqueId + " has no subject assigned, unable to determine subject.");
                                     }
                                     Logger.Debug("Exporting " + emailMessage.Id.UniqueId + " from " + exchangeFolder.FolderPath + " : " + subject);
                                     var     flags = new Collection <MessageFlags>();
                                     Boolean flag;
                                     if (emailMessage.TryGetProperty(EmailMessageSchema.IsRead, out flag) &&
                                         !flag)
                                     {
                                         flags.Add(MessageFlags.Unread);
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.IsDraft, out flag) && flag)
                                     {
                                         flags.Add(MessageFlags.Draft);
                                     }
                                     if (
                                         emailMessage.TryGetProperty(EmailMessageSchema.IsReadReceiptRequested,
                                                                     out flag) && flag)
                                     {
                                         flags.Add(MessageFlags.ReadReceiptRequested);
                                     }
                                     if (
                                         emailMessage.TryGetProperty(
                                             EmailMessageSchema.IsDeliveryReceiptRequested, out flag) && flag)
                                     {
                                         flags.Add(MessageFlags.DeliveryReceiptRequested);
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.IsReminderSet, out flag) && flag)
                                     {
                                         flags.Add(MessageFlags.ReminderSet);
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.IsAssociated, out flag) && flag)
                                     {
                                         flags.Add(MessageFlags.Associated);
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.IsFromMe, out flag) && flag)
                                     {
                                         flags.Add(MessageFlags.FromMe);
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.IsResend, out flag) && flag)
                                     {
                                         flags.Add(MessageFlags.Resend);
                                     }
                                     var message = new RawMessageDescriptor
                                     {
                                         SourceId          = emailMessage.Id.UniqueId,
                                         Subject           = subject,
                                         Flags             = flags,
                                         RawMessage        = "",
                                         SourceFolder      = exchangeFolder.FolderPath,
                                         DestinationFolder = exchangeFolder.MappedDestination,
                                         IsPublicFolder    = exchangeFolder.IsPublicFolder,
                                     };
                                     Object result;
                                     if (emailMessage.TryGetProperty(ItemSchema.MimeContent, out result) &&
                                         result != null)
                                     {
                                         message.RawMessage = Encoding.UTF8.GetString(emailMessage.MimeContent.Content);
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.ItemClass, out result) &&
                                         result != null)
                                     {
                                         message.ItemClass = emailMessage.ItemClass;
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.IconIndex, out result) &&
                                         result != null)
                                     {
                                         message.IconIndex = (int)emailMessage.IconIndex;
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.Importance, out result) &&
                                         result != null)
                                     {
                                         message.Importance = (int)emailMessage.Importance;
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.Sensitivity, out result) &&
                                         result != null)
                                     {
                                         message.Sensitivity = (int)emailMessage.Sensitivity;
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.InReplyTo, out result) &&
                                         result != null)
                                     {
                                         message.InReplyTo = emailMessage.InReplyTo;
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.ConversationId, out result) &&
                                         result != null)
                                     {
                                         message.ConversationId = emailMessage.ConversationId.ChangeKey;
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.ReminderDueBy, out result) &&
                                         result != null)
                                     {
                                         message.ReminderDueBy = emailMessage.ReminderDueBy;
                                     }
                                     if (
                                         emailMessage.TryGetProperty(ExchangeHelper.PidTagFollowupIcon,
                                                                     out result) && result != null)
                                     {
                                         message.FlagIcon = ExchangeHelper.ConvertFlagIcon((int)result);
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.DateTimeReceived, out result) &&
                                         result != null)
                                     {
                                         message.ReceivedDateTime = emailMessage.DateTimeReceived;
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.DateTimeSent, out result) &&
                                         result != null)
                                     {
                                         message.SentDateTime = emailMessage.DateTimeSent;
                                     }
                                     if (emailMessage.TryGetProperty(ItemSchema.Flag, out result) &&
                                         result != null)
                                     {
                                         message.FollowUpFlag = new FollowUpFlag()
                                         {
                                             StartDateTime    = ((Flag)result).StartDate,
                                             DueDateTime      = ((Flag)result).DueDate,
                                             CompleteDateTime = ((Flag)result).CompleteDate,
                                             Status           =
                                                 ExchangeHelper.ConvertFlagStatus(((Flag)result).FlagStatus),
                                         }
                                     }
                                     ;
                                     if (emailMessage.TryGetProperty(ItemSchema.Categories, out result) &&
                                         result != null && emailMessage.Categories.Count > 0)
                                     {
                                         foreach (var category in emailMessage.Categories)
                                         {
                                             message.Categories.Add(category);
                                         }
                                     }
                                     if (emailMessage.ExtendedProperties != null)
                                     {
                                         foreach (var extendedProperty in emailMessage.ExtendedProperties)
                                         {
                                             if (
                                                 extendedProperty.PropertyDefinition.Equals(
                                                     ExchangeHelper.MsgPropertyContentType))
                                             {
                                                 if (extendedProperty.Value.ToString().Contains("signed-data"))
                                                 {
                                                     message.IsEncrypted = true;
                                                 }
                                             }
                                         }
                                     }
                                     NextReader.Process(message);
                                     SucceededMessageCount++;
                                 }
                                 catch (Exception e)
                                 {
                                     Logger.Error("Failed to load properties for message " + emailMessage.Id.UniqueId, e);
                                     FailedMessageCount++;
                                 }
                             }
                         }
                         catch (Exception e)
                         {
                             Logger.Error("Failed to load properties for messages in " + exchangeFolder.FolderPath, e);
                             FailedMessageCount += emails.Count;
                         }
                         ProcessedMessageCount += emails.Count;
                     }
                     if (more)
                     {
                         view.Offset += _pageSize;
                     }
                 }
                 catch (Exception e)
                 {
                     Logger.Error("Failed to find results against folder " + exchangeFolder.FolderPath, e);
                     more = false;
                 }
             }
         }
     }
     catch (Exception e)
     {
         Logger.Error("Failed to run exporter", e);
     }
     finally
     {
         Close();
     }
 }
Beispiel #23
0
        private SearchFilter.SearchFilterCollection setupFilterCollection()
        {
            SearchFilter.SearchFilterCollection filterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);

            switch (readMailFilter)
            {
            case "All Email":
                break;

            case "Unread Only":
                filterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                break;

            case "Read Only":
                filterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
                break;

            default:
                filterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
                break;
            }

            switch (subjectFilterType)
            {
            case "Contains":
                filterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.Subject, subjectFilter));
                break;

            case "Is Equal To":
                filterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.Subject, subjectFilter));
                break;

            default:
                break;
            }

            switch (fromAddressFilterType)
            {
            case "Contains":
                filterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.From, fromAddressFilter));
                break;

            case "Is Equal To":
                filterCollection.Add(new SearchFilter.IsEqualTo(EmailMessageSchema.From, fromAddressFilter));
                break;

            default:
                break;
            }

            switch (recievedTimeOffsetFilterType.ToUpper())
            {
            case "OLDER THAN":
                filterCollection.Add(new SearchFilter.IsLessThan(EmailMessageSchema.DateTimeReceived, DateTime.Now.AddSeconds(recievedTimeOffset * -1)));
                break;

            case "NEWER THAN":
                filterCollection.Add(new SearchFilter.IsGreaterThan(EmailMessageSchema.DateTimeReceived, DateTime.Now.AddSeconds(recievedTimeOffset * -1)));
                break;

            default:
                break;
            }
            return(filterCollection);
        }
Beispiel #24
0
        //thread to get all emails
        public static void _getMails(object param)
        {
            helpers.addLog("_getMails() started...");
            ews _ews = (ews)param;  //need an instance

            _ews.OnStateChanged(new StatusEventArgs(StatusType.busy, "_getMails() started..."));
            const int chunkSize = 50;

            try
            {
                PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                itempropertyset.RequestedBodyType = BodyType.Text; //request plain text body
                //blocking call
                ItemView view = new ItemView(chunkSize);
                view.PropertySet = itempropertyset;

                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);

                /*
                 * private static void GetAttachments(ExchangeService service)
                 * {
                 *  // Return a single item.
                 *  ItemView view = new ItemView(1);
                 *
                 *  string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email";
                 *
                 *  // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
                 *  FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);
                 *
                 *  if (results.TotalCount > 0)
                 *  {
                 *      EmailMessage email = results.Items[0] as EmailMessage;
                 */
                FindItemsResults <Item> findResults;

                do
                {
                    //findResults = service.FindItems(WellKnownFolderName.Inbox, view);
                    SearchFilter.SearchFilterCollection filterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
                    filterCollection.Add(new SearchFilter.Not(new SearchFilter.ContainsSubstring(ItemSchema.Subject, sMailHasAlreadyProcessed)));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, helpers.filterSubject));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Attachments, helpers.filterAttachement));
                    findResults = _ews._service.FindItems(WellKnownFolderName.Inbox, filterCollection, view);

                    _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: found " + findResults.Items.Count + " items in inbox"));
                    foreach (Item item in findResults.Items)
                    {
                        helpers.addLog("found item...");
                        if (item is EmailMessage)
                        {
                            EmailMessage mailmessage = item as EmailMessage;
                            mailmessage.Load(itempropertyset); //load data from server

                            helpers.addLog("\t is email ...");

                            // If the item is an e-mail message, write the sender's name.
                            helpers.addLog(mailmessage.Sender.Name + ": " + mailmessage.Subject);
                            _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: processing eMail " + mailmessage.Subject));

                            MailMsg myMailMsg = new MailMsg(mailmessage, _ews._userData.sUser);

                            // Bind to an existing message using its unique identifier.
                            //EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId));
                            int iRet = _ews._licenseMail.processMail(myMailMsg);

                            //change subject?
                            // Bind to the existing item, using the ItemId. This method call results in a GetItem call to EWS.
                            Item myItem = Item.Bind(_ews._service, item.Id as ItemId);
                            myItem.Load();
                            // Update the Subject of the email.
                            myItem.Subject += "[processed]";
                            // Save the updated email. This method call results in an UpdateItem call to EWS.
                            myItem.Update(ConflictResolutionMode.AlwaysOverwrite);

                            _ews.OnStateChanged(new StatusEventArgs(StatusType.license_mail, "processed " + iRet.ToString()));
                        }
                    }
                    view.Offset += chunkSize;
                } while (findResults.MoreAvailable && _ews._bRunThread);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.idle, "readmail done"));
            }
            catch (ThreadAbortException ex)
            {
                helpers.addLog("ThreadAbortException: " + ex.Message);
            }
            catch (Exception ex)
            {
                helpers.addLog("Exception: " + ex.Message);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "readmail exception: " + ex.Message));
            }
            helpers.addLog("_getMails() ended");
            _ews.startPull();
        }
Beispiel #25
0
        public void Start(object o)
        {
            string logpath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "stafferror.log");

            if (File.Exists(logpath))
            {
                File.Delete(logpath);
            }
            StreamWriter sr = new StreamWriter(logpath);

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                if (string.IsNullOrEmpty(Properties.Settings.Default.Domain))
                {
                    service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword);
                }
                else
                {
                    service.Credentials = new WebCredentials(Properties.Settings.Default.EXIMPUser, Properties.Settings.Default.EXIMPPassword, Properties.Settings.Default.Domain);
                }
                if (string.IsNullOrEmpty(Properties.Settings.Default.ExchangeUri))
                {
                    service.AutodiscoverUrl(Properties.Settings.Default.EXIMPUser, RedirectionUrlValidationCallback);
                }
                else
                {
                    service.Url = new Uri(Properties.Settings.Default.ExchangeUri + "/ews/exchange.asmx");
                }
                Terms terms = new Terms();
                staff = o as List <Staff>;
                if (Initialized != null)
                {
                    Initialized(staff.Count);
                }

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

                XmlDocument doc = new XmlDocument();
                doc.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "staffmapping.xml"));

                foreach (Staff s in staff)
                {
                    try
                    {
                        if (doc.SelectSingleNode("/staffmappings/staff[@first=\"" + s.FirstName + "\" and @last=\"" + s.Surname + "\"]") != null)
                        {
                            this.Current = "Removing previous appointments for " + s.Title + " " + s.FirstName + " " + s.Surname;
                            if (Updated != null)
                            {
                                Updated();
                            }
                            service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, doc.SelectSingleNode("/staffmappings/staff[@first=\"" + s.FirstName + "\" and @last=\"" + s.Surname + "\"]").Attributes["email"].Value);


                            SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
                            searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, terms[0].StartDate));
                            searchFilter.Add(new SearchFilter.ContainsSubstring(AppointmentSchema.Subject, "Lesson:"));
                            bool removecompleted = false;
                            while (!removecompleted)
                            {
                                ItemView view = new ItemView(1000);
                                view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType);
                                FindItemsResults <Item> findResults = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view);
                                this.Current = "Found Existing" + findResults.TotalCount + " out of " + findResults.Items.Count + " for " + s.Title + " " + s.FirstName + " " + s.Surname;
                                if (Updated != null)
                                {
                                    Updated();
                                }
                                var appsids = new List <ItemId>();
                                foreach (Item item in findResults.Items)
                                {
                                    Appointment appt = item as Appointment;
                                    if (appt.AppointmentType == AppointmentType.RecurringMaster)
                                    {
                                        appsids.Add(appt.Id);
                                    }
                                }
                                this.Current = "Removing previous appointments for " + s.Title + " " + s.FirstName + " " + s.Surname + " " + appsids.Count;
                                if (Updated != null)
                                {
                                    Updated();
                                }
                                try
                                {
                                    if (appsids.Count > 0)
                                    {
                                        service.DeleteItems(appsids, DeleteMode.HardDelete, SendCancellationsMode.SendToNone, AffectedTaskOccurrence.AllOccurrences, true);
                                    }
                                }
                                catch { System.Threading.Thread.Sleep(1000); }
                                var c = service.FindItems(WellKnownFolderName.Calendar, searchFilter, view).TotalCount;
                                removecompleted = c == 0;
                                if (!removecompleted)
                                {
                                    removecompleted = c == 1;
                                }
                                if (!removecompleted)
                                {
                                    this.Current = "Remove not completed, still " + c + " to remove for " + s.Title + " " + s.FirstName + " " + s.Surname;
                                    if (Updated != null)
                                    {
                                        Updated();
                                    }
                                    System.Threading.Thread.Sleep(2000);
                                }
                            }
                            this.Current = "Creating appointments for " + s.Title + " " + s.FirstName + " " + s.Surname;
                            if (Updated != null)
                            {
                                Updated();
                            }
                            var apps = new List <Appointment>();
                            foreach (Lesson l in s.Lessons)
                            {
                                foreach (Term t in terms)
                                {
                                    try
                                    {
                                        if (t.HalfTerm.HasValue)
                                        {
                                            DateTime hts = t.HalfTerm.Value.StartDate;
                                            if (hts.DayOfWeek == DayOfWeek.Monday)
                                            {
                                                hts = hts.AddDays(-3);
                                            }
                                            DateTime hte = t.HalfTerm.Value.EndDate;
                                            if (hte.DayOfWeek == DayOfWeek.Friday)
                                            {
                                                hte = hte.AddDays(3);
                                            }
                                            if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, hts))) == 0)
                                            {
                                                apps.Add(CreateApp(l, t.StartDate, hts, t.StartWeekNum == 2, service));
                                            }
                                            if (hte < t.EndDate)
                                            {
                                                if (apps.Count(f => f.Body.Text.Contains(GenBody(l, hte, t.EndDate))) == 0)
                                                {
                                                    apps.Add(CreateApp(l, hte, t.EndDate, t.WeekNum(hte) == 2, service));
                                                }
                                            }
                                        }
                                        else if (apps.Count(f => f.Body.Text.Contains(GenBody(l, t.StartDate, t.EndDate))) == 0)
                                        {
                                            apps.Add(CreateApp(l, t.StartDate, t.EndDate, t.StartWeekNum == 2, service));
                                        }
                                    }
                                    catch (Exception ex1)
                                    {
                                        sr.WriteLine(ex1.Message);
                                        sr.WriteLine(ex1.Source);
                                        sr.WriteLine(ex1);
                                        sr.WriteLine(s.ToString());
                                        sr.Flush();
                                    }
                                }
                            }
                            this.Current = "Creating " + apps.Count + " appointments for " + s.Title + " " + s.FirstName + " " + s.Surname;
                            if (Updated != null)
                            {
                                Updated();
                            }
                            service.CreateItems(apps, null, MessageDisposition.SaveOnly, SendInvitationsMode.SendToNone);
                        }
                    }
                    catch (Exception ex)
                    {
                        sr.WriteLine(ex.Message);
                        sr.WriteLine(ex.Source);
                        sr.WriteLine(ex);
                        sr.WriteLine(s.ToString());
                        sr.Flush();
                    }
                    this.Progress++;
                    if (Updated != null)
                    {
                        Updated();
                    }
                }
            }
            catch (Exception e)
            {
                sr.WriteLine(e.Message);
                sr.WriteLine(e.Source);
                sr.WriteLine(e);
            }
            finally
            {
                sr.Close();
            }
            if (Done != null)
            {
                Done();
            }
        }
Beispiel #26
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            // If no folder has been identified, warn the user
            if (this._SelectedFolder == null)
            {
                ErrorDialog.ShowWarning("No calendar folder selected.");
                this.DialogResult = DialogResult.None;
                return;
            }


            DateTime start = Convert.ToDateTime(txtStartTime.Text);
            DateTime end   = Convert.ToDateTime(txtEndTime.Text);


            //// TODO: Add more search capablities
            // http://msdn.microsoft.com/en-us/library/dd633700(v=exchg.80).aspx

            SearchFilter.SearchFilterCollection searchFilter = new SearchFilter.SearchFilterCollection();
            searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, start));
            searchFilter.Add(new SearchFilter.IsGreaterThanOrEqualTo(AppointmentSchema.Start, end));
            if (this.chkSearchSubject.Checked == true)
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, txtSubject.Text));
            }
            if (this.chkSearchToAttendee.Checked == true)
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(ItemSchema.DisplayTo, this.txtToAttendee.Text));
            }
            if (this.chkSearchCCAttendee.Checked == true)
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(ItemSchema.DisplayCc, this.txtCCAttendee.Text));
            }
            if (this.chkSearchBody.Checked == true)
            {
                searchFilter.Add(new SearchFilter.ContainsSubstring(ItemSchema.Body, this.txtBody.Text));
            }

            ItemView view = new ItemView(20);

            view.PropertySet = new PropertySet(BasePropertySet.IdOnly, AppointmentSchema.Subject, AppointmentSchema.Start, AppointmentSchema.AppointmentType);
            _CurrentService.ClientRequestId = Guid.NewGuid().ToString();  // Set a new GUID.
            FindItemsResults <Item> findResults = _CurrentService.FindItems(WellKnownFolderName.Calendar, searchFilter, view);

            foreach (Item item in findResults.Items)
            {
                Appointment appt = item as Appointment;
                if (appt.AppointmentType == AppointmentType.RecurringMaster)
                {
                    // Calendar item is a recurring master item for a recurring series.
                }
                if (appt.AppointmentType == AppointmentType.Occurrence)
                {
                    // Calendar item is an occurrence in a recurring series.
                }
                else if (appt.AppointmentType == AppointmentType.Exception)
                {
                    // Calendar item is an exception in a recurring series.
                }
            }
        }
Beispiel #27
0
        //thread to get all emails
        public static void _getMails(object param)
        {
            helpers.addLog("_getMails() started...");
            ews _ews = (ews)param;  //need an instance
            _ews.OnStateChanged(new StatusEventArgs(StatusType.busy, "_getMails() started..."));
            const int chunkSize = 50;
            try
            {
                PropertySet itempropertyset = new PropertySet(BasePropertySet.FirstClassProperties);
                itempropertyset.RequestedBodyType = BodyType.Text; //request plain text body
                //blocking call
                ItemView view = new ItemView(chunkSize);
                view.PropertySet = itempropertyset;

                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
                /*
                private static void GetAttachments(ExchangeService service)
                {
                    // Return a single item.
                    ItemView view = new ItemView(1);

                    string querystring = "HasAttachments:true Subject:'Message with Attachments' Kind:email";

                    // Find the first email message in the Inbox that has attachments. This results in a FindItem operation call to EWS.
                    FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox, querystring, view);

                    if (results.TotalCount > 0)
                    {
                        EmailMessage email = results.Items[0] as EmailMessage;
                */
                FindItemsResults<Item> findResults;

                do
                {
                    //findResults = service.FindItems(WellKnownFolderName.Inbox, view);
                    SearchFilter.SearchFilterCollection filterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
                    filterCollection.Add(new SearchFilter.Not(new SearchFilter.ContainsSubstring(ItemSchema.Subject, sMailHasAlreadyProcessed)));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, helpers.filterSubject));
                    filterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Attachments, helpers.filterAttachement));
                    findResults = _ews._service.FindItems(WellKnownFolderName.Inbox, filterCollection, view);

                    _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: found "+ findResults.Items.Count + " items in inbox"));
                    foreach (Item item in findResults.Items)
                    {
                        helpers.addLog("found item...");
                        if (item is EmailMessage)
                        {
                            EmailMessage mailmessage = item as EmailMessage;
                            mailmessage.Load(itempropertyset); //load data from server

                            helpers.addLog("\t is email ...");

                            // If the item is an e-mail message, write the sender's name.
                            helpers.addLog(mailmessage.Sender.Name + ": " + mailmessage.Subject);
                            _ews.OnStateChanged(new StatusEventArgs(StatusType.none, "getMail: processing eMail " + mailmessage.Subject));

                            MailMsg myMailMsg = new MailMsg(mailmessage, _ews._userData.sUser);

                            // Bind to an existing message using its unique identifier.
                            //EmailMessage message = EmailMessage.Bind(service, new ItemId(item.Id.UniqueId));
                            int iRet = _ews._licenseMail.processMail(myMailMsg);

                            //change subject?
                            // Bind to the existing item, using the ItemId. This method call results in a GetItem call to EWS.
                            Item myItem = Item.Bind(_ews._service, item.Id as ItemId);
                            myItem.Load();
                            // Update the Subject of the email.
                            myItem.Subject += "[processed]";
                            // Save the updated email. This method call results in an UpdateItem call to EWS.
                            myItem.Update(ConflictResolutionMode.AlwaysOverwrite);

                            _ews.OnStateChanged(new StatusEventArgs(StatusType.license_mail, "processed "+iRet.ToString()));
                        }
                    }
                    view.Offset += chunkSize;
                } while (findResults.MoreAvailable && _ews._bRunThread);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.idle, "readmail done"));
            }
            catch (ThreadAbortException ex)
            {
                helpers.addLog("ThreadAbortException: " + ex.Message);
            }
            catch (Exception ex)
            {
                helpers.addLog("Exception: " + ex.Message);
                _ews.OnStateChanged(new StatusEventArgs(StatusType.error, "readmail exception: " + ex.Message));
            }
            helpers.addLog("_getMails() ended");
            _ews.startPull();
        }
Beispiel #28
0
        public static void DownloadAttachement(string mailaddress, string subject, string outfolder, string logFile, bool logVerbose)
        {
            ExchangeService exservice = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

            exservice.UseDefaultCredentials = true;
            exservice.AutodiscoverUrl(mailaddress);
            FolderId folderid = new FolderId(WellKnownFolderName.Inbox, mailaddress);
            Folder   inbox    = Folder.Bind(exservice, folderid);

            SearchFilter.SearchFilterCollection sfcollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
            SearchFilter.IsEqualTo sfir = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
            sfcollection.Add(sfir);
            SearchFilter.IsEqualTo sfha = new SearchFilter.IsEqualTo(EmailMessageSchema.HasAttachments, true);
            sfcollection.Add(sfha);
            //SearchFilter.ContainsSubstring sffrm = new SearchFilter.ContainsSubstring(EmailMessageSchema.From, from); No longer needed as multiple addresses will send emails.
            //sfcollection.Add(sffrm);
            SearchFilter.IsGreaterThanOrEqualTo sfdt = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, DateTime.Now.AddDays(-31));
            sfcollection.Add(sfdt);
            SearchFilter.ContainsSubstring sfsub = new SearchFilter.ContainsSubstring(ItemSchema.Subject, subject);
            sfcollection.Add(sfsub);

            //Initialise loop variables
            int  pagesize  = 100;
            int  offset    = 0;
            bool moreitems = true;

            //Load emails and download attachments
            while (moreitems)
            {
                ItemView view = new ItemView(pagesize, offset, OffsetBasePoint.Beginning);
                FindItemsResults <Item> finditems = inbox.FindItems(sfcollection, view);

                if (finditems.TotalCount > 0)
                {
                    Log.message(LogEntryType.INFO, "DBAidExtractor", "Found " + finditems.TotalCount.ToString() + " mail items.", logFile);
                }
                else
                {
                    Log.message(LogEntryType.INFO, "DBAidExtractor", "No more mail items found.", logFile);
                    break;
                }

                foreach (EmailMessage item in finditems.Items)
                {
                    try
                    {
                        item.Load();

                        foreach (FileAttachment attach in item.Attachments)
                        {
                            attach.Load();
                            FileStream file = null;

                            try
                            {
                                file = new System.IO.FileStream(Path.Combine(outfolder, attach.Name), FileMode.Create);
                                file.Write(attach.Content, 0, attach.Content.Length);
                            }
                            catch (Exception ex)
                            {
                                Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                                continue;
                            }
                            finally
                            {
                                file.Flush();
                                file.Close();
                            }

                            Log.message(LogEntryType.INFO, "DBAidExtractor", "Downloaded Attachment:" + outfolder + "\\" + attach.Name, logFile);
                        }

                        item.IsRead = true;
                        item.Update(ConflictResolutionMode.AlwaysOverwrite);
                    }
                    catch (Exception ex)
                    {
                        Log.message(LogEntryType.WARNING, "DBAidExtractor", ex.Message + (logVerbose ? " - " + ex.StackTrace : ""), logFile);
                        continue;
                    }
                }

                if (finditems.MoreAvailable == false)
                {
                    moreitems = false;
                }
            }
        }