1.创建一个实体存放编号
2.代码如下:
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PostCreateLeads
{
public class PostCreatefollowup : 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);
Entity targer = (Entity)context.InputParameters["Target"];//传入单条数据
if (context.Depth > 1) return;//深度防止死循环
string subjectsid = "";
var a = DateTime.Now.Year.ToString();
var b= DateTime.Now.Month.ToString();
if (DateTime.Now.Month < 10)
{
b = "0" + b;
}
var c= DateTime.Now.Day.ToString();
if (DateTime.Now.Day < 10)
{
c = "0" + c;
}
string date = a + b + c;
QueryExpression qe = new QueryExpression("new_zdbh");//存放编号的实体名称
qe.Orders.Add(new OrderExpression() { AttributeName = "new_name", OrderType = OrderType.Descending });
qe.ColumnSet.AddColumns("new_name");//存放编号的实体的字段名称
EntityCollection result = service.RetrieveMultiple(qe);
if (result.Entities.Count > 0)
{
if (result.Entities[0].Contains("new_name"))
{
string sid = result.Entities[0]["new_name"].ToString();
DateTime dt = DateTime.ParseExact(sid.Substring(0, 8), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
if (dt.Year < DateTime.Now.Year)
{
sid = "0";
}
else if (dt.Month < DateTime.Now.Month)
{
sid = "0";
}
else if (dt.Day < DateTime.Now.Day)
{
sid = "0";
}
if (sid.Length > 8)
{
sid = sid.Substring(8).ToString();
}
int ssid = Convert.ToInt32(sid) + 1;
int length = 4 - ssid.ToString().Length;
for (int i = 0; i < length; i++)
{
subjectsid += "0";
}
subjectsid = date += subjectsid += ssid;
Entity entity = new Entity("new_zdbh");//存放编号实体
entity.Id = result.Entities[0].Id;
entity["new_name"] = subjectsid;
service.Update(entity);
Entity entity3 = new Entity("new_followup");//跟进任务实体
entity3["new_accountid"] = targer["new_accountid"]; //查找类型
entity3["ownerid"] = targer["ownerid"];
entity3["modifiedby"] = targer["modifiedby"];
entity3["new_name"] = "FW" + subjectsid;
service.Create(entity3);
}
}
else
{
subjectsid = "0001";
Entity entity1 = new Entity("new_zdbh");//存放编号实体
entity1["new_name"] = date+subjectsid;
service.Create(entity1);
Entity entity2 = new Entity("new_followup");//跟进任务实体
entity2["new_accountid"] = targer["new_accountid"]; //查找类型
entity2["ownerid"] = targer["ownerid"];
entity2["modifiedby"] = targer["modifiedby"];
entity2["new_name"] = "FW" + date + subjectsid;
service.Create(entity2);
}
}
}
}
3.注册插件的时候:事件:选择Create、实体选择:销售线索 、选择Post-operation