Dynamic CRM调用WCF接口获取选项集的说明数据

发布时间 2023-09-15 15:09:50作者: 江渔湖

一、SQL语句:

  select Value Id,Label Name 

  from LocalizedLabel a left join AttributePicklistValue b on a.ObjectId=b.AttributePicklistValueId

  left join OptionSet c on b.OptionSetId=c.OptionSetId

  where a.ComponentState=0 and b.ComponentState=0 and c.ComponentState=0

  and c.Name='{name}' and a.LanguageId=2052

  and a.ObjectColumnName='{desc}' order by Value asc

  参数说明:name 为选项集名称。desc为字段名称:Description,选项集说明;DisplayName,选项集标签

 

二、后端WCF接口封装获取选项集说明数据的方法

    /// <summary>
    /// 获取选项集说明数据
    /// </summary>
    /// <param name="name">选项集的名称</param>
    /// <returns></returns>
    //[WebGet(RequestFormat = WebMessageFormat.Json)]
    public static string GetOptionSetList(string name,string desc)
    {
      KDOperateResult response = new KDOperateResult();
      var list = new List<OptionSet>();
      try
      {
        if (!string.IsNullOrWhiteSpace(name))
          list = SQLDBHELPER.ExecSQL<OptionSet>($"select Value Id,Label Name from LocalizedLabel a left join AttributePicklistValue b on                                                                                                                          a.ObjectId=b.AttributePicklistValueId left join OptionSet c on b.OptionSetId=c.OptionSetId where                                                                                                                                 a.ComponentState=0 and b.ComponentState=0 and c.ComponentState=0 and c.Name='{name}' and                                                                                                                         a.LanguageId=2052 and a.ObjectColumnName='{desc}' order by Value asc");
        response.code = "0";
        response.message = new JavaScriptSerializer().Serialize(list);
      }
      catch (Exception ex)
      {
        LoggerHelper.Instance.Error("UploadAttachmentKD索赔获取选项集索赔明细附件说明出错:", ex);
        response.code = "2";
        response.message = ex.Message.ToString();
      }

      return new JavaScriptSerializer().Serialize(response);
    }
 
三、调用WCF接口的三种方式
  1.在浏览器地址输入已GET方式调用,参数在地址栏通过?选项集名称&desc方式连接
    WCF地址/rest/GetOptionSetList?name=选项集名称&desc=Description
     说明:使用该方式需要在方法上面打赏WebGet标签:[WebGet(RequestFormat = WebMessageFormat.Json)]
 
  2.通过POST方式调用

      var entity = {};
      entity.foton_action = "GetOptionSetList";
      entity.foton_actionparams = JSON.stringify({
        name: 选项集名称,
        desc: Description
      })

 

      $.ajax({
        url: "WCF地址/OTDDMSService.svc/rest/" + entity.foton_action,
        type: "POST",
        data: entity.foton_actionparams,
        contentType: "application/json;charset=utf-8",
        async: entity.async == undefined ? true : entity.async,
        success: function (data) {
        },
        error: function (xhr, textStatus, errorThrown) {
        }
      })

 

  3.通过触发插件的方式,在插件后端调用

   说明:需新建一实体,调用时向实体插入数据,并触发该实体的create插件,在插件中调用WCF接口实现

      var entity = {};
      entity.foton_action = "GetOptionSetList";
      entity.foton_actionparams = JSON.stringify({
        name: 选项集名称,
        desc: Description
      })

      $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: Xrm.Page.context.getClientUrl() + "/api/data/v8.2/foton_pluginactions",
        data: JSON.stringify(entity),
        beforeSend: function (XMLHttpRequest) {
          XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
          XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
          XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        async: entity.async == undefined ? true : entity.async,
        //success: function (data) {
          // if (cbfun != undefined)
          // cbfun(data);
        //},
        error: function (xhr) {
          if (cbfun != undefined) {
            var pData = JSON.parse(JSON.parse(xhr.responseText.toString()).error.message);
            cbfun(pData);
          }
        }
      });

 

   后端插件代码实现如下:   

    public class PluginAction : IPlugin
    {
      public void Execute(IServiceProvider serviceProvider)
      {
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService service = serviceFactory.CreateOrganizationService(null);

        try
        {
          string result = "";

          Entity target = (Entity)context.InputParameters["Target"];
          string environment = target.GetAttributeValue<string>("foton_environment");
          string action = target.GetAttributeValue<string>("foton_action");
          string actionParams = target.GetAttributeValue<string>("foton_actionparams");

          result = post(environment, action, actionParams);

          StringBuilder strPluginTrace = new StringBuilder();
          strPluginTrace.Append("【environment】" + environment + "。");
          strPluginTrace.Append("【action】" + action + "。");
          strPluginTrace.Append("【actionParams】" + actionParams + "。");
          strPluginTrace.Append("【result】" + result + "。");

          PluginTrace.info(strPluginTrace.ToString());

          throw new InvalidPluginExecutionException("error:" + result);
        }
        catch (Exception ex)
        {
          OperateResultByPlugin operateResultByPlugin = null;

          if (ex.Message.IndexOf("_red_fox_error") == 0)
          {
            OperateResultByInterface operateResultByInterface = JsonConvert.DeserializeObject<OperateResultByInterface>(ex.Message.Substring(14));
            operateResultByPlugin = JsonConvert.DeserializeObject<OperateResultByPlugin>(operateResultByInterface.d);
          }
          else
          {
            operateResultByPlugin = new OperateResultByPlugin();
            operateResultByPlugin.code = "-2";
            operateResultByPlugin.message = ex.Message;

            PluginTrace.error(ex.Message);
          }

          throw new InvalidPluginExecutionException(JsonConvert.SerializeObject(operateResultByPlugin));
        }
      }


      #region 发送api请求,返回api处理结果
      private string post(string environment, string action, string actionparams)
      {
        try
        {
          string url_prefix = ""WCF地址/rest/"";
          string url_postfix = action;
          string url_params = actionparams;

 

          byte[] byteArray = Encoding.UTF8.GetBytes(url_params);

          HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url_prefix + url_postfix));
          webRequest.Proxy = null;
          webRequest.Timeout = 300000;
          webRequest.Method = "POST";
          webRequest.ContentType = "application/json;charset=utf-8";
          webRequest.ContentLength = byteArray.Length;
          Stream stream = webRequest.GetRequestStream();
          stream.Write(byteArray, 0, byteArray.Length);
          stream.Close();

          HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
          StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"));

          return sr.ReadToEnd();
        }
        catch (Exception ex)
        {
          throw new InvalidPluginExecutionException("请求接口失败:" + ex.ToString());
        }
      }
      #endregion


      #region 结果模型
      private class OperateResultByInterface
      {
        public string d { get; set; }
      }


      private class OperateResultByPlugin
      {
        public string code { get; set; }
        public string message { get; set; }
        public string extra { get; set; }
      }
      #endregion
    }