Quantcast
Channel: Microsoft Dynamics CRM Forum - Recent Threads
Viewing all articles
Browse latest Browse all 82002

plugin update not firing in preimage

$
0
0
HI Friends,
 
I am working on one plugin, it is calling external rest service,I am calling address and borough fields.
Restful service will send response I need to update response in custom entity called intake.
I need to pass address and borough in the intake form.
1.i create plugin in the context of pre create and pre update and I am using preimages.
First time when I create form plug in working fine. But if use user update form its not firing request to service again and form values not updating.In Preimage update I am using two attributes and pre update 2 attributes but its failing on update the form.
I am pasting the code here please help me issue with code I am using crm online 2015
 
Thanks for help

 
namespace CRMPluginClientcallTest
{
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using System.Linq;
    using System.Runtime.Serialization.Json;
    using System.Net;
    using System.IO;
    using System.Text; ///<summary>
                       /// AutoNumber  Plugin.
                       ///</summary>        
    publicclassClientcall : PluginBase
    {
        ///<summary>
        /// Initializes a new instance of the <see cref="Clientcall"/> class.
        ///</summary>
        ///
        private
        conststring baseUrl = "api.cityofnewyork.us/.../address.json{0}&street={1}&borough={2}&app_id=77&app_key=hhhhh";
        public Clientcall() : base(typeof(Clientcall))
        {
            //PRE-OPERATION
            base.RegisteredEvents.Add(newTuple<int, string, string, Action<LocalPluginContext>>(20, "Create", "intake", newAction<LocalPluginContext>(Execute)));
       base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Update", "intake", new Action<LocalPluginContext>(Execute)));
            //PRE-OPERATION
            //base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Create", "appointment", new Action<LocalPluginContext>(ExecutePreAppointmentCreate)));
            // Note : you can register for more events here if this plugin is not specific to an individual entity and message combination.
            // You may also need to update your RegisterFile.crmregister plug-in registration file to reflect any change.
        }
        ///<summary>
        /// Executes the plug-in.
        ///</summary>
        ///<param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        ///<see cref="IPluginExecutionContext"/>,
        ///<see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        ///</param>
        ///<remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        ///</remarks>
        protectedvoid Execute(LocalPluginContext localContext)
        {
            try
            {
                if (localContext == null)
                {
                    thrownewArgumentNullException("localContext");
                }
                // Get a reference to the Organization service.
                IOrganizationService service = localContext.OrganizationService;
                IPluginExecutionContext context = localContext.PluginExecutionContext;
                Entity entity = null;
                Entity PreEntityImage = null;
                //if (context.Depth > 1)
                //{
                //    return;
                //}
                // The InputParameters collection contains all the data passed in the message request.
                if (context.InputParameters.Contains("Target") && (context.InputParameters["Target"] isEntity))
                {
                    entity = context.InputParameters["Target"] asEntity;
                    if (context.PreEntityImages.Contains("PreImage"))
                    {
                        PreEntityImage = (Entity)context.PreEntityImages["PreImage"];
 
                        if (context.MessageName != "Create"&& context.MessageName != "Update") { return; }
                        if (context.MessageName != "intake") { return; }
                    }
            
                }
                else
                {
                    return;
                }
                QueryExpression query = newQueryExpression("intake")
                {
                    ColumnSet = newColumnSet(true)
                    //  Criteria = new FilterExpression()
                };
                // query.Criteria.AddCondition("name", ConditionOperator.Equal, entity.LogicalName);
                EntityCollection results = service.RetrieveMultiple(query);
                if (results.Entities.Any()) // no error checkig to see if there are 2 incrementors set for the same entity
                {
                    foreach (Entity e in results.Entities)
                    {
 
                        string newborough = entity.FormattedValues["newborough"].ToString();
                        string streetaddress = null;
                        if (entity.Attributes.ContainsKey("streetaddress"))
                        {
                            streetaddress = (string)entity["streetaddress"];
                        }
                        string street, houseNumber;
                        SplitHouseNumberAndStreet(streetaddress, out street, out houseNumber);
                        Address addr = newAddress();
                        // Customize URL according to geo location parameters
                        var url = string.Format(baseUrl, houseNumber, street, newborough);
                        // Syncronious Consumption
                        var syncClient = newWebClient();
                        var content = syncClient.DownloadString(url);
                        // Create the Json serializer and parse the response
                        DataContractJsonSerializer serializer = newDataContractJsonSerializer(typeof(Geoclientapicall));
                        using (var ms = newMemoryStream(Encoding.Unicode.GetBytes(content)))
                        {
                            // deserialize the JSON object using the GeoDataData type.
                            var GeoDataData = (Geoclientapicall)serializer.ReadObject(ms);
                            addr.geosupportReturnCode = GeoDataData.address.geosupportReturnCode;
                            addr.geosupportReturnCode2 = GeoDataData.address.geosupportReturnCode2;
                            addr.houseNumber = GeoDataData.address.houseNumber;
                            addr.houseNumberIn = GeoDataData.address.houseNumberIn;
 
                            if (addr.geosupportReturnCode == "EE" )
                            {
                                entity["hiddenfiled"] = GeoDataData.address.houseNumber;
                            }
                            else {
                                entity["hiddenfiled"] = GeoDataData.address.houseNumberIn;
                            }
                            addr.boroughCode1In = GeoDataData.address.boroughCode1In;
                            addr.crossStreetNamesFlagIn = GeoDataData.address.crossStreetNamesFlagIn;
                            addr.firstBoroughName = GeoDataData.address.firstBoroughName;
                            addr.firstStreetNameNormalized = GeoDataData.address.firstStreetNameNormalized;
                            addr.geosupportFunctionCode = GeoDataData.address.geosupportFunctionCode;
                            addr.geosupportReturnCode = GeoDataData.address.geosupportReturnCode;
                            addr.geosupportReturnCode2 = GeoDataData.address.geosupportReturnCode2;
                            addr.houseNumber = GeoDataData.address.houseNumber;
                            addr.houseNumberIn = GeoDataData.address.houseNumberIn;
                            addr.houseNumberSortFormat = GeoDataData.address.houseNumberSortFormat;
                            //addr.message = GeoDataData.address.message;
                            //addr.message2 = GeoDataData.address.message2;
                            //addr.numberOfStreetCodesAndNamesInList = GeoDataData.address.numberOfStreetCodesAndNamesInList;
                            addr.boroughCode1In = GeoDataData.address.boroughCode1In;
                            addr.crossStreetNamesFlagIn = GeoDataData.address.crossStreetNamesFlagIn;
                            addr.firstBoroughName = GeoDataData.address.firstBoroughName;
                            addr.firstStreetNameNormalized = GeoDataData.address.firstStreetNameNormalized;
                            addr.geosupportFunctionCode = GeoDataData.address.geosupportFunctionCode;
                            addr.geosupportReturnCode = GeoDataData.address.geosupportReturnCode;
                            addr.workAreaFormatIndicatorIn = GeoDataData.address.workAreaFormatIndicatorIn;
                        }
                    }
                }
                else
                {
                    return;
                }
            }
            catch (FaultException<OrganizationServiceFault> faultException1)
            {
                FaultException<OrganizationServiceFault> faultException = faultException1;
                thrownewInvalidPluginExecutionException(string.Concat(faultException.Message, Environment.NewLine, faultException.StackTrace));
            }
            catch (Exception exp)
            {
                Exception exception = exp;
                thrownewInvalidPluginExecutionException(string.Concat(exception.Message, Environment.NewLine, exception.StackTrace));
            }
        }
        privatevoid SplitHouseNumberAndStreet(string streetaddress, outstring street, outstring houseNumber)
        {
            string str = null;
            street = null;
            houseNumber = null;
            str = streetaddress;
            var split = str.Split(new[] {' '}, 2);
            houseNumber = split[0];
            street = split[1];
        }
    }
}
 
namespace CRMPluginGeiclientCallTest
{
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Query;
    using System.Linq;
    using System.Runtime.Serialization.Json;
    using System.Net;
    using System.IO;
    using System.Text; ///<summary>
                       /// AutoNumber  Plugin.
                       ///</summary>        
    publicclassGeiClientCall : PluginBase
    {
        ///<summary>
        /// Initializes a new instance of the <see cref="GeiClientCall"/> class.
        ///</summary>
        ///
        private
        conststring baseUrl = "api.cityofnewyork.us/.../address.json{0}&street={1}&borough={2}&app_id=61583e27&app_key=c6e8acfbbc6487b24db697c4b0634d9a";
        public GeiClientCall() : base(typeof(GeiClientCall))
        {
            //PRE-OPERATION
            base.RegisteredEvents.Add(newTuple<int, string, string, Action<LocalPluginContext>>(20, "Create", "dycdcm_intake", newAction<LocalPluginContext>(Execute)));
        //    base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Update", "dycdcm_intake", new Action<LocalPluginContext>(Execute)));
            //PRE-OPERATION
            //base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Create", "appointment", new Action<LocalPluginContext>(ExecutePreAppointmentCreate)));
            // Note : you can register for more events here if this plugin is not specific to an individual entity and message combination.
            // You may also need to update your RegisterFile.crmregister plug-in registration file to reflect any change.
        }
        ///<summary>
        /// Executes the plug-in.
        ///</summary>
        ///<param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        ///<see cref="IPluginExecutionContext"/>,
        ///<see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        ///</param>
        ///<remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        ///</remarks>
        protectedvoid Execute(LocalPluginContext localContext)
        {
            try
            {
                if (localContext == null)
                {
                    thrownewArgumentNullException("localContext");
                }
                // Get a reference to the Organization service.
                IOrganizationService service = localContext.OrganizationService;
                IPluginExecutionContext context = localContext.PluginExecutionContext;
                Entity entity = null;
                Entity PreEntityImage = null;
                //if (context.Depth > 1)
                //{
                //    return;
                //}
                // The InputParameters collection contains all the data passed in the message request.
                if (context.InputParameters.Contains("Target") && (context.InputParameters["Target"] isEntity))
                {
                    entity = context.InputParameters["Target"] asEntity;
                    if (context.PreEntityImages.Contains("PreImage"))
                    {
                        PreEntityImage = (Entity)context.PreEntityImages["PreImage"];
 
                        if (context.MessageName != "Create"&& context.MessageName != "Update") { return; }
                        if (context.MessageName != "dycdcm_intake") { return; }
                    }
            
                }
                else
                {
                    return;
                }
                QueryExpression query = newQueryExpression("dycdcm_intake")
                {
                    ColumnSet = newColumnSet(true)
                    //  Criteria = new FilterExpression()
                };
                // query.Criteria.AddCondition("dycdcm_name", ConditionOperator.Equal, entity.LogicalName);
                EntityCollection results = service.RetrieveMultiple(query);
                if (results.Entities.Any()) // no error checkig to see if there are 2 incrementors set for the same entity
                {
                    foreach (Entity e in results.Entities)
                    {
 
                        string newborough = entity.FormattedValues["dycdcm_newborough"].ToString();
                        string streetaddress = null;
                        if (entity.Attributes.ContainsKey("dycdcm_streetaddress"))
                        {
                            streetaddress = (string)entity["dycdcm_streetaddress"];
                        }
                        string street, houseNumber;
                        SplitHouseNumberAndStreet(streetaddress, out street, out houseNumber);
                        Address addr = newAddress();
                        // Customize URL according to geo location parameters
                        var url = string.Format(baseUrl, houseNumber, street, newborough);
                        // Syncronious Consumption
                        var syncClient = newWebClient();
                        var content = syncClient.DownloadString(url);
                        // Create the Json serializer and parse the response
                        DataContractJsonSerializer serializer = newDataContractJsonSerializer(typeof(Geoclientapicall));
                        using (var ms = newMemoryStream(Encoding.Unicode.GetBytes(content)))
                        {
                            // deserialize the JSON object using the GeoDataData type.
                            var GeoDataData = (Geoclientapicall)serializer.ReadObject(ms);
                            addr.geosupportReturnCode = GeoDataData.address.geosupportReturnCode;
                            addr.geosupportReturnCode2 = GeoDataData.address.geosupportReturnCode2;
                            addr.houseNumber = GeoDataData.address.houseNumber;
                            addr.houseNumberIn = GeoDataData.address.houseNumberIn;
 
                            if (addr.geosupportReturnCode == "EE" )
                            {
                                entity["dycdcm_hiddenfiled"] = GeoDataData.address.houseNumber;
                            }
                            else {
                                entity["dycdcm_hiddenfiled"] = GeoDataData.address.houseNumberIn;
                            }
                            addr.boroughCode1In = GeoDataData.address.boroughCode1In;
                            addr.crossStreetNamesFlagIn = GeoDataData.address.crossStreetNamesFlagIn;
                            addr.firstBoroughName = GeoDataData.address.firstBoroughName;
                            addr.firstStreetNameNormalized = GeoDataData.address.firstStreetNameNormalized;
                            addr.geosupportFunctionCode = GeoDataData.address.geosupportFunctionCode;
                            addr.geosupportReturnCode = GeoDataData.address.geosupportReturnCode;
                            addr.geosupportReturnCode2 = GeoDataData.address.geosupportReturnCode2;
                            addr.houseNumber = GeoDataData.address.houseNumber;
                            addr.houseNumberIn = GeoDataData.address.houseNumberIn;
                            addr.houseNumberSortFormat = GeoDataData.address.houseNumberSortFormat;
                            //addr.message = GeoDataData.address.message;
                            //addr.message2 = GeoDataData.address.message2;
                            //addr.numberOfStreetCodesAndNamesInList = GeoDataData.address.numberOfStreetCodesAndNamesInList;
                            addr.boroughCode1In = GeoDataData.address.boroughCode1In;
                            addr.crossStreetNamesFlagIn = GeoDataData.address.crossStreetNamesFlagIn;
                            addr.firstBoroughName = GeoDataData.address.firstBoroughName;
                            addr.firstStreetNameNormalized = GeoDataData.address.firstStreetNameNormalized;
                            addr.geosupportFunctionCode = GeoDataData.address.geosupportFunctionCode;
                            addr.geosupportReturnCode = GeoDataData.address.geosupportReturnCode;
                            addr.workAreaFormatIndicatorIn = GeoDataData.address.workAreaFormatIndicatorIn;
                        }
                    }
                }
                else
                {
                    return;
                }
            }
            catch (FaultException<OrganizationServiceFault> faultException1)
            {
                FaultException<OrganizationServiceFault> faultException = faultException1;
                thrownewInvalidPluginExecutionException(string.Concat(faultException.Message, Environment.NewLine, faultException.StackTrace));
            }
            catch (Exception exp)
            {
                Exception exception = exp;
                thrownewInvalidPluginExecutionException(string.Concat(exception.Message, Environment.NewLine, exception.StackTrace));
            }
        }
        privatevoid SplitHouseNumberAndStreet(string streetaddress, outstring street, outstring houseNumber)
        {
            string str = null;
            street = null;
            houseNumber = null;
            str = streetaddress;
            var split = str.Split(new[] {' '}, 2);
            houseNumber = split[0];
            street = split[1];
        }
    }
}

Viewing all articles
Browse latest Browse all 82002

Latest Images

Trending Articles



Latest Images