Запись обновления плагина Dynamics после созданияC#

Место общения программистов C#
Ответить
Anonymous
 Запись обновления плагина Dynamics после создания

Сообщение Anonymous »

Привет, я новичок в Dynamics и плагинах для динамики. Я создал простую сущность под названием «Библиотека», в которой хранятся книги.
После создания новой книги я хочу, чтобы цена книги увеличивалась на GST на 10 % на стороне сервера с помощью плагина.
Я знаю, что это обычно происходит на странице перед сохранением, и я пытаюсь понять, как работает логика на стороне сервера.
Я создал шаг postOperation (синхронный) для сообщения «Создать» для вызова Метод плагина Execute(). Судя по моему прочтению, это должно произойти ПОСЛЕ того, как запись будет сохранена в базе данных.
У меня также есть объект изображения публикации, к которому я обращаюсь.
В методе Execute я пытаюсь получить доступ к сохраненной записи через PostMessageEntity, чтобы обновить цену, но получаю исключение, сообщающее, что запись не существует на основе полученного мной идентификатора записи. Я могу подтвердить, что запись никогда не создавалась в системе, однако postOperation была вызвана.
Как мне получить доступ к только что сохраненной записи в плагине, чтобы обновить цену?
Мой код:
public void Execute(IServiceProvider serviceProvider)
{
// Obtain the execution context from the service provider.
Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)
serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));
// create a trace log so you can see where in the code it breaks
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
// create access to service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
tracingService.Trace("have reached execute event in plugin.");
// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
tracingService.Trace("We have a target and it is an entity.");
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];

if (entity.LogicalName == "new_books")
{
tracingService.Trace("the entity id of the record that was created is .." + entity.Attributes["new_booksid"].ToString());
// do we have a post update image of the new_books entity
if (context.PostEntityImages.Contains("newbookpostImage") && context.PostEntityImages["newbookpostImage"] is Entity)
{
tracingService.Trace("we have a postEntityImage.");
// // yep lets grab it.
Entity postMessageEntity = (Entity)context.PostEntityImages["newbookpostImage"];
// get book price as just saved to db
decimal bookPrice = ((Money)postMessageEntity.Attributes["new_price"]).Value;
// get id of the the record we have
Guid RecordID = ((Guid)postMessageEntity.Attributes["new_booksid"]);
tracingService.Trace("we have a post update bookprice.");
tracingService.Trace("the entity id of the post image entity is ..." + postMessageEntity.Attributes["new_booksid"].ToString());

Entity created_book = new Entity("new_books");

// use service to access a field of the current record as it is in the database and column we want to update.
created_book = service.Retrieve(created_book.LogicalName, RecordID, new ColumnSet(true));

//And the last line is where it dies and tells me new_books with id with d7bfc9e2 - 2257 - ec11 - 8f8f - 00224814e6e0 does not exist.
}
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/702 ... ter-create
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»