AXForum  
Вернуться   AXForum > Microsoft Dynamics CRM > Dynamics CRM: Blogs
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 19.04.2013, 00:11   #1  
Blog bot is offline
Blog bot
Участник
 
25,475 / 846 (79) +++++++
Регистрация: 28.10.2006
crminthefield: Code Review: Refactored Handling of Plug-in Pre-Image Attribute Values
Источник: http://blogs.msdn.com/b/crminthefiel...te-values.aspx
==============

During a recent Dynamics CRM 2011 code review engagement, I noticed a pattern being implemented repeatedly throughout the customer's plug-in library. This library was in desperate need of a refactor in the form of a method that encapsulated the repeated pattern. In my assessment report, I provided them a suggested method refactor which could eliminated hundreds of lines of redundant plug-in code. Keep reading and I'll provide you this same method to put in your coding arsenal.

The pattern I identified sought to incorporate the values from pre-event entity image snapshots when evaluating the primary entity's attribute values. We most often see this scenario for pre-event Update message plug-in code. The need for such a pattern is dictated by the nature of the Update message where the entity submitted only contains the attributes to be updated. Makes perfect sense…until you are executing within the event pipeline and need to evaluate a condition based on another attribute of the entity that may or may not have been submitted with the update.

Enter pre (and post) event image registrations. Event images provide a snapshot of the primary entity prior to (or after) the requested operation. This capability allows you to have broader context about the entity state without having to incur unnecessary retrieval of the primary entity from within your plug-in operation. Nevertheless, having this additional context means that you have two potential sources for the value of an entity attribute. Handling this unique situation requires additional logic to determine the appropriate value. The logic goes something like this:
  1. Attempt to get the attribute value from the primary entity
  2. If the primary entity contains the attribute, use its value
  3. Otherwise, if the primary entity doesn't contain the attribute, attempt to get the attribute from the pre-event image entity
  4. If the pre-event image entity contains the attribute, use its value
  5. Otherwise, use some default value (or null)
First, let's take a look at how this logic is often implemented in code.

Common Scenario
int value = -1; //default value

if (entity.Contains("attributename"))
{
value = entity.GetAttributeValue("attributename");
}
elseif (preImage.Contains("attributename"))
{
value = preImage.GetAttributeValue("attributename");
}


Next, we'll take the logic implemented above and encapsulate it in a method. I chose an extension method in this case to provide fluent companion to the standard Entity.GetAttributeValue(string attributeLogicalName) method.

Extension Method
publicstaticclassEntityExtensions
{
///
/// Extension method to get an attribute value from the entity
/// or its image snapshot
///
///The attribute type
///The primary entity
///Logical name of the attribute
///Image (pre/post) of the primary entity
///The attribute value of type T
///If neither entity contains the attribute, returns default(T)
public static T GetAttributeValue(thisEntity entity,
string attributeLogicalName,
Entity image)
{
return entity.GetAttributeValue(attributeLogicalName, image, default(T));
}

///
///Extension method to get an attribute value from the entity or image
///
///The attribute type
///The primary entity
///Logical name of the attribute
///Image (pre/post) of the primary entity
///The default value to use
///The attribute value of type T
public static T GetAttributeValue(thisEntity entity,
string attributeLogicalName,
Entity image,
T defaultValue)
{
return entity.Contains(attributeLogicalName)
? entity.GetAttributeValue(attributeLogicalName)
: image != null && image.Contains(attributeLogicalName)
? image.GetAttributeValue(attributeLogicalName)
: defaultValue;
}
}


How does incorporating our new extension method impact the original code? As shown below, each instance of executing this logic has been reduced to a single line of code. Implement this logic even a few times in a single plug-in and the reductions add up quickly.

Refactored Scenario
int value = entity.GetAttributeValue("attributename", preImage, -1);


Remember, if logic is worth repeating, it’s worth implementing once as a method!

Curious what’s involved in the PFE Dynamics Code Review service? It’s comprised of a thorough analysis of managed, .NET code from components that interact with Dynamics CRM and extend the core platform as well as client extensions such as JavaScript libraries. That analysis seeks to identify contraventions to known best-practices that present design, security, performance, or maintainability/supportability concerns. In addition, we commonly provide sample code to demonstrate a remediation approach to the most impactful issues.

Please let us know if the timing is right to explore a Code Review service engagement for your CRM solution or if you’re interested in becoming a Microsoft Premier Services customer.

Austin Jones

Microsoft Premier Field Engineer





Источник: http://blogs.msdn.com/b/crminthefiel...te-values.aspx
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
crminthefield: How to Create a Silverlight Web Resource that Interacts with CRM 2011 Forms Blog bot Dynamics CRM: Blogs 0 24.06.2011 04:17
crminthefield: Microsoft Dynamics CRM 2011 Custom Contact Entry Website using Early-Bound entity Classes. Blog bot Dynamics CRM: Blogs 0 04.06.2011 08:16
CRM DE LA CREME! Some more useful javascripts for MS CRM Blog bot Dynamics CRM: Blogs 0 04.05.2010 11:05
lcash: Using document handling to add image in Demo VM Blog bot DAX Blogs 0 21.07.2009 10:05
Вопрос про Demand Planner slava09 DAX: Функционал 4 25.09.2006 11:43

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 07:52.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.