1.在dynamics365中创建一个实体来存放编号
2.vs2019中的代码
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 preCreateLeads
{
public class preCreateLeads : 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"];//传入单条数据
try
{
if (context.Depth > 1) return;
string subjectsid = "";
string date = DateTime.Now.ToString("yyyyMMdd");
QueryExpression qe = new QueryExpression("new_leads_auto");//查询存放编号的实体
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_leads_auto");//需要实现自动编号的实体
entity.Id = result.Entities[0].Id;
entity["new_name"] = subjectsid;
service.Update(entity);
}
else
{
subjectsid = date + "0001";
Entity entity1 = new Entity("new_leads_auto");
entity1["new_name"] = subjectsid;
service.Create(entity1);
}
}
catch (Exception)
{
throw;
}
}
}
}
3.注册插件的时候要选择 Pre-operation(Post-operation是无效的)