Monday, August 22, 2011

Dynamics CRM 2011 : Execute Custom Business Logic in Plugin on Incomming Email Tracking


Sometime there is a requirement to execute custom code for performing custom validations, extract data or manipulate data on receiving incoming email in Microsoft Dynamics CRM 2011. The following step by step guide steps explains to develop and register a CRM SDK plugin to achieve this functionality.
[Instructions]

1. Use the plugin code below or download the plugin solution wod.Crm.IncommingEmail, make required changes and build plugin assembly file.
2. Use plugin registration tool to register the plugin assembly and then register a new plugin step for Email entity on Create event with Pre-Operation event pipeline stage in Synchronous execution mode

[Plugin: C# Code]


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk;

namespace wod.Crm.IncommingEmail
{
    public class wodPlugin : IPlugin
    {
        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));

            IOrganizationServiceFactory wod_serviceFactory = null;

            IOrganizationService wod_CrmService = null;

            try
            {
                wod_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(
                         typeof(IOrganizationServiceFactory));
                wod_CrmService = wod_serviceFactory.CreateOrganizationService(context.UserId);

                if (context.MessageName == "Create" &&
                    context.InputParameters.Contains("Target") &&
                    context.InputParameters["Target"] is Entity
                    )
                {
                    Entity wod_PluginEntity = (Entity)context.InputParameters["Target"];

                    //Checking if plugin is trigger for Email entity
                    if (wod_PluginEntity.LogicalName == "email")
                    {
                        // Checking if email direction is incomming
                        if (wod_PluginEntity.Contains("directioncode"))
                        {
                            // Checking if email is incomming
                            if (((Boolean)wod_PluginEntity["directioncode"]) == false)
                            {
                                EntityCollection wod_IncommingParty = null;

                                wod_IncommingParty = (EntityCollection)wod_PluginEntity["from"];

                                // Checking if plugin entity From field is activityparty entity object

                                if (wod_IncommingParty != null && wod_IncommingParty[0].LogicalName
                                 == "activityparty")
                                {
                                    EntityReference wod_PartyReference =
                                    (EntityReference)wod_IncommingParty[0]["partyid"];

                                    // Checking if email is sent by CRM Account
                                    if (wod_PartyReference.LogicalName == "account")
                                    {
                                        // Retrieve sender Account record
                                        Entity wod_Account = wod_CrmService.Retrieve("account",
                                        wod_PartyReference.Id, new ColumnSet(true));

                                        // You can write your code for validation, data manipulation here
                                        throw new Exception("email account: " + wod_Account["name"]);

                                    }
                                }
                            }
                        }
                    }
                }
            }

            catch (System.Web.Services.Protocols.SoapException ex)
            {
                throw new InvalidPluginExecutionException(ex.Detail.InnerText);
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
    }
}


15 comments:

  1. i am trying to update the regardingobjectid of the email in my post-processing synchronous plugin to point to an account entity. is it possible? i tryied following code, with no or partial success:

    1. no success (index out of range exception thrown). i have tried early and late bound code too.
    early bound:
    xrmContext.AddLink(
    account,
    new Relationship("Account_Emails"),
    email);
    xrmContext.SaveChanges();

    late bound:
    service.Associate(account.LogicalName, account.Id, new Relationship() { SchemaName = "Account_Emails" },
    new EntityReferenceCollection() { new EntityReference(email.LogicalName, email.Id) });
    service.Execute(request);


    2. partial success - The Regarding is created, but in the UI there is no text (only an Icon, the accountname is not shown)

    service.Associate(account.LogicalName, account.Id, new Relationship() { SchemaName = "Account_Emails" },
    new EntityReferenceCollection() { new EntityReference(email.LogicalName, email.Id) });
    service.Execute(request);


    any ideas? thank you.

    ReplyDelete
  2. number 2. should be without the execute method. i tryied the execute method with an AssociateRequest as follows

    AssociateRequest request = new AssociateRequest()
    {

    Target = new EntityReference(email.LogicalName, email.Id),
    RelatedEntities = new EntityReferenceCollection
    {
    new EntityReference(account.LogicalName, account.Id)
    },
    Relationship = new Relationship()
    {
    SchemaName = "Account_Emails"
    }
    };
    service.Execute(request);

    ReplyDelete
  3. How to test this plugin in CRM 2011

    ReplyDelete
  4. Hi Manoj,

    You can register the plugin as mentioned above and can test the plugin by Tracking an Email from Outlook into Dynamics CRM. Let me know if you face any issue during testing or require any suggestions for extending the plugin code or logic.

    ReplyDelete
  5. Can you help me on the matter that i need a piece of code to strip the domain name and associate it with a known Accounts email's domain name, for example if a company is abc@company.com and another email arrives with def@company.com i want the newly created contact(using workflow on that) to be associated with the company. is it possible?

    ReplyDelete
  6. Great post

    In this plugin we receive an information who is the sender. And when we know who is the sender, can we write this information in a customized lookup field to account entity and this field is located on email entity. I want to write the information on a lookup field to use it later in a workflow to create a case.

    ReplyDelete

  7. شركة الكمال أفضل شركة تنظيف بحائل للتنظيف أهمية كبرى فى حياة الفرد وبالأخص المواطن

    السعودى مما
    يؤدى ذالك إلى تعرض المنزل بشكل كبير إلى الأتربة والأوساخ والبقع والدهون وأن نظافة

    المنزل تشعر الفرد بالراحة
    النفسية الكبيرة وتتكفل شركة الكمال بهذا العمل لأنها أفضل


    شركة تنظيف بحائل

    ولانها الشركة الرائدة
    والمشهود لها بالفضلى فى هذا المجال من النظافة لوجود المقومات التى تساعد على ذالك منها

    العمالة المدربة وذوى الخبرة
    والكفاءة مع وجود أحدث معدات التنظيف للفلل التى تساعد على إنهاء العمل بكفاءة ونهتم كثيرا

    بأراء عملائنا فى


    شركة تنظيف فلل بحائل

    ويقوم طاقم العمل بتنظيف الشقه بدون التسبب بأى إزعاج للعميل فلا تتباطؤ فى إختيار شركة

    الكمال لتنظيف منزلكم لأنها أفضل


    شركة تنظيف شقق بحائل

    ولأن تنظيف المجالس يحتاج إلى وقت وجهد كبير فشركة الكمال أفضل شركة تنظيف
    مجالس بحائل كفيلة بتنظيف مجلسك فى أسرع وقت وبدون جهد وبالتالى شركة الكمال هى الحل

    الأمثل فى فى مجال تنظيف المجالس
    بحائل ونحن بانتظاركم لتتصلوا على


    شركة تنظيف مجالس بحائل

    وأفضل مايميز شركة الكمال أفضل شركة تنظيف منازل بحائل وضعها للخطط قبل البدء فى
    شركة تنظيف مجالس وكنب بحائل
    شركة تنظيف سجاد

    وموكيت بحائل

    العمل وتقسيم طاقمها إلى
    مجموعات كل منها مختص بتنظيف جزء معين وتمر عملية التنظيف على عدة مراحل :-
    1- البدء بتنظيف الموكيت والكنب والمفروشات والسجاد بالأعتماد على أحدث المعدات

    الألكترونية التى تعمل بالبخار لكى
    تقضى على المشاكل التقليدية للتنظيف وهى بهتان اللون وبذالك قمنا بالأعتماد على البخار فى

    إزالة الأوساخ والبقع
    2- ثم بعد ذالك يأتى دور البلاط والأرضيات فيقوم العمال بجلى البلاط والأرضيات بأحدث

    ألالآت جلى البلاط والأرضيات


    شركة تنظيف واجهات بحائل

    شركة الكمال أفضل شركة تنظيف خزانات بحائل نظرا لارتفاع درجات الحرارة فى حائل وفى
    غيرها من باقى مدن
    المملكة ووجود مياه البحر المحلاة التى تحمل الكثير من الرمال والأتربة مما يؤدى
    ذالك إلى تكون الفطريات والجراثيم على
    جدران الخزان ويؤدى ذالك إلى تلوث المياه والتى بدورها تؤدى إلى تسمم الفرد إذا فما الحل ؟
    الحل تقدمه لكم شركة الكمال وهى أفضل
    (( شركة كشف تسربات المياه بحائل )) نسعى فى شركة الكمال بتقديم كافة خدمات كشف

    تسربات المياه ويتم كشف تسربات المياه بأحدث
    الأجهزة الألكترونية و طاقم عمل يتكون من فنيين وخبراء منهم فنيين أجانب ونسعى جاهدين

    لتقديم أفضل خدمة بأقل سعر وإرضاء العميل واسعارنا حصرية لا تقبل المنافسة لدينا فى


    شركة كشف تسربات المياه بحائل

    شركة الكمال أفضل (( شركة نقل عفش بحائل )) نقل العفش من الأمور الهامة جدا (( شركة نقل

    عفش بحائل )) التى يلزم فبها الدقة والخبرة للحد ولذالك خصصنا قسما فى شركتنا لمجال
    نقل العفش مع تجهيزه :-
    1- أسطول كبير من السياراة المجهزة والتى (( شركة نقل عفش بحائل )) أعدن خصيصا

    لنقل العفش
    2- طافم العمل المدرب على حمل وتنزيل العفش والأثاث
    3- فنيين متخصصين فى الفك والتركيب (( شركة نقل عفش بحائل ))
    ومايجعل نقل الاثاث من أشهر الخدمات التى يكثر عليها الطلب هوا أن معظم العملاء يقومون

    بتغيير عفشهم القديم أكثر من مرة فى العام ويرجع ذالك أيضا إلى أنا
    العملاء يقومون بتأجير الفلل والقصور والشقق وذالك لأنهم يحبون تغير الجو ولذالك يكون اعتما

    نا فى شركة العربى على أحسن تقنيات نقل الاثاث بداخل وخارج
    حائل ونقل الاثاث من الأعمال شديدة الكثافة لذا تحتاج إلى


    شركة نقل اثاث بحائل

    دقة عالية ومهارة فى فك العفش وحمله وإنزاله إلى السياراة وتغليفه لتقليل من شدة الصدمات

    وعدم
    تعرضه للكسر وللخدش أيضا ونستخدم فى شركة العربى أفضل وأحدث السيارات المجهزة

    خصيصا لنقل العفش

    ReplyDelete
  8. van phong eva air tai tphcm là địa chỉ tin cậy để khách hàng đặt mua ve may bay di my gia re. Không chỉ có vậy, nếu bạn đang lên kế hoạch cho chuyến du lịch khám phá Đông Nam Á như Thái Lan hay Singapore hãy mua ve may bay di singapore gia reve may bay di thai lan gia re

    Một số điểm đến trong nước thu hút du khách trong hè này như Nha Trang, Phú Quốc, Đà Nẵng cũng đang đưa ra cá chương trình khuyến mại giá vé. Nhanh tay đặt mua ve may bay di nha trang gia re, ve may bay di phu quoc gia re
    Xứ sở Bạch Dương cũng là điểm đến vô cùng thú vị với ve may bay di nga gia re
    ve may bay di my
    > Xem thêm: ve may bay di phap

    ReplyDelete
  9. sahamalkhalij moving company

    With the launch of the best furniture moving company in Dammam, most service institutions are competing for this title, due to the continuous increase in the demand of the furniture moving company in Dammam, which all our customers are looking for in Dammam
    It is the cheapest company that offers experience and high quality in moving furniture in Khobar
    Many people are looking for a moving company in Qatif that has sufficient capacity to move their home furniture in the fastest time, with high efficiency and at reasonable prices.
    Furniture moving company in Dhahran We use the best and latest means in dismantling, installing and packing furniture, all with the presence of equipped, designed and specialized transport vehicles
    With pride, Siham Al Khaleej Company, we can tell you that we are the best furniture moving company that you can have dealing with in moving furniture.


    شركة نقل عفش بالدمام شركة نقل الأثاث بالخبر

    شركة نقل عفش بالقطيف شركة نقل أثاث بالظهران

    شركة نقل عفش شركة سهام الخليج لنقل الأثاث

    ReplyDelete