//main EWS entry
        protected void EWS(object source, System.Timers.ElapsedEventArgs e)
        {
            writeLog("Start EWS Operation");


            Stopwatch s_watch = new Stopwatch();

            s_watch.Start();



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

            sql_delete.ExecuteNonQuery();

            sql_conn().Close();


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

            DataSet ds = new DataSet();

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

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


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


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

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

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


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

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

                cmd_str_err.ExecuteNonQuery();

                sql_conn().Close();
            }

            EmailAddressCollection myRoomLists = es.GetRoomLists();

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

            DataTable dt_sql = new DataTable();

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

            EmailAddress address = new EmailAddress();

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

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

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

            int room_count = room_addresses.Count;

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

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


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


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

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


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

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


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


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

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

            writeLog("all rooms operation finsihed");

            Stopwatch sw_dt_sql = new Stopwatch();

            sw_dt_sql.Start();

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

                sql_dt_insert.DestinationTableName = "Meeting_Status_Loop";

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

                sql_conn().Close();

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


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

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

            sw_dt_sql.Stop();
            writeLog("\r\n" + " time cost of dt insert is:" + sw_dt_sql.ElapsedMilliseconds.ToString());
        }
Exemple #2
0
        private void MainFormLoad(object sender, EventArgs e)
        {
            Form.CheckForIllegalCrossThreadCalls = false;
            Action <string> action = str => this.lbLog.Items.Add(str);

            Logger.AddAlgorithm(new ComponentLogWriteAlgorithm(action));

            this.panel1.Enabled = false;
            this.generateToolStripMenuItem.Enabled     = false;
            this.saveSettingsToolStripMenuItem.Enabled = false;

            this.splitContainer4.SplitterWidth = 10;
            this.splitContainer1.SplitterWidth = 10;
            this.RearrangeCountControls();

            ToolStripButton tsbtnMove =
                new ToolStripButton(LocalizibleStrings.BtnAddSelectedToMailList)
            {
                DisplayStyle = ToolStripItemDisplayStyle.Image,
                Image        = LocalizibleStrings.ArrowRight
            };

            tsbtnMove.Click += (o, args) =>
            {
                IEnumerable <StoredContact> storedContacts =
                    this.clTargetContacts.dgObjects.Objects.Cast <StoredContact>().ToList();

                foreach (Contact obj in
                         from Contact obj in this.clEwsContacts.dgObjects.SelectedObjects
                         let existed = storedContacts.FirstOrDefault(s => s.UniqId == obj.Id.UniqueId)
                                       where existed == null
                                       select obj)
                {
                    this.clTargetContacts.dgObjects.AddObject(new StoredContact(obj));
                }
            };

            this.clEwsContacts._barTools.Items.Insert(2, tsbtnMove);

            string mailTemplateFolder;
            string eventTemplateFolder;

            switch (Thread.CurrentThread.CurrentUICulture.LCID)
            {
            case LocalizationHelper.EnInt:
                this.englishToolStripMenuItem.Checked = true;
                this.russianToolStripMenuItem.Checked = false;
                mailTemplateFolder  = Config.EmailTemplateFolderEn;
                eventTemplateFolder = Config.EventTemplateFolderEn;
                break;

            case LocalizationHelper.RuInt:
                this.russianToolStripMenuItem.Checked = true;
                this.englishToolStripMenuItem.Checked = false;
                mailTemplateFolder  = Config.EmailTemplateFolderRu;
                eventTemplateFolder = Config.EventTemplateFolderRu;
                break;

            default:
                this.englishToolStripMenuItem.Checked = true;
                this.russianToolStripMenuItem.Checked = false;
                mailTemplateFolder  = Config.EmailTemplateFolderEn;
                eventTemplateFolder = Config.EventTemplateFolderEn;
                break;
            }

            this.SetEwsContactsColumns();
            this.SetMailTemplatesColumns();
            this.SetEventTemplatesColumns();
            this.SetTargetContactsColumns();

            this.clEwsContacts.tsbtnFilteredProperties.Visible = false;
            this.clEwsContacts.tsbtnCreate.Visible             = false;
            this.clEwsContacts.tsbtnEdit.Visible               = false;
            this.clEwsContacts.tsbtnDelete.Visible             = false;
            this.clEwsContacts.tsbtnFilterSettings.Visible     = false;
            this.clEwsContacts.tsbtnFilteredProperties.Visible = false;

            this.clEwsContacts.tsbtnRefresh.Text     = LocalizibleStrings.BtnRefresh;
            this.clEwsContacts.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clEwsContacts.tsbtnSearch.Text      = LocalizibleStrings.BtnSearch;
            this.clEwsContacts.tslbSearch.Text       = LocalizibleStrings.LbSearch;
            this.clEwsContacts.tslbCount.Text        = LocalizibleStrings.LbCount;

            this.clEwsContacts.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    Folder contactsFolder;
                    if (!TryGetFolder(Config.ContactFolder, out contactsFolder))
                    {
                        Logger.Message(LocalizibleStrings.TryLoadFromDefault);
                        contactsFolder = ContactsFolder.Bind(_service, WellKnownFolderName.Contacts);
                    }

                    SearchFilter sf = new SearchFilter.IsEqualTo(ItemSchema.ItemClass, @"IPM.Contact");

                    FindItemsResults <Item> items =
                        contactsFolder.FindItems(sf, new ItemView(int.MaxValue));
                    this.clEwsContacts.dgObjects.SetObjects(items.ToList());
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetContactList, exc);
                }
            };

            this.clMailTemplates.tsbtnFilteredProperties.Visible = false;
            this.clMailTemplates.tsbtnCreate.Visible             = false;
            this.clMailTemplates.tsbtnEdit.Visible               = false;
            this.clMailTemplates.tsbtnDelete.Visible             = false;
            this.clMailTemplates.tsbtnFilterSettings.Visible     = false;
            this.clMailTemplates.tsbtnFilteredProperties.Visible = false;

            this.clMailTemplates.tsbtnRefresh.Text     = LocalizibleStrings.BtnRefresh;
            this.clMailTemplates.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clMailTemplates.tsbtnSearch.Text      = LocalizibleStrings.BtnSearch;
            this.clMailTemplates.tslbSearch.Text       = LocalizibleStrings.LbSearch;
            this.clMailTemplates.tslbCount.Text        = LocalizibleStrings.LbCount;

            this.clMailTemplates.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    /*Folder templatesFolder;
                     * if (!TryGetFolder(mailTemplateFolder, out templatesFolder))
                     *  return;
                     *
                     * FindItemsResults<Item> items =
                     *  templatesFolder.FindItems(new ItemView(int.MaxValue));*/

                    IList <Storage.Message> items = new List <Storage.Message>();

                    // ReSharper disable once LoopCanBeConvertedToQuery
                    // под отладчиком всякая фигня происходит если linq
                    foreach (string path in
                             Directory.GetFiles(Config.GetParam(mailTemplateFolder)))
                    {
                        items.Add(new Storage.Message(path));
                    }

                    this.clMailTemplates.dgObjects.SetObjects(items.ToList());
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetMailTemplateList, exc);
                }
            };

            this.clEventTemplates.tsbtnCreate.Visible             = false;
            this.clEventTemplates.tsbtnEdit.Visible               = false;
            this.clEventTemplates.tsbtnDelete.Visible             = false;
            this.clEventTemplates.tsbtnFilterSettings.Visible     = false;
            this.clEventTemplates.tsbtnFilteredProperties.Visible = false;

            this.clEventTemplates.tsbtnRefresh.Text     = LocalizibleStrings.BtnRefresh;
            this.clEventTemplates.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clEventTemplates.tsbtnSearch.Text      = LocalizibleStrings.BtnSearch;
            this.clEventTemplates.tslbSearch.Text       = LocalizibleStrings.LbSearch;
            this.clEventTemplates.tslbCount.Text        = LocalizibleStrings.LbCount;

            this.clEventTemplates.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    /*Folder templatesFolder;
                     * if (!TryGetFolder(eventTemplateFolder, out templatesFolder))
                     *  return;
                     *
                     * FindItemsResults<Item> items =
                     *  templatesFolder.FindItems(new ItemView(int.MaxValue));*/

                    List <Storage.Message> tasks =
                        Directory.GetFiles(Config.GetParam(eventTemplateFolder))
                        .Select(t => new Storage.Message(t))
                        .ToList();

                    this.clEventTemplates.dgObjects.SetObjects(tasks);
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetEventTemplateList, exc);
                }
            };

            this.clTargetContacts.tsbtnCreate.Text      = LocalizibleStrings.BtnCreate;
            this.clTargetContacts.tsbtnDelete.Text      = LocalizibleStrings.BtnDelete;
            this.clTargetContacts.tsbtnRefresh.Text     = LocalizibleStrings.BtnRefresh;
            this.clTargetContacts.tsbtnClearFilter.Text = LocalizibleStrings.BtnClear;
            this.clTargetContacts.tsbtnSearch.Text      = LocalizibleStrings.BtnSearch;
            this.clTargetContacts.tslbSearch.Text       = LocalizibleStrings.LbSearch;
            this.clTargetContacts.tslbCount.Text        = LocalizibleStrings.LbCount;

            this.clTargetContacts.tsbtnCreate.Visible             = true;
            this.clTargetContacts.tsbtnEdit.Visible               = false;
            this.clTargetContacts.tsbtnDelete.Visible             = true;
            this.clTargetContacts.tsbtnFilterSettings.Visible     = false;
            this.clTargetContacts.tsbtnFilteredProperties.Visible = false;

            this.clTargetContacts.dgObjects.TriStateCheckBoxes = false;
            this.clTargetContacts.dgObjects.RenderNonEditableCheckboxesAsDisabled = false;
            this.clTargetContacts.dgObjects.UseSubItemCheckBoxes = true;

            ToolStripButton tsbtnSave =
                new ToolStripButton(LocalizibleStrings.BtnSaveAll)
            {
                DisplayStyle = ToolStripItemDisplayStyle.Image,
                Image        = LocalizibleStrings.Save
            };

            tsbtnSave.Click +=
                (o, args) =>
            {
                IEnumerable <StoredContact> contacts =
                    this.clTargetContacts.dgObjects.Objects.Cast <StoredContact>();
                foreach (StoredContact contact in contacts)
                {
                    contact.Save();
                }
            };

            this.clTargetContacts._barTools.Items.Insert(1, tsbtnSave);

            this.clTargetContacts.tsbtnRefresh.Click += (s, args) =>
            {
                try
                {
                    this.clTargetContacts.dgObjects.SetObjects(StoredContact.GetAll());
                }
                catch (Exception exc)
                {
                    Logger.Error(LocalizibleStrings.CannotGetStoredContacts, exc);
                }
            };

            this.clTargetContacts.tsbtnCreate.Click +=
                (o, args) => this.clTargetContacts.dgObjects.AddObject(new StoredContact());

            this.clTargetContacts.tsbtnDelete.Click += (o, args) =>
            {
                DialogResult res = MessageBox.Show(
                    LocalizibleStrings.DeleteConfirmation,
                    LocalizibleStrings.Warning,
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Warning,
                    MessageBoxDefaultButton.Button2);

                if (res == DialogResult.No)
                {
                    return;
                }

                foreach (StoredContact cont in this.clTargetContacts.dgObjects.SelectedObjects)
                {
                    try
                    {
                        this.clTargetContacts.dgObjects.RemoveObject(cont);
                        cont.Delete();
                    }
                    catch (Exception exc)
                    {
                        Logger.Error(LocalizibleStrings.CannotDeleteContact + cont.FileName, exc);
                    }
                }
            };
        }
        //use mutilable process
        //protected void GetData_EWS(string username, string pwd, Mailbox mailbox, string RoomName)
        protected void GetData_EWS(object obj)
        {
            //List<string> par_get = obj as List<string>;

            DataTable dt_get = obj as DataTable;

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

            ExchangeService es = new ExchangeService(ExchangeVersion.Exchange2013);

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


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

            Stopwatch sw = new Stopwatch();


            try
            {
                sw.Start();


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

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


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


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


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



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

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

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

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

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

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


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

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

            catch (Exception et)
            {
                writeLog("there is an error when operate at" + RoomName + " the error is:\r\n" + et);
            }
        }