C# CRM 2013发生错误时如何创建实体
我在CRM 2013中创建了自定义错误记录器,该记录器具有将错误信息保存到CRM实体的功能。我调试代码,发现代码运行良好。但问题是,当CRM回滚事务时,日志实体也会消失。我想知道是否有可能在catch块上创建实体并仍然抛出那个错误C# CRM 2013发生错误时如何创建实体,c#,dynamics-crm,C#,Dynamics Crm,我在CRM 2013中创建了自定义错误记录器,该记录器具有将错误信息保存到CRM实体的功能。我调试代码,发现代码运行良好。但问题是,当CRM回滚事务时,日志实体也会消失。我想知道是否有可能在catch块上创建实体并仍然抛出那个错误 public void Execute(IServiceProvider serviceProvider) { try { ... }
public void Execute(IServiceProvider serviceProvider)
{
try
{
...
}
catch (Exception ex)
{
IPluginExecutionContext context =
(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.
GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(Guid.Empty);
var log = new Log
{
Message = ex.Message
};
service.Create(log);
throw;
}
}
从本质上说,不是。您无法防止异常回滚事务。请参阅上的类似问题 一种常见的方法是创建一个单独的日志服务,该服务可以在数据库事务之外存储日志
B.t.w.Dynamics CRM 2015春季版引入了存储日志的功能,无论您的插件是否参与数据库事务。我找到了解决此问题的另一种方法。我们可以创建新服务,在失败的事务之外创建新事务。如果要执行相同操作,请参见以下代码段:
try
{
...
}
catch (Exception ex)
{
var HttpCurrentContext = HttpContext.Current;
var UrlBase = HttpCurrentContext.Request.Url.Host;
string httpUrl = @"http://";
if (HttpCurrentContext.Request.IsLocal)
{
UrlBase += ":" + HttpCurrentContext.Request.Url.Port;
}
if (!UrlBase.Contains(httpUrl))
{
UrlBase = httpUrl + UrlBase;
}
var UriBase = UriBuilder(UrlBase.ToLowerInvariant().Trim() + "/xrmservices/2011/organization.svc").Uri;
IServiceConfiguration<IOrganizationService> orgConfigInfo =
ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(UriBase);
var creds = new ClientCredentials();
using (_serviceProxy = new OrganizationServiceProxy(orgConfigInfo, creds))
{
// This statement is required to enable early-bound type support.
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_service = (IOrganizationService)_serviceProxy;
var log = new Log
{
Message = ex.Message
};
_service.Create(NewLog);
}
throw;
}
试试看
{
...
}
捕获(例外情况除外)
{
var HttpCurrentContext=HttpContext.Current;
var UrlBase=HttpCurrentContext.Request.Url.Host;
字符串httpUrl=@“http://”;
if(HttpCurrentContext.Request.IsLocal)
{
UrlBase+=“:”+HttpCurrentContext.Request.Url.Port;
}
如果(!UrlBase.Contains(httpUrl))
{
UrlBase=httpUrl+UrlBase;
}
var UriBase=UriBuilder(UrlBase.ToLowerInvariant().Trim()+“/xrmservices/2011/organization.svc”).Uri;
IServiceConfiguration组织配置信息=
ServiceConfigurationFactory.CreateConfiguration(UriBase);
var creds=new ClientCredentials();
使用(_serviceProxy=new OrganizationServiceProxy(orgConfigInfo,creds))
{
//此语句是启用早期绑定类型支持所必需的。
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(新的ProxyTypesBehavior());
_服务=(i组织服务)\ u服务代理;
var log=新日志
{
消息=例如消息
};
_创建(NewLog);
}
投掷;
}
谢谢你明确地给了我解决这个问题的想法。