Showing posts with label CRM Plugins. Show all posts
Showing posts with label CRM Plugins. Show all posts

Wednesday, 18 June 2014

Plugin registration tool Timeout Exception

When you registering the plugin using plugin registration tool the plugin doesn't get registered and you will get the exception below

Unhandled Exception: System.TimeoutException: The request channel timed out while waiting for a reply after 00:01:59.9139778.Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding.

The above error may be occur of slow internet connection or your early bind class may be an big size.

If your Early bound class is an big size you can reduce the size of early bound class by following the bellow steps:

  1. Create a new C# class library project in Visual Studio called SvcUtilFilter.
  2. In the project, add references to the following:

  • CrmSvcUtil.exe(from sdk)   This exe has the interface we will implement.

  • Microsoft.Xrm.Sdk.dll

  • System.Runtime.Serialization.

  • Add the following class to the project:

    using System;
    using System.Collections.Generic;
    using System.Xml.Linq;
    using Microsoft.Crm.Services.Utility;
    using Microsoft.Xrm.Sdk.Metadata;

    namespace SvcUtilFilter
    {
        /// <summary>
        /// CodeWriterFilter for CrmSvcUtil that reads list of entities from an xml file to
        /// determine whether or not the entity class should be generated.
        /// </summary>
        public class CodeWriterFilter : ICodeWriterFilterService
        {
            //list of entity names to generate classes for.
            private HashSet<string> _validEntities = new HashSet<string>();
           
            //reference to the default service.
            private ICodeWriterFilterService _defaultService = null;

            /// <summary>
            /// constructor
            /// </summary>
            /// <param name="defaultService">default implementation</param>
            public CodeWriterFilter( ICodeWriterFilterService defaultService )
            {
                this._defaultService = defaultService;
                LoadFilterData();
            }

            /// <summary>
            /// loads the entity filter data from the filter.xml file
            /// </summary>
            private void LoadFilterData()
            {
                XElement xml = XElement.Load("filter.xml");
                XElement entitiesElement = xml.Element("entities");
                foreach (XElement entityElement in entitiesElement.Elements("entity"))
                {
                    _validEntities.Add(entityElement.Value.ToLowerInvariant());
                }
            }

            /// <summary>
            /// /Use filter entity list to determine if the entity class should be generated.
            /// </summary>
            public bool GenerateEntity(EntityMetadata entityMetadata, IServiceProvider services)
            {
                return (_validEntities.Contains(entityMetadata.LogicalName.ToLowerInvariant()));
            }

            //All other methods just use default implementation:

            public bool GenerateAttribute(AttributeMetadata attributeMetadata, IServiceProvider services)
            {
                return _defaultService.GenerateAttribute(attributeMetadata, services);
            }

            public bool GenerateOption(OptionMetadata optionMetadata, IServiceProvider services)
            {
                return _defaultService.GenerateOption(optionMetadata, services);
            }

            public bool GenerateOptionSet(OptionSetMetadataBase optionSetMetadata, IServiceProvider services)
            {
                return _defaultService.GenerateOptionSet(optionSetMetadata, services);
            }

            public bool GenerateRelationship(RelationshipMetadataBase relationshipMetadata, EntityMetadata otherEntityMetadata, IServiceProviderservices)
            {
                return _defaultService.GenerateRelationship(relationshipMetadata, otherEntityMetadata, services);
            }

            public bool GenerateServiceContext(IServiceProvider services)
            {
                return _defaultService.GenerateServiceContext(services);
            }
        }
    }

    This class implements the ICodeWriterFilterService interface.  This interface is used by the class generation utility to determine which entities, attrributes, etc. should actually be generated.  The interface is very simple and just has seven methods that are passed metadata info and return a boolean indicating whether or not the metadata should be included in the generated code file.   

    For now I just want to be able to determine which entities are generated, so in the constructor I read from an XML file (filter.xml) that holds the list of entities to generate and put the list in a Hashset.  The format of the xml is this:

    <filter>
    <entities>
    <entity>team</entity>
        <entity>role</entity>
        <entity>businessunit</entity>
    <entity>systemuser</entity>
    <entity>lead</entity>
    <entity>contact</entity>
    <entity>email</entity>
    <entity>activitymimeattachment</entity>
    </entities>
    </filter>

    Take a look at the methods in the class. In the GenerateEntity method, we can simply check the EntityMetadata parameter against our list of valid entities and return true if it's an entity that we want to generate.

    For all of the other methods we want to just do whatever the default implementation of the utility is.  Notice how the constructor of the class accepts a defaultService parameter.  We can just save a reference to this default service and use it whenever we want to stick with the default behavior.  All of the other methods in the class just call the default service.

    To use our extension when running the utility, we just have to make sure the compiled DLL and the filter.xml file are in the same folder as CrmSvcUtil.exe, and set the /codewriterfilter command-line argument when running the utility (as described in the SDK):

    CrmSvcUtil.exe /url:https://<orgName>.api.crm.dynamics.com/XRMServices/2011/Organization.svc /out:Xrm.cs /username:kanagaraj@XXX.com /password:******* /namespace:Xrm /codewriterfilter:SvcUtilFilter.CodeWriterFilter,SvcUtilFilter

    That's it! You now have a generated sdk.cs file that is only a few hundred kilobytes instead of 5MB. 

    One final note:  There is actually a lot more you can do with extensions to the code generation utility.  For example: if you return true in the GenerateOptionSet method, it will actually generated Enums for each CRM picklist (which it doesn't normally do by default).

    Also, the source code for this SvcUtilFilter example can be found here.  Use at your own risk, no warranties, etc. etc. 


    Wednesday, 13 November 2013

    Plugin to Create record in the creation of email activity in CRM 2011 and 2013

    In my scenario i have to create new lead in creation of email. The email contain one Xml attachment named enquiry. That attachment have some standard tags. I have to read the xml tag and its values.Based on the values i have to create a new lead record. I did this scenario using the following code:

    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using Xrm;
    using System.Xml;
    using System.IO;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Metadata;

    namespace OPS.Lead.Create
    {  
        public class GenerateLead : IPlugin
        {
            XmlDocument doc = new XmlDocument();
            IOrganizationService service;
            public void Execute(IServiceProvider serviceProvider)
            {          
                ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                try
                {
                    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    service = serviceFactory.CreateOrganizationService(context.UserId);
                 
                    if (context.InputParameters.ContainsKey("Target") && context.InputParameters["Target"] is Entity)
                    {                  
                        Entity entity = context.InputParameters["Target"] as Entity;
                     
                        if (entity.LogicalName != "email")
                            return;
                        Email email = entity.ToEntity<Email>();                  
                        string to = string.Empty;

                        ColumnSet col = new ColumnSet("to", "from");
                        entity = service.Retrieve(entity.LogicalName, entity.Id, col);
                        Guid partyId = new Guid();
                        EntityCollection Recipients = entity.GetAttributeValue<EntityCollection>("to");
                        foreach (var party in Recipients.Entities)
                        {                      
                            partyId = party.GetAttributeValue<EntityReference>("partyid").Id;
                        }

                        ColumnSet column = new ColumnSet("internalemailaddress");
                        Entity toRecipent = service.Retrieve(SystemUser.EntityLogicalName, partyId, column);

                        SystemUser contact = toRecipent.ToEntity<SystemUser>();
                        to = contact.InternalEMailAddress;

                        if (!(to == "enquiry@xyz.com"))
                            return;

                        try
                        {
                            //Retrieve all attachments associated with the email activity.
                            QueryExpression _attachmentQuery = new QueryExpression
                            {
                                EntityName = ActivityMimeAttachment.EntityLogicalName,
                                ColumnSet = new ColumnSet("activitymimeattachmentid"),
                                Criteria = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    Conditions =
                            {
                                new ConditionExpression
                                {
                                    AttributeName = "objectid",
                                    Operator = ConditionOperator.Equal,
                                    Values = {entity.Id}
                                },
                                new ConditionExpression
                                {
                                    AttributeName = "objecttypecode",
                                    Operator = ConditionOperator.Equal,
                                    Values = {Email.EntityLogicalName}
                                }
                            }
                                }
                            };

                            EntityCollection results = service.RetrieveMultiple(_attachmentQuery);

                            if (results.Entities.Count == 0)
                                return;
                            string filename=string.Empty;
                            foreach (Entity ent in results.Entities)
                            {

                                ColumnSet colset = new ColumnSet();
                                colset.AllColumns = true;
                                ActivityMimeAttachment emailAttachment = (ActivityMimeAttachment)service.Retrieve("activitymimeattachment", ent.Id, colset);
                                filename= emailAttachment.FileName;
                                if (filename.Equals("enquiry"))
                                {
                                    byte[] fileContent = Convert.FromBase64String(emailAttachment.Body);
                                    using (MemoryStream ms = new MemoryStream(fileContent))
                                    {
                                        doc.Load(ms);
                                    }
                                }
                            }

                            if (filename.Equals("enquiry"))
                            {
                                Entity newLead = new Entity("lead");

                                newLead["subject"] = entity.GetAttributeValue<string>("subject");
                                newLead["firstname"] = GetTagValue("Firstname");
                                newLead["lastname"] = GetTagValue("LastName");
                                newLead["emailaddress1"] = GetTagValue("EmailAddress");
                                newLead["companyname"] = GetTagValue("Companyname");
                                newLead["jobtitle"] = GetTagValue("Title");
                                newLead["mobilephone"] = GetTagValue("MobileNo");
                                newLead["address1_country"] = GetTagValue("Country");

                                string numberOfUsers = GetTagValue("Crmusers");
                                OptionSetValue crmUsers = new OptionSetValue(getOptionSetValue("ln_crmusers", numberOfUsers));
                                newLead["ln_crmusers"] = crmUsers;

                                string source = GetTagValue("Channel");
                                OptionSetValue leadSource = new OptionSetValue(getOptionSetValue("leadsourcecode", source));
                                newLead["leadsourcecode"] = leadSource;

                                string NoOfProduct = GetTagValue("ProductImplemented");
                                OptionSetValue productImplemented = new OptionSetValue(getOptionSetValue("ln_productimplemented", NoOfProduct));
                                newLead["ln_productimplemented"] = productImplemented;

                                string durationToBuy = GetTagValue("BuyPeriod");
                                OptionSetValue buyPeriod = new OptionSetValue(getOptionSetValue("ln_buyplan", durationToBuy));
                                newLead["ln_buyplan"] = buyPeriod;

                                string wantDemo = GetTagValue("Demo");
                                bool demo = false;
                                if (wantDemo.Equals("true"))
                                    demo = true;
                                newLead["ln_demo"] = demo;

                                string broucher = GetTagValue("Brochure");
                                bool ln_broucher = false;
                                if (broucher.Equals("true"))
                                    ln_broucher = true;
                                newLead["ln_brochure"] = ln_broucher;

                                newLead["description"] = GetTagValue("Comments");
                                newLead["ownerid"] = new EntityReference(SystemUser.EntityLogicalName, context.UserId);

                                service.Create(newLead);
                            }
                            else
                                return;
                        }
                        catch (FaultException<OrganizationServiceFault> ex)
                        {
                            tracingService.Trace("1"+ex.Message);
                        }
                        catch (Exception e)
                        {
                            tracingService.Trace("2"+e.Message);
                        }
                    }
                }          
                catch (Exception exp)
                {
                    tracingService.Trace("3"+exp.Message);
                }
            }

            public string GetTagValue(string element)
            {          
                string values = "";
                foreach (XmlNode node in doc.GetElementsByTagName(element))
                    values = node.InnerText;
                return values;
            }

            public int getOptionSetValue(string attributeName, string optionsetText)
            {
                int optionSetValue = 0;
                RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest();
                retrieveAttributeRequest.EntityLogicalName = "lead";
                retrieveAttributeRequest.LogicalName = attributeName;
                retrieveAttributeRequest.RetrieveAsIfPublished = true;

                RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest);
                PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveAttributeResponse.AttributeMetadata;

                OptionSetMetadata optionsetMetadata = picklistAttributeMetadata.OptionSet;

                foreach (OptionMetadata optionMetadata in optionsetMetadata.Options)
                {
                    if (optionMetadata.Label.UserLocalizedLabel.Label.ToLower() == optionsetText.ToLower())
                    {
                        optionSetValue = optionMetadata.Value.Value;
                        return optionSetValue;
                    }

                }
                return optionSetValue;
            }
        }
    }