|
|
|
|
#1 |
|
Участник
|
Цитата:
X++: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
namespace Bum.Survey.CRM.Plugin.BaseLib
{
public static class MessageName
{
public const string Create = "Create";
public const string Update = "Update";
public const string Delete = "Delete";
public const string RetrieveMultiple = "RetrieveMultiple";
public const string Retrieve = "Retrieve";
}
public static class ParameterName
{
public const string Target = "Target";
public const string id = "id";
public const string Query = "Query";
public const string BusinessEntityCollection = "BusinessEntityCollection";
public const string BusinessEntity = "BusinessEntity";
}
public class bf_PluginError : Exception
{
public bf_PluginError(string message)
: base(message)
{
}
}
public abstract class bf_PluginProcess
{
IServiceProvider _serviceProvider;
public IServiceProvider serviceProvider
{
get { return _serviceProvider; }
}
IPluginExecutionContext _executionContext;
public IPluginExecutionContext executionContext
{
get
{
if (_executionContext == null)
_executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
return _executionContext;
}
}
IOrganizationServiceFactory _serviceFactory;
public IOrganizationServiceFactory serviceFactory
{
get
{
if (_serviceFactory == null)
_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
return _serviceFactory;
}
}
IOrganizationService _crmService;
public IOrganizationService crmService
{
get
{
if (_crmService == null)
_crmService = serviceFactory.CreateOrganizationService(executionContext.UserId);
return _crmService;
}
}
ITracingService _tracingService;
public ITracingService tracingService
{
get
{
if (_tracingService == null)
_tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
return _tracingService;
}
}
public bf_PluginProcess(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
Entity _entity;
public Entity TargetEntity
{
get
{
return _entity;
}
}
EntityReference _entity_key;
public EntityReference TargetKey
{
get { return _entity_key; }
}
public void LoadEntity()
{
if (executionContext.InputParameters.Contains(ParameterName.Target))
{
if (executionContext.InputParameters[ParameterName.Target] is Entity)
{
_entity = (Entity)executionContext.InputParameters[ParameterName.Target];
_entity_key = new EntityReference(_entity.LogicalName, _entity.Id);
}
else if (executionContext.InputParameters[ParameterName.Target] is EntityReference)
{
_entity_key = (EntityReference)executionContext.InputParameters[ParameterName.Target];
}
}
if (executionContext.MessageName == MessageName.Create)
{
if (executionContext.OutputParameters.Contains(ParameterName.id))
_entity_key.Id = (Guid)executionContext.OutputParameters[ParameterName.id];
}
}
public void RequeryTarget()
{
RequeryTarget(new ColumnSet(true));
}
public void RequeryTarget(ColumnSet columnSet)
{
_entity = crmService.Retrieve(TargetKey.LogicalName, TargetKey.Id, columnSet);
}
public bool ValidateEntityName(string logicalName)
{
return _entity_key.LogicalName == logicalName;
}
public bool ValidateMessage(params string[] messages)
{
return messages.Contains(executionContext.MessageName);
}
abstract public void Execute();
public void Run()
{
try
{
Execute();
}
catch (System.Exception ex)
{
throw new InvalidPluginExecutionException(
String.Format("An error occurred in the {0} plug-in: {1}", this.GetType().ToString(), ex.ToString()), ex);
}
}
public Dictionary<int, string> GetOptionSet(string entityName, string optionSetName)
{
RetrieveAttributeRequest req = new RetrieveAttributeRequest();
req.EntityLogicalName = entityName;
req.LogicalName = optionSetName;
RetrieveAttributeResponse res = (RetrieveAttributeResponse)_crmService.Execute(req);
Dictionary<int, string> result = new Dictionary<int, string>();
foreach (var r in ((PicklistAttributeMetadata)res.AttributeMetadata).OptionSet.Options)
{
result.Add(r.Value.Value, r.Label.UserLocalizedLabel.Label);
}
return result;
}
}
public static class DateTimeExt
{
public static string ConvertToCulturalString(this DateTime dt)
{
return dt.ToLocalTime().ToString("dd.MM.yyyy");
}
}
} |
|
|
|
|
#2 |
|
Чайный пьяница
|
Мда. Зачем таким образом плагины писать - мне умом не понять (хотя я в CRM пришёл из мира ООП и немного в этом понимаю), но то ваше дело.
Суть в чём - как я и писал у вас не заполняется _entity. И соответственно проперти TargetEntity отдаёт null. Отсюда и ошибка. А вообще - учитесь дебажить плагины через VS.
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством. Подписывайтесь на мой блог, twitter и YouTube канал. Пользуйтесь моим Ultimate Workflow Toolkit |
|
|
|
| За это сообщение автора поблагодарили: Lavdislav (1). | |
|
|
#3 |
|
Участник
|
Цитата:
Сообщение от a33ik
Мда. Зачем таким образом плагины писать - мне умом не понять (хотя я в CRM пришёл из мира ООП и немного в этом понимаю), но то ваше дело.
Суть в чём - как я и писал у вас не заполняется _entity. И соответственно проперти TargetEntity отдаёт null. Отсюда и ошибка. А вообще - учитесь дебажить плагины через VS. |
|
|
|
|
#4 |
|
Участник
|
Цитата:
Сообщение от a33ik
Мда. Зачем таким образом плагины писать - мне умом не понять (хотя я в CRM пришёл из мира ООП и немного в этом понимаю), но то ваше дело.
Суть в чём - как я и писал у вас не заполняется _entity. И соответственно проперти TargetEntity отдаёт null. Отсюда и ошибка. А вообще - учитесь дебажить плагины через VS. X++: if (executionContext.MessageName == MessageName.Delete) { if (executionContext.PreEntityImages.Contains("Target") && executionContext.PreEntityImages["Target"] is Entity) { Entity preMessageImage = (Entity)executionContext.PreEntityImages["Target"]; QueryExpression surveyz = new QueryExpression() { EntityName = "bf_survey", ColumnSet = new ColumnSet(true) }; surveyz.Criteria.AddCondition("bf_surveyid", ConditionOperator.Equal, preMessageImage.GetAttributeValue<EntityReference>("bf_surveytoken_survey").Id); List<Entity> surveylists = crmService.RetrieveMultiple(surveyz).Entities.ToList(); foreach (var surveylist in surveylists) { QueryExpression token = new QueryExpression() { EntityName = "bf_surveytoken", ColumnSet = new ColumnSet(true) }; token.Criteria.AddCondition("bf_surveytoken_survey", ConditionOperator.Equal, surveylist.Id); List<Entity> surveyTokens = crmService.RetrieveMultiple(token).Entities.ToList(); surveylist["bf_survey_tkcnt"] = surveyTokens.Count - 1; crmService.Update(surveylist); } } } |
|
|
|
|
#5 |
|
Чайный пьяница
|
Повторюсь. Учитесь отлаживать плагины.
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством. Подписывайтесь на мой блог, twitter и YouTube канал. Пользуйтесь моим Ultimate Workflow Toolkit |
|
|
|
|
#6 |
|
Участник
|
|
|
|
|
|
|