也谈MS CRM4中实现模糊查找

    看了星吧客的文章<<MSCRM4 让视图查找功能默认实现模糊查找>>,确实在项目实施中有这种需求出现,End User希望实现完全的模糊查询,而现有系统中给定的功能呢,只是在输入的查询字符之后加入了通配符以便进行模糊查找。举例来说,用户在客户列表的搜索查找框中输入数字"8",MS CRM系统会在处理时,将"8"扩充为"8*",由此可见,这只是部分的模糊匹配,即,只能够查找出以"8"开头的所有数据,而End User经常希望的结果是,只要数据中还有8,就要被挑选出来,也就是形如"*8*"的查询。

    星吧客的做法,是修改了源文件,一种Unsupported方法,我也提供另一个方法的思路吧。

    主旨想法就是借用MS CRM中的Plugin,将完全模糊查询功能实现在一个Plugin中。那么应该截获那个消息呢?凭感觉,想到了Fetch方法,不过,在SDK给的注册工具中,并没有相对应的消息,那么是什么呢?在Reference中找到ExecuteFetch Message方法,还是没有对应的消息,不过,倒是有Execute消息,是不是可以用乜?try一下,get it。在进行查找时,使用Execute方法可以拦截到该查找请求。分析context参数的属性,如下图所示。

image

其中,InputParameters[“FetchXml”]对应的值如下:

<fetch distinct="false" mapping="logical" page="1" count="50">
  <entity name="account">
    <attribute name="name" />
    <attribute name="accountnumber" />
    <attribute name="createdon" />
    <attribute name="modifiedon" />
    <attribute name="accountid" />
    <attribute name="name" />
    <attribute name="accountnumber" />
    <attribute name="modifiedon" />
    <attribute name="createdon" />
    <filter type="and">
      <filter type="and">
        <condition attribute="statecode" operator="eq" value="0" />
      </filter>
      <filter type="or">
        <condition attribute="name" operator="like" value="8%" />
        <condition attribute="accountnumber" operator="like" value="8%" />
      </filter>
    </filter>
  <order attribute="name" descending="false" />
  </entity>
</fetch>

从上面红色以及蓝色着色的部分,可以看到MS CRM系统是如何处理,那么在待开发的Plugin的Execute方法中,只要将形如"8%"的value更改为"%8%"不就可以了么?

    我的代码如下:

public void Execute(IPluginExecutionContext context)
{
    if (context.InputParameters.Contains("FetchXml") == false) return;
    string fetchXml = context.InputParameters["FetchXml"].ToString();
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(fetchXml);
    XmlNodeList nodeList = doc.GetElementsByTagName("condition");
    foreach (XmlNode node in nodeList)
    {
        if (node.Attributes["operator"].Value != "like") continue;
        if (node.Attributes["value"] == null) continue;
        node.Attributes["value"].Value = "%" + node.Attributes["value"].Value + "%";
    }
    context.InputParameters["FetchXml"] = doc.InnerXml;
}

注册Step时,选择Execute消息,以及PreStage,其他的选项不必修改。

 

如此,即可实现完全模糊查找功能。

posted on 2009-06-27 19:07  石头居  阅读(1067)  评论(4编辑  收藏  举报