/// <summary>
        /// Deletes a single item in a call to EWS.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        private static void DeleteAnItem(ExchangeService service)
        {
            // Create an item to be deleted. You can delete any item type in your Exchange mailbox.
            // You will need to save these items to your Exchange mailbox before they can be deleted.
            EmailMessage email1 = new EmailMessage(service);

            email1.Subject = "Draft email one";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");

            EmailMessage email2 = new EmailMessage(service);

            email2.Subject = "Draft email two";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");

            Collection <EmailMessage> messages = new Collection <EmailMessage>();

            messages.Add(email1);
            messages.Add(email2);

            try
            {
                // This results in a CreateItem call to EWS. The items are created on the server.
                // The response contains the item identifiers of the newly created items. The items on the client
                // now have item identifiers. You need the identifiers to delete the item.
                ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(messages, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null);

                if (responses.OverallResult == ServiceResult.Success)
                {
                    Console.WriteLine("Successfully created items to be copied.");
                }
                else
                {
                    throw new Exception("The batch creation of the email message draft items was not successful.");
                }
            }
            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }

            try
            {
                // You can delete a single item. Both of the following lines will result in a DeleteItem operation call to EWS.
                // The email message to delete must be saved on the server before you can delete it.
                email1.Delete(DeleteMode.HardDelete);
                email2.Delete(DeleteMode.HardDelete);
            }

            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }
Exemplo n.º 2
0
        } // End Sub FindUnreadEmail

        public static void MoveMessage(ExchangeService service)
        {
            // Create two items to be moved. You can move any item type in your Exchange mailbox.
            // You will need to save these items to your Exchange mailbox before they can be moved.
            EmailMessage email1 = new EmailMessage(service);

            email1.Subject = "Draft email one";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");

            EmailMessage email2 = new EmailMessage(service);

            email2.Subject = "Draft email two";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");


            System.Collections.ObjectModel.Collection <EmailMessage> messages = new System.Collections.ObjectModel.Collection <EmailMessage>();
            messages.Add(email1);
            messages.Add(email2);

            try
            {
                // This results in a CreateItem operation call to EWS. The items are created on the server.
                // The response contains the item identifiers of the newly created items. The items on the client
                // now have item identifiers, which you need in order to move the item.
                ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(messages, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null);

                if (responses.OverallResult == ServiceResult.Success)
                {
                    System.Console.WriteLine("Successfully created items to be copied.");
                }
                else
                {
                    throw new System.Exception("The batch creation of the email message draft items was not successful.");
                }
            }
            catch (ServiceResponseException ex)
            {
                System.Console.WriteLine("Error: {0}", ex.Message);
            }

            try
            {
                // You can move a single item. This will result in a MoveItem operation call to EWS.
                // The EmailMessage that is returned is the item with its updated item identifier. You must save the email
                // message to the server before you can move it.
                EmailMessage email3 = email1.Move(WellKnownFolderName.DeletedItems) as EmailMessage;
            }

            catch (ServiceResponseException ex)
            {
                System.Console.WriteLine("Error: {0}", ex.Message);
            }
        } // End Sub MoveMessage
Exemplo n.º 3
0
        /// <summary>
        /// Copies a single item between folders in a call to EWS.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        private static void CopyAnItem(ExchangeService service)
        {
            // Create two items to copy. You can copy any item type in your Exchange mailbox.
            // You will need to save these items to your Exchange mailbox before they can be copied.
            EmailMessage email1 = new EmailMessage(service);

            email1.Subject = "Draft email one";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");

            EmailMessage email2 = new EmailMessage(service);

            email2.Subject = "Draft email two";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");

            Collection <EmailMessage> messages = new Collection <EmailMessage>();

            messages.Add(email1);
            messages.Add(email2);

            try
            {
                // This results in a CreateItem operation call to EWS. The items are created on the server.
                // The response contains the item identifiers of the newly created items. The items on the client
                // now have item identifiers, which you need in order to make a copy.
                ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(messages, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null);

                if (responses.OverallResult == ServiceResult.Success)
                {
                    Console.WriteLine("Successfully created items that we will copy.");
                }
                else
                {
                    throw new Exception("The batch creation of the email message draft items was not successful.");
                }
            }
            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }

            try
            {
                // You can create copies of a single item. This will result in a CopyItem operation call to EWS.
                // The EmailMessage that is returned is a copy of the item with its own unique identifier. The email message to copy
                // must be saved on the server before you can copy it.
                EmailMessage email3 = email1.Copy(WellKnownFolderName.DeletedItems) as EmailMessage;
            }

            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }
Exemplo n.º 4
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();
            }
        }
        /// <summary>
        /// Moves two items between folders in a batched call to EWS.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        private static void MoveManyItems(ExchangeService service)
        {
            // Create two items to be moved. You can move any item type in your Exchange mailbox.
            // You will need to save these items to your Exchange mailbox before they can be moved.
            EmailMessage email1 = new EmailMessage(service);

            email1.Subject = "Draft email one";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");

            EmailMessage email2 = new EmailMessage(service);

            email2.Subject = "Draft email two";
            email1.Body    = new MessageBody(BodyType.Text, "Draft body of the mail.");

            Collection <EmailMessage> messages = new Collection <EmailMessage>();

            messages.Add(email1);
            messages.Add(email2);

            try
            {
                // This results in a CreateItem operation call to EWS. The items are created on the server.
                // The response contains the item identifiers of the newly created items. The items on the client
                // now have item identifiers, which you need in order to move the item.
                ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(messages, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null);

                if (responses.OverallResult == ServiceResult.Success)
                {
                    Console.WriteLine("Successfully created items to be copied.");
                }
                else
                {
                    throw new Exception("The batch creation of the email message draft items was not successful.");
                }
            }
            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }

            // Get the item identifiers of the items to be moved in a batch operation.
            Collection <ItemId> itemIds = new Collection <ItemId>();

            foreach (EmailMessage email in messages)
            {
                itemIds.Add(email.Id);
            }

            try
            {
                // You can move items in a batch request. This will result in MoveItem operation call to EWS.
                // Unlike the EmailMessage.Move method, the batch request takes a collection of item identifiers,
                // which identify the items that will be moved. This sample moves the items to the DeletedItems folder.
                ServiceResponseCollection <MoveCopyItemResponse> responses = service.MoveItems(itemIds, WellKnownFolderName.DeletedItems);

                if (responses.OverallResult == ServiceResult.Success)
                {
                    Console.WriteLine("Successfully moved the items.");
                }
                else
                {
                    throw new Exception("The batch move of the email message items was not successful.");
                }
            }
            catch (ServiceResponseException ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }
Exemplo n.º 6
0
        } // End Sub MoveMessage

        /// <summary>
        /// Creates and tries to send three email messages with one call to EWS. The third email message intentionally fails
        /// to demonstrate how EWS returns errors for batch requests.
        /// </summary>
        /// <param name="service">A valid ExchangeService object with credentials and the EWS URL.</param>
        static void SendBatchEmails(ExchangeService service)
        {
            // Create three separate email messages.
            EmailMessage message1 = new EmailMessage(service);

            message1.ToRecipients.Add("*****@*****.**");
            message1.ToRecipients.Add("*****@*****.**");
            message1.Subject = "Status Update";
            message1.Body    = "Project complete!";

            EmailMessage message2 = new EmailMessage(service);

            message2.ToRecipients.Add("*****@*****.**");
            message2.Subject    = "High priority work items";
            message2.Importance = Importance.High;
            message2.Body       = "Finish estimate by EOD!";

            EmailMessage message3 = new EmailMessage(service);

            message3.BccRecipients.Add("*****@*****.**");
            message3.BccRecipients.Add("user2contoso.com"); // Invalid email address format.
            message3.Subject = "Surprise party!";
            message3.Body    = "Don't tell anyone. It will be at 6:00 at Aisha's house. Shhh!";
            message3.Categories.Add("Personal Party");

            System.Collections.ObjectModel.Collection <EmailMessage> msgs = new System.Collections.ObjectModel.Collection <EmailMessage>()
            {
                message1, message2, message3
            };

            try
            {
                // Send the batch of email messages. This results in a call to EWS. The response contains the results of the batched request to send email messages.
                ServiceResponseCollection <ServiceResponse> response = service.CreateItems(msgs, WellKnownFolderName.Drafts, MessageDisposition.SendOnly, null);

                // Check the response to determine whether the email messages were successfully submitted.
                if (response.OverallResult == ServiceResult.Success)
                {
                    System.Console.WriteLine("All email messages were successfully submitted");
                    return;
                }

                int counter = 1;

                /* If the response was not an overall success, access the errors.
                 * Results are returned in the order that the action was submitted. For example, the attempt for message1
                 * will be represented by the first result since it was the first one added to the collection.
                 * Errors are not returned if an NDR is returned.
                 */
                foreach (ServiceResponse resp in response)
                {
                    System.Console.WriteLine("Result (message {0}): {1}", counter, resp.Result);
                    System.Console.WriteLine("Error Code: {0}", resp.ErrorCode);
                    System.Console.WriteLine("Error Message: {0}\r\n", resp.ErrorMessage);

                    counter++;
                }
            }
            catch (System.Exception e)
            {
                System.Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Create meetings either one at a time or batch request the creation of meetings. Meetings
        /// are appointments that include attendees.
        /// </summary>
        /// <param name="service">An ExchangeService object with credentials and the EWS URL.</param>
        private static void CreateMeeting(ExchangeService service)
        {
            bool demoBatchCreateMeeting = true;

            Appointment meeting1 = new Appointment(service);

            meeting1.Subject  = "Status Meeting";
            meeting1.Body     = "The purpose of this meeting is to discuss status.";
            meeting1.Start    = new DateTime(2013, 6, 1, 9, 0, 0);
            meeting1.End      = meeting1.Start.AddHours(2);
            meeting1.Location = "Conf Room";
            meeting1.RequiredAttendees.Add("*****@*****.**");
            meeting1.RequiredAttendees.Add("*****@*****.**");
            meeting1.OptionalAttendees.Add("*****@*****.**");

            Appointment meeting2 = new Appointment(service);

            meeting2.Subject  = "Lunch";
            meeting2.Body     = "The purpose of this meeting is to eat and be merry.";
            meeting2.Start    = new DateTime(2013, 6, 1, 12, 0, 0);
            meeting2.End      = meeting2.Start.AddHours(2);
            meeting2.Location = "Contoso cafe";
            meeting2.RequiredAttendees.Add("*****@*****.**");
            meeting2.RequiredAttendees.Add("*****@*****.**");
            meeting2.OptionalAttendees.Add("*****@*****.**");

            try
            {
                if (demoBatchCreateMeeting) // Show batch.
                {
                    Collection <Appointment> meetings = new Collection <Appointment>();
                    meetings.Add(meeting1);
                    meetings.Add(meeting2);

                    // Create the batch of meetings. This results in a CreateItem operation call to EWS.
                    ServiceResponseCollection <ServiceResponse> responses = service.CreateItems(meetings,
                                                                                                WellKnownFolderName.Calendar,
                                                                                                MessageDisposition.SendOnly,
                                                                                                SendInvitationsMode.SendToAllAndSaveCopy);

                    if (responses.OverallResult == ServiceResult.Success)
                    {
                        Console.WriteLine("You've successfully created a couple of meetings in a single call.");
                    }
                    else if (responses.OverallResult == ServiceResult.Warning)
                    {
                        Console.WriteLine("There are some issues with your batch request.");

                        foreach (ServiceResponse response in responses)
                        {
                            if (response.Result == ServiceResult.Error)
                            {
                                Console.WriteLine("Error code: " + response.ErrorCode.ToString());
                                Console.WriteLine("Error message: " + response.ErrorMessage);
                            }
                        }
                    }
                    else // responses.OverallResult == ServiceResult.Error
                    {
                        Console.WriteLine("There are errors with your batch request.");

                        foreach (ServiceResponse response in responses)
                        {
                            if (response.Result == ServiceResult.Error)
                            {
                                Console.WriteLine("Error code: " + response.ErrorCode.ToString());
                                Console.WriteLine("Error message: " + response.ErrorMessage);
                            }
                        }
                    }
                }
                else // Show creation of a single meeting.
                {
                    // Create a single meeting. This results in a CreateItem operation call to EWS.
                    meeting1.Save(SendInvitationsMode.SendToAllAndSaveCopy);
                    Console.WriteLine("You've successfully created a single meeting.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception info: " + ex.Message);
            }
        }
Exemplo n.º 8
0
        public MailResponse SendMail(Mails mails)
        {
            mailerdaemonEntities db = new mailerdaemonEntities();

            using (var transaction = db.Database.BeginTransaction())
            {
                try
                {
                    var appClient = db.applications.Where(x => x.ApplicationGUID == mails.ApplicationGUID).FirstOrDefault();

                    appmail mail = new appmail();
                    mail.ApplicationID   = appClient.id;
                    mail.Content         = mails.Content;
                    mail.DateCreated     = DateTime.Now;
                    mail.DateLastUpdated = DateTime.Now;
                    mail.From            = mails.From;
                    mail.Subject         = mails.Subject;

                    db.appmails.Add(mail);
                    db.SaveChanges();

                    if (mails.To != null)
                    {
                        foreach (var z in mails.To)
                        {
                            ValidatorTool.CustomValidator cv = new ValidatorTool.CustomValidator();
                            if (!cv.IsEmail(z))
                            {
                                Exception emEx = new Exception("EmailID :" + mail.id + Environment.NewLine + "Invalid email address (Recipient): " + z);

                                Elmah.ErrorSignal.FromCurrentContext().Raise(emEx);
                                throw new Exception("Invalid email address: " + z);
                            }

                            appmailrecipient recipient = new appmailrecipient();
                            recipient.AppMailID       = mail.id;
                            recipient.DateCreated     = DateTime.Now;
                            recipient.DateLastUpdated = DateTime.Now;
                            recipient.To = z;

                            db.appmailrecipients.Add(recipient);
                            db.SaveChanges();
                        }
                    }

                    if (mails.Cc != null)
                    {
                        foreach (var z in mails.Cc)
                        {
                            ValidatorTool.CustomValidator cv = new ValidatorTool.CustomValidator();

                            if (!cv.IsEmail(z))
                            {
                                Exception emEx = new Exception("EmailID :" + mail.id + Environment.NewLine + "Invalid email address (CC): " + z);

                                Elmah.ErrorSignal.FromCurrentContext().Raise(emEx);
                                throw new Exception("Invalid email address: " + z);
                            }

                            appmailcc cc = new appmailcc();
                            cc.AppMailID       = mail.id;
                            cc.DateCreated     = DateTime.Now;
                            cc.DateLastUpdated = DateTime.Now;
                            cc.To = z;

                            db.appmailccs.Add(cc);
                            db.SaveChanges();
                        }
                    }

                    if (mails.Bcc != null)
                    {
                        foreach (var z in mails.Bcc)
                        {
                            ValidatorTool.CustomValidator cv = new ValidatorTool.CustomValidator();

                            if (!cv.IsEmail(z))
                            {
                                Exception emEx = new Exception("EmailID :" + mail.id + Environment.NewLine + "Invalid email address (BCC): " + z);

                                Elmah.ErrorSignal.FromCurrentContext().Raise(emEx);
                                throw new Exception("Invalid email address: " + z);
                            }

                            appmailbcc bcc = new appmailbcc();
                            bcc.AppMailID       = mail.id;
                            bcc.DateCreated     = DateTime.Now;
                            bcc.DateLastUpdated = DateTime.Now;
                            bcc.To = z;

                            db.appmailbccs.Add(bcc);
                            db.SaveChanges();
                        }
                    }



                    List <Mails> m = new List <Mails>();
                    m.Add(mails);


                    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                    service.Credentials = new NetworkCredential(appClient.MailUsername, appClient.MailPassword, appClient.MailDomain);
                    // service.Credentials = new WebCredentials(appagent.username, appagent.password);
                    service.Url = new Uri(appClient.MailServiceUrl);



                    Collection <EmailMessage> messageItems = new Collection <EmailMessage>();

                    foreach (Mails mm in m)
                    {
                        EmailMessage newmessage = new EmailMessage(service);
                        newmessage.Body          = mm.Content;
                        newmessage.Subject       = mm.Subject;
                        newmessage.Body.BodyType = BodyType.HTML;
                        newmessage.Importance    = Importance.High;
                        /// ADD MULTIPLE RECIPIENTS
                        ///
                        if (mm.To != null)
                        {
                            foreach (string r in mm.To)
                            {
                                newmessage.ToRecipients.Add(r);
                            }
                        }

                        /// ADD CC RECIPIENTS
                        ///
                        if (mm.Cc != null)
                        {
                            foreach (string c in mm.Cc)
                            {
                                newmessage.CcRecipients.Add(c);
                            }
                        }


                        /// ADD BCC RECIPIENTS
                        ///
                        if (mm.Bcc != null)
                        {
                            foreach (string b in mm.Bcc)
                            {
                                newmessage.BccRecipients.Add(b);
                            }
                        }

                        /// ADD MULTIPLE ATTACHMENTS
                        ///
                        if (mm.Attachments != null)
                        {
                            foreach (MailAttachment amt in mm.Attachments)
                            {
                                newmessage.Attachments.AddFileAttachment(amt.Filename, amt.Data);
                            }
                        }



                        // Create a custom extended property and add it to the message.
                        Guid myPropertySetId = new Guid("{20B5C09F-7CAD-44c6-BDBF-8FCBEEA08544}");
                        Guid g;
                        g = Guid.NewGuid();

                        ExtendedPropertyDefinition myExtendedPropertyDefinition = new ExtendedPropertyDefinition(myPropertySetId, "UUID", MapiPropertyType.String);
                        newmessage.SetExtendedProperty(myExtendedPropertyDefinition, g.ToString());
                        newmessage.IsDeliveryReceiptRequested = true;
                        newmessage.IsReadReceiptRequested     = true;


                        mail.UID    = g.ToString();
                        mail.isSent = 1;
                        db.SaveChanges();

                        messageItems.Add(newmessage);
                    }
                    ServiceResponseCollection <ServiceResponse> response = service.CreateItems(messageItems, WellKnownFolderName.SentItems, MessageDisposition.SendAndSaveCopy, null);



                    transaction.Commit();



                    MailResponse mailResp = new MailResponse();
                    mailResp.Result       = "OK";
                    mailResp.MessageID    = mail.id;
                    mailResp.MailGUID     = mail.UID;
                    mailResp.ErrorMessage = "";

                    return(mailResp);
                }
                catch (Exception ex1)
                {
                    transaction.Rollback();

                    MailResponse mailResp = new MailResponse();
                    mailResp.Result       = "ERROR";
                    mailResp.MessageID    = -1;
                    mailResp.ErrorMessage = ex1.GetBaseException().Message;
                    return(mailResp);
                    // throw new Exception(ex1.Message);
                }
                finally
                {
                    db.Database.Connection.Close();
                }
            }
        }
Exemplo n.º 9
0
        private void CommitBufferedMessages()
        {
            int tryCount   = 0;
            var retryItems = new List <ExchangeItemContainer>();

            while (itemBuffer.Count > 0)
            {
                Logger.Debug("Committing " + itemBuffer.Count + " messages to EWS.");
                retryItems.Clear();
                tryCount++;
                var start = Environment.TickCount;
                try
                {
                    try
                    {
                        FolderId parentFolderId = GetCreateFolder(previousFolder);
                        var      response       =
                            service.CreateItems(
                                itemBuffer.Select(exchangeItemContainer => exchangeItemContainer.ExchangeItem)
                                .AsEnumerable(), parentFolderId,
                                MessageDisposition.SaveOnly, null);
                        if (response.OverallResult != ServiceResult.Success)
                        {
                            Logger.Warn("Looks like some items succeeded, others failed, checking.");
                            var count        = 0;
                            var successCount = 0;
                            foreach (var serviceResponse in response)
                            {
                                if (serviceResponse.Result == ServiceResult.Success)
                                {
                                    successCount++;
                                    SucceededMessageCount++;
                                }
                                else
                                {
                                    if (serviceResponse.ErrorCode == ServiceError.ErrorTimeoutExpired ||
                                        serviceResponse.ErrorCode == ServiceError.ErrorBatchProcessingStopped ||
                                        serviceResponse.ErrorCode == ServiceError.ErrorServerBusy)
                                    {
                                        // we can attempt these again
                                        Logger.Warn("Failed to import message " +
                                                    itemBuffer[count].MsgDescriptor.Subject + "[" +
                                                    itemBuffer[count].ExchangeItem.ItemClass + "] into " + _username +
                                                    "@" +
                                                    _hostname +
                                                    "/" +
                                                    previousFolder + " [" + (Environment.TickCount - start) + "ms]" +
                                                    ", will retry, not a permanent error : [" +
                                                    serviceResponse.ErrorCode + "]" +
                                                    serviceResponse.ErrorMessage);
                                        retryItems.Add(itemBuffer[count]);
                                    }
                                    else
                                    {
                                        Logger.Error("Failed to import message " +
                                                     itemBuffer[count].MsgDescriptor.Subject + "[" +
                                                     itemBuffer[count].ExchangeItem.ItemClass + "] into " + _username +
                                                     "@" +
                                                     _hostname +
                                                     "/" +
                                                     previousFolder + " [" + (Environment.TickCount - start) + "ms]" +
                                                     ", permanent error : [" + serviceResponse.ErrorCode + "]" +
                                                     serviceResponse.ErrorMessage);
                                        FailedMessageCount++;
                                    }
                                }
                                count++;
                            }
                            Logger.Warn("Saved " + successCount + " of a possible " + itemBuffer.Count +
                                        " messages into " +
                                        _username + "@" + _hostname + "/" + previousFolder + " [" +
                                        (Environment.TickCount - start) + "ms]");
                        }
                        else
                        {
                            Logger.Info("Saved " + itemBuffer.Count + " messages [" + (bufferedSize / 1024) + "Kb] into " +
                                        _username + "@" + _hostname + "/" + previousFolder + " [" +
                                        (Environment.TickCount - start) + "ms]");
                            SucceededMessageCount += itemBuffer.Count;
                        }
                    }
                    // This exception still gets through, its very odd, this should be part of the response codes
                    catch (ServiceLocalException e)
                    {
                        if (
                            Regex.Match(e.Message,
                                        @"The type of the object in the store \(\w+\) does not match that of the local object \(\w+\).")
                            .Success)
                        {
                            // this is an error we can ignore, it just means we sent it as an email message, but its actually a meeting request/response, exchange imports it anyway
                            Logger.Info("Saved " + itemBuffer.Count + " messages [" + (bufferedSize / 1024) + "Kb] into " +
                                        _username + "@" + _hostname + "/" + previousFolder + " [" +
                                        (Environment.TickCount - start) + "ms]");
                            SucceededMessageCount += itemBuffer.Count;
                        }
                        else
                        {
                            Logger.Error("Got a service local exception I didn't understand.");
                            // this will be caught by the bigger try and processed correctly
                            throw e;
                        }
                    }
                    catch (ServerBusyException e)
                    {
                        var retryWait = 30000;
                        // make sure its reasonable
                        if (e.BackOffMilliseconds > retryWait && e.BackOffMilliseconds < 300000)
                        {
                            retryWait = e.BackOffMilliseconds;
                        }
                        Logger.Error("Failed to create items, server too busy, backing off (" + (int)(retryWait / 1000) +
                                     "s) and trying again : " +
                                     e.Message);
                        // Lets loop back around and try again.
                        Thread.Sleep(retryWait); // Sleep x seconds
                        continue;                // run loop again
                    }
                    catch (ServiceRequestException e)
                    {
                        if (e.GetBaseException() is System.Net.WebException)
                        {
                            var retryWait = 30000;
                            Logger.Error("Failed to create items, error connecting to server, backing off (" + (int)(retryWait / 1000) + "s) and trying again : " + e.Message);
                            // Lets loop back around and try again.
                            Thread.Sleep(retryWait); // Sleep x seconds
                            continue;                // run loop again
                        }
                        else
                        {
                            throw e;
                        }
                    }
                }
                catch (Exception e)
                {
                    // This exception means something happened on the server, we try again MaxRetryOnUnknownError times, then fail
                    if (tryCount > MaxRetryOnUnknownError)
                    {
                        Logger.Error("Failed to create items on the server : " + e.Message, e);
                        foreach (var item in itemBuffer)
                        {
                            Logger.Error("Gave up on inserting [" + item.MsgDescriptor.Subject + "] into " + _username + "@" + _hostname + "/" +
                                         previousFolder);
                        }
                        FailedMessageCount += itemBuffer.Count;
                    }
                    else
                    {
                        Logger.Warn("Failed to create items on server, trying " + (MaxRetryOnUnknownError - tryCount) + " more times : " +
                                    e.Message);
                        Thread.Sleep(30000); // sleep 30 second
                        continue;            // run loop again
                    }
                }
                ProcessedMessageCount += itemBuffer.Count - retryItems.Count;
                itemBuffer.Clear();
                bufferedSize = 0;
                // if there are retry items, we need to put them back in the buffer
                if (retryItems.Count > 0)
                {
                    Logger.Info("Will retry " + retryItems.Count + " items, will wait for 30s before retrying.");
                    itemBuffer.AddRange(retryItems);
                    bufferedSize = retryItems.Sum(m => m.MsgDescriptor.RawMessage.Length);
                    Thread.Sleep(30000); // wait 30 seconds before retrying
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// SEND SCHEDULED MAIL
        /// </summary>
        /// <param name="mailID"></param>
        /// <param name="jobID"></param>
        /// <returns></returns>
        public MailResponse SendScheduledMail(int mailID, string jobID, Boolean oneTimeOnly = true)
        {
            mailerdaemonEntities db = new mailerdaemonEntities();



            using (var transaction = db.Database.BeginTransaction())
            {
                try
                {
                    var mail      = db.appmails.Where(x => x.id == mailID).FirstOrDefault();
                    var appClient = db.applications.Where(x => x.id == mail.ApplicationID).FirstOrDefault();


                    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                    service.Credentials = new NetworkCredential(appClient.MailUsername, appClient.MailPassword, appClient.MailDomain);
                    service.Url         = new Uri(appClient.MailServiceUrl);

                    Collection <EmailMessage> messageItems = new Collection <EmailMessage>();

                    EmailMessage newmessage = new EmailMessage(service);
                    newmessage.Body          = mail.Content;
                    newmessage.Subject       = mail.Subject;
                    newmessage.Body.BodyType = BodyType.HTML;
                    newmessage.Importance    = Importance.High;
                    /// ADD MULTIPLE RECIPIENTS
                    ///
                    if (mail.appmailrecipients != null)
                    {
                        foreach (var recipient in mail.appmailrecipients)
                        {
                            newmessage.ToRecipients.Add(recipient.To);
                        }
                    }

                    /// ADD CC RECIPIENTS
                    ///
                    if (mail.appmailccs != null)
                    {
                        foreach (var cc in mail.appmailccs)
                        {
                            newmessage.CcRecipients.Add(cc.To);
                        }
                    }


                    /// ADD BCC RECIPIENTS
                    ///
                    if (mail.appmailbccs != null)
                    {
                        foreach (var bcc in mail.appmailbccs)
                        {
                            newmessage.BccRecipients.Add(bcc.To);
                        }
                    }

                    /// ADD MULTIPLE ATTACHMENTS
                    ///
                    if (mail.appmailattachments != null)
                    {
                        foreach (var amt in mail.appmailattachments)
                        {
                            newmessage.Attachments.AddFileAttachment(amt.Filename, amt.Data);
                        }
                    }



                    // Create a custom extended property and add it to the message.
                    Guid myPropertySetId = new Guid("{20B5C09F-7CAD-44c6-BDBF-8FCBEEA08544}");
                    Guid g;
                    g = Guid.NewGuid();

                    ExtendedPropertyDefinition myExtendedPropertyDefinition = new ExtendedPropertyDefinition(myPropertySetId, "UUID", MapiPropertyType.String);
                    newmessage.SetExtendedProperty(myExtendedPropertyDefinition, g.ToString());
                    newmessage.IsDeliveryReceiptRequested = true;
                    newmessage.IsReadReceiptRequested     = true;

                    messageItems.Add(newmessage);
                    ServiceResponseCollection <ServiceResponse> response = service.CreateItems(messageItems, WellKnownFolderName.SentItems, MessageDisposition.SendAndSaveCopy, null);


                    mail.UID      = g.ToString();
                    mail.isSent   = 1;
                    mail.Retries += 1;
                    db.SaveChanges();


                    appmailjob mailjob = db.appmailjobs.Where(x => x.JobID == jobID).FirstOrDefault();

                    if (mailjob != null)
                    {
                        mailjob.DateLastUpdated = DateTime.Now;
                        mailjob.Status          = (int)JobStatus.UPDATED;
                        db.SaveChanges();
                    }



                    if (oneTimeOnly)
                    {
                        RecurringJob.RemoveIfExists(jobID);
                    }

                    MailResponse mailResp = new MailResponse();
                    mailResp.Result    = "OK";
                    mailResp.MessageID = mail.id;
                    mailResp.MailGUID  = mail.UID;
                    mailResp.JobID     = jobID;

                    transaction.Commit();

                    return(mailResp);
                }

                catch (Exception ex)
                {
                    transaction.Rollback();
                    MailResponse mailResp = new MailResponse();
                    mailResp.Result       = "ERROR";
                    mailResp.MessageID    = -1;
                    mailResp.ErrorMessage = ex.GetBaseException().Message;
                    return(mailResp);
                }
                finally
                {
                    db.Database.Connection.Close();
                }
            }
        }
Exemplo n.º 11
0
        public  bool CreateCalendarEvent(ExchangeService service,Appointment objAppointment,string[] rqdAttendeelist,string[] optionalAttendeelist)
        {          
            try
            {             

                ItemView itemView = new ItemView(100);
                itemView.PropertySet = new PropertySet(BasePropertySet.IdOnly);
                List<Appointment> ToCreate = new List<Appointment>();
                Appointment appointment = new Appointment(service);
                appointment.Subject = objAppointment.Subject;// "Calendar Request from Console App";
                appointment.Location = objAppointment.Location;// "Office365";
                appointment.Start = TimeZoneInfo.ConvertTimeToUtc(objAppointment.Start, TimeZoneInfo.Local);
                appointment.End = TimeZoneInfo.ConvertTimeToUtc(objAppointment.End, TimeZoneInfo.Local);// objAppointment.End;
                appointment.Body = objAppointment.Body;
                appointment.IsReminderSet = objAppointment.IsReminderSet;           
                appointment.IsResponseRequested = false;
                foreach(string req in rqdAttendeelist)
                {
                    appointment.RequiredAttendees.Add(req);
                }
                foreach (string opt in optionalAttendeelist)
                {
                    appointment.OptionalAttendees.Add(opt);
                }
                ToCreate.Add(appointment);
                ServiceResponseCollection<ServiceResponse> CreateResponse = service.CreateItems(ToCreate, WellKnownFolderName.Calendar, MessageDisposition.SaveOnly, SendInvitationsMode.SendOnlyToAll);
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                service = null;
            }
        }
Exemplo n.º 12
0
        public MailStatus sendMailWorker(List <Mails> m, int appID, int agentID)
        {
            //int fileCount = 0;


            // Determine whether to parallelize file processing on each folder based on processor count.
            // int procCount = System.Environment.ProcessorCount;

            ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;

            using (MailerDaemonEntities db = new MailerDaemonEntities())
            {
                //try {

                AppMailAgents appagent = (from a in db.appmailagents
                                          join b in db.appmailagentassignments on a.id equals b.AppMailAgentID
                                          where a.isActive == 1 && b.ApplicationID == appID && b.AppMailAgentID == agentID
                                          select new AppMailAgents
                {
                    id = a.id,
                    username = a.username,
                    password = a.password,
                    domain = a.domain,
                    DateCreated = a.DateCreated
                }).ToList <AppMailAgents>().FirstOrDefault();

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
                service.Credentials = new NetworkCredential(appagent.username, appagent.password, appagent.domain);
                // service.Credentials = new WebCredentials(appagent.username, appagent.password);
                service.Url = new Uri("https://smic1eexphc1.smic.sm.ph/EWS/Exchange.asmx");

                //service.UseDefaultCredentials = true;
                //service.AutodiscoverUrl("*****@*****.**");
                //Parallel.ForEach(m, mm => {
                //    EmailMessage message = new EmailMessage(service);
                //    message.Body=mm.content;
                //    message.Subject = mm.subject;
                //    message.Body.BodyType = BodyType.HTML;

                //    /// ADD MULTIPLE RECIPIENTS
                //    foreach (string r in mm.recipients)
                //    {
                //        message.ToRecipients.Add(r);
                //    }
                //    /// ADD BCC RECIPIENTS
                //    foreach (string b in mm.bcc)
                //    {
                //        message.BccRecipients.Add(b);
                //    }
                //    /// ADD MULTIPLE ATTACHMENTS
                //    foreach (AppMailAttachments amt in mm.attachments)
                //    {
                //         message.Attachments.AddFileAttachment(amt.Filename, amt.Data);
                //    }
                //    message.Update(ConflictResolutionMode.AutoResolve);
                //    message.Send();

                //});


                ////FEATURE NOT IMPLEMENTED DUE TO
                ////NO SUPPORT TO FILE ATTACHMENT
                //Console.WriteLine(service.Url);

                //List<EmailMessage> messages = new List<EmailMessage>();
                Collection <EmailMessage> messageItems = new Collection <EmailMessage>();

                foreach (Mails mm in m)
                {
                    EmailMessage newmessage = new EmailMessage(service);
                    newmessage.Body          = mm.content;
                    newmessage.Subject       = mm.subject;
                    newmessage.Body.BodyType = BodyType.HTML;
                    newmessage.Importance    = Importance.High;
                    /// ADD MULTIPLE RECIPIENTS
                    ///
                    if (mm.recipients != null)
                    {
                        foreach (string r in mm.recipients)
                        {
                            newmessage.ToRecipients.Add(r);
                        }
                    }

                    /// ADD CC RECIPIENTS
                    ///
                    if (mm.cc != null)
                    {
                        foreach (string c in mm.cc)
                        {
                            newmessage.CcRecipients.Add(c);
                        }
                    }


                    /// ADD BCC RECIPIENTS
                    ///
                    if (mm.bcc != null)
                    {
                        foreach (string b in mm.bcc)
                        {
                            newmessage.BccRecipients.Add(b);
                        }
                    }

                    /// ADD MULTIPLE ATTACHMENTS
                    ///
                    if (mm.attachments != null)
                    {
                        foreach (AppMailAttachments amt in mm.attachments)
                        {
                            // newmessage.Attachments.AddFileAttachment(amt.Filename, amt.Data);
                        }
                    }



                    // Create a custom extended property and add it to the message.
                    Guid myPropertySetId = new Guid("{20B5C09F-7CAD-44c6-BDBF-8FCBEEA08544}");
                    Guid g;
                    g = Guid.NewGuid();

                    ExtendedPropertyDefinition myExtendedPropertyDefinition = new ExtendedPropertyDefinition(myPropertySetId, "UUID", MapiPropertyType.String);
                    newmessage.SetExtendedProperty(myExtendedPropertyDefinition, g.ToString());
                    newmessage.IsDeliveryReceiptRequested = true;

                    appmail appm = db.appmails.Where(x => x.id == mm.id).FirstOrDefault();
                    appm.UID = g.ToString();
                    db.SaveChanges();

                    messageItems.Add(newmessage);
                }



                //// Create the batch of email messages on the server.
                //// This method call results in an CreateItem call to EWS.
                //ServiceResponseCollection<ServiceResponse> response = service.CreateItems(messageItems, WellKnownFolderName.Drafts, MessageDisposition.SaveOnly, null);



                // Create and send the batch of email messages on the server.
                // This method call results in an CreateItem call to EWS.
                ServiceResponseCollection <ServiceResponse> response = service.CreateItems(messageItems, WellKnownFolderName.SentItems, MessageDisposition.SendAndSaveCopy, null);



                // Instantiate a collection of item IDs to populate from the values that are returned by the Exchange server.
                Collection <ItemId> itemIds = new Collection <ItemId>();

                // Collect the item IDs from the created email messages.
                foreach (EmailMessage message in messageItems)
                {
                    try
                    {
                        itemIds.Add(message.Id);
                        string UUID = message.ExtendedProperties[0].Value.ToString();


                        Console.WriteLine("Email message '{0}' created successfully. UID {1}.", message.Subject, UUID);
                        appmail appm = db.appmails.Where(x => x.UID == UUID).FirstOrDefault();
                        appm.isSent = 1;
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine(ex.Message);
                        // Print out the exception and the last eight characters of the item ID.
                        Console.WriteLine("Exception while creating message {0}: {1}", message.Id.ToString().Substring(144), ex.Message);
                    }
                }

                // Check for success of the CreateItems method call.
                if (response.OverallResult == ServiceResult.Success)
                {
                    Console.WriteLine("All locally created messages were successfully saved to the Drafts folder.");
                    Console.WriteLine("\r\n");
                }

                // If the method did not return success, print the result message for each email.
                else
                {
                    int counter = 1;

                    foreach (ServiceResponse resp in response)
                    {
                        // Print out the result and the last eight characters of the item ID.
                        Console.WriteLine("Result (message {0}), id {1}: {2}", counter, itemIds[counter - 1].ToString().Substring(144), resp.Result);
                        Console.WriteLine("Error Code: {0}", resp.ErrorCode);
                        Console.WriteLine("ErrorMessage: {0}\r\n", resp.ErrorMessage);
                        Console.WriteLine("\r\n");

                        counter++;
                    }
                }

                //}
                //catch (Exception ex) {

                //    Exception e = ex.GetBaseException();
                //    //throw new Exception(e.ToString());

                //}
                //finally {
                //    db.Database.Connection.Close();
                //}
            }



            return(null);
        }
Exemplo n.º 13
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;
            }
        }
Exemplo n.º 14
0
        /**
         * Function Add the Holidays
         **/
        static void AddHolidays(ExchangeService service, List<string[]> holidays, List<string> mailboxes)
        {
            // Log file
            string datetimeString = DateTime.Now.ToString("MMddyyyy");
            string logfile = "../../logs/" + datetimeString + "_add_holiday_log.txt";

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

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

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

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

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

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

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

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

                        uga_holidays.Add(appointment);

                    }

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

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

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

                    }

                    // Clear impersonation.
                    service.ImpersonatedUserId = null;

                }

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

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

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

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

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

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

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

                            if (items.TotalCount > 0)
                            {

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

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

                                    ids.Add(item.Id);

                                }

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

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

                            // Rerun: Adds

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

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

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

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

                                holidays.Add(appointment);

                            }

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

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

                        // Clear impersonation.
                        service.ImpersonatedUserId = null;

                    }
                }
            }
        }