简体   繁体   English

C#-Outlook VSTO-获取AdvancedSearchComplete进行触发

[英]C# - Outlook VSTO - Getting AdvancedSearchComplete to trigger

I am converting an old Outlook VBA macro I created to a C# VSTO Add-in. 我将我创建的旧Outlook VBA宏转换为C#VSTO加载项。 This tool is for bulk archiving of emails to various public folders and a local .pst file and needs to be able to find emails based on a user's search criteria. 该工具用于将电子邮件批量存档到各种公用文件夹和本地.pst文件,并且需要能够根据用户的搜索条件查找电子邮件。 I had a whale of a time getting the AdvancedSearchComplete event to trigger in VBA, but eventually got it to work. 我花了很多时间让AdvancedSearchComplete事件在VBA中触发,但最终使它起作用。 Of course, I am now have the same problem in the C# VSTO add-in. 当然,我现在在C#VSTO加载项中有同样的问题。

To use the tool, the user will input their criteria on a userform, then click the Find Emails button to perform the search with the results populating a datagridview. 要使用该工具,用户将在用户表单上输入他们的条件,然后单击“ 查找电子邮件”按钮执行搜索,并在结果中填充datagridview。

public partial class Email_Archiver : Form
{

    public Email_Archiver()
    {
        InitializeComponent();

        //Add event handlers
        Globals.ThisAddIn.Application.AdvancedSearchComplete += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_AdvancedSearchCompleteEventHandler(Application_AdvancedSearchComplete);
    }

    public void Application_AdvancedSearchComplete(Microsoft.Office.Interop.Outlook.Search SearchObject)
    { //Handles AdvancedSearchComplete event

        if (SearchObject.Tag == "Archiver Search")
        {
            OutlookFunctions.SearchComplete = true;
            MessageBox.Show(this, "Search Complete!","Email Search Error",MessageBoxButtons.OK);
        }

    }

    private void Find_Button_Click(object sender, EventArgs e)
    {

        //Set datagridview datasource
        EmailList.DataSource = FindEmails();
        EmailList.Columns["EntryID"].Visible = false;

    }

    public DataTable FindEmails()
    {
        var dt = new DataTable();

        //Format DataTable
        dt.Columns.Add("EntryID", typeof(string));
        dt.Columns.Add("Project No.", typeof(int));
        dt.Columns.Add("Subject", typeof(string));
        dt.Columns.Add("Sender", typeof(string));
        dt.Columns.Add("Recipient", typeof(string));
        dt.Columns.Add("Time Sent", typeof(DateTime));
        dt.Columns.Add("Size", typeof(decimal));

        //Do stuff to get "searchFolders" and "searchCriteria" from form
        //...

        dt = OutlookFunctions.RunAdvancedSearch(searchFolders, searchCriteria);

        return dt;
    }
}


class OutlookFunctions
{

    public static bool SearchComplete;

    public static DataTable RunAdvancedSearch(string[] searchFolders, string[] searchCriteria)
    {

        //Get Outlook namespace
        var oApp = Globals.ThisAddIn.Application;
        var oNS = oApp.GetNamespace("mapi");
        Microsoft.Office.Interop.Outlook.Search advSearch = null;

        //Do other stuff to properly set up the scope and filter
        //...

        //Perform search
        SearchComplete = false;
        try
        {
            advSearch = oApp.AdvancedSearch(scope, filter, false, "Archiver Search");
        }
        catch (System.Exception ex)
        {
            MessageBox.Show("An error has occurred during the search for emails. \n \n"
                    + ex.Message);
            return null;
        }

        Stopwatch timer = new Stopwatch();
        timer.Start();

        while (!SearchComplete && timer.Elapsed.TotalSeconds < 10)
        {
            //Do nothing
        }

        if (!SearchComplete)
        {
            advSearch.Stop();
        }

        if (advSearch != null)
        {
            var resultTable = new DataTable();

            //Send results to resultTable

            return resultTable;
        }

        return null;

    }

}

The search works and I get the proper results, but I had to add in the timer to make things move along, otherwise the code never finishes because AdvancedSearchComplete isn't triggered. 搜索有效,我得到了正确的结果,但是我必须添加计时器以使事情继续进行,否则代码将不会完成,因为不会触发AdvancedSearchComplete I still get all of the emails I'm looking for and doing essentially the same search just in the Outlook explorer, I get the same results in a fraction of a second. 我仍然可以得到所有我要查找的电子邮件,并且仅在Outlook资源管理器中进行基本上相同的搜索,而在一秒钟之内,我可以获得相同的结果。

After the timer ends the search and the datagridview is filled with the results, THEN the AdvancedSearchComplete fires and I get my "Search Complete!" 在计时器结束搜索并且datagridview填充了结果之后,然后AdvancedSearchComplete触发,我得到了“搜索完成!”。 message. 信息。

What am I missing here that is keeping the event from triggering to end the search (in a timely fashion)? 我在这里遗漏了什么,导致该事件无法触发(及时)结束搜索?

You could refer to the following code about using backgroundwork: 您可以参考以下有关使用后台工作的代码:

BackgroundWorker bw = new BackgroundWorker();
    private void button1_Click(object sender, EventArgs e)
    {
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        if (bw.IsBusy != true)
        {
            bw.RunWorkerAsync();
        }
    }
    private void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        //
        // Boring.... Do your long work
        //
        System.Threading.Thread.Sleep(20000);
    }
    private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (this.InvokeRequired)
        {
            //Hide your form here
            this.Invoke(new MethodInvoker(delegate { this.Close(); }));
        }
    }

It appears that any code following the initiation for the AdvancedSearch method will essentially end the search without triggering the AdvancedSearchComplete or AdvancedSearchStopped events. 看起来,启动AdvancedSearch方法之后的任何代码实际上都将结束搜索而不会触发AdvancedSearchComplete或AdvancedSearchStopped事件。

Instead, I now have the following in the ThisAddIn class: 相反,我现在在ThisAddIn类中具有以下内容:

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    //Create task pane object
    archiverTaskPane1 = new ArchiverTaskPane();
    customTaskPane = this.CustomTaskPanes.Add(archiverTaskPane1, "Title");

    //Add event handler for opening task pane
    customTaskPane.VisibleChanged += new EventHandler(customTaskPane_VisibleChanged);

    //Add event handler for Outlook's AdvancedSearch
    Globals.ThisAddIn.Application.AdvancedSearchComplete += new Outlook.ApplicationEvents_11_AdvancedSearchCompleteEventHandler(Application_AdvancedSearchComplete);
}

public void Application_AdvancedSearchComplete(Microsoft.Office.Interop.Outlook.Search SearchObject)
{
    DataTable dt = new DataTable();
    OutlookFunctions oFunctions = new OutlookFunctions();
    dt = oFunctions.BuildResults(SearchObject.Results);
    this.archiverTaskPane1.DataGridFiller(dt);
}

In the ArchiverTaskPane Class (formerly Email_Archiver Form - I REALLY liked the Task Pane idea) 在ArchiverTaskPane类中(以前是Email_Archiver表单-我真的很喜欢Task Pane的想法)

private void Find_Button_Click(object sender, EventArgs e)
{
    FindEmails();
}

public void FindEmails()
{
    DataTable dt = new DataTable();

    //Add columns to DataTable

    //Do stuff to get "searchFolders" and "searchCriteria" from form
    //...

    //Create OutlookFunctions instance
    OutlookFunctions oFunctions = new OutlookFunctions();
    oFunctions.RunAdvancedSearch(searchFolders, searchCriteria);
}

public void DataGridFiller(DataTable results)
{
    EmailList.DataSource = results;
}

In the OutlookFunctions Class: 在OutlookFunctions类中:

public static DataTable RunAdvancedSearch(string[] searchFolders, string[] searchCriteria)
{
    //Get Outlook namespace
    var oApp = Globals.ThisAddIn.Application;
    var oNS = oApp.GetNamespace("mapi");
    Microsoft.Office.Interop.Outlook.Search advSearch = null;

    //Do other stuff to properly set up the scope and filter
    //...

    //Perform search
    SearchComplete = false;
    try
    {
        advSearch = oApp.AdvancedSearch(scope, filter, false, "Archiver Search");
    }
    catch (System.Exception ex)
    {
        MessageBox.Show("An error has occurred during the search for emails. \n \n"
                + ex.Message);
    }
}

public DataTable BuildResults(Results searchResults)
{
    DataTable resultTable = new DataTable();

    //Do stuff to build DataTable from search results
    //...

    return resultTable;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM