web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

GUID fetching im Ms crm Plugin (MS crm 2011)

(0) ShareShare
ReportReport
Posted on by 547

I have a Entity "Test" and I have created a plugin as create and pre operation.

Now I have one more entity "counter" I need the GUID of this entity in my "Test" plugin.

I could get the direct GUID for exmaple "abc-4589-sdhfj-fhh" something like this but this is static what I actually need is a dynamic one just by using the name of entity "counter"

Below is one of few way I tried but could not got it. Giving me the Generic key error that means it is uable to get the abaxis_prefixcounter name. Any help would be appreciated!!!!

Guid counter = ((EntityReference)entity["abaxis_prefixcounter"]).Id

Thanks,

Ankush

*This post is locked for comments

I have the same question (0)
  • Royal King Profile Picture
    27,686 on at

    Can you post full code of your plugin also do you have single record in counter entity or multiple?  Ii you have multiple entity then you need to have unique field value in the record to retrieve specific record from counter entity.

  • chikhaleankush Profile Picture
    547 on at

    // TODO: Implement your custom Plug-in business logic.

               IPluginExecutionContext context = localContext.PluginExecutionContext;

               IOrganizationService service = localContext.OrganizationService;

               if (context.InputParameters.Contains("Target") &&

              context.InputParameters["Target"] is Entity)

               {

                   // Obtain the target entity from the input parmameters.

                   Entity entity = (Entity)context.InputParameters["Target"];

                   if (entity.LogicalName == "new_testingcrm1")

                   {

                       try

                       {

                           String x = entity.FormattedValues["abc_spieces"].ToString();

                          // Guid counter = new Guid("c864af69-6e7d-e511-bc3b-005056830006");

                          Guid   counter = ((EntityReference)entity["abc_prefixcounter"]).Id;

                            // Entity entity1 = (Entity)context.OutputParameters["abc_prefixcounter"];

                             //Guid counter = ((EntityRefrence)entity1["abc_prefixcounter"]).Id;

                           Entity member = service.Retrieve("abc_prefixcounter",counter,new Microsoft.Xrm.Sdk.Query.ColumnSet(true));

                           var prefix1 = member.Attributes["abc_prefix1"];

                           var prefix2 = member.Attributes["abc_prefix2"];

                           var medcounter = member.Attributes["abc_medcounter"];

                           var vetcounter = member.Attributes["abc_vetcounter"];

                           string medcounter1 = medcounter.ToString();

                           string vetcounter1 = vetcounter.ToString();

                           string med1 = prefix1.ToString();

                           string vet1 = prefix2.ToString();

                           decimal medcounter2 = Convert.ToDecimal(medcounter1);

                           decimal vetcounter2 = Convert.ToDecimal(vetcounter1);

                           //entity.Attributes["new_medid"] = counter;

                           if (x.Contains("MED"))

                           {

                               entity.Attributes["new_medid"] = med1 + medcounter1;

                               member.Attributes["abc_medcounter"] = medcounter2 + 1;

                           }

                           else

                           {

                               entity.Attributes["new_medid"] = vet1 + vetcounter1;

                               member.Attributes["abc_vetcounter"] = vetcounter2 + 1;

                           }

                           service.Update(member);

    ---------------------------------------------------------

    if you see this line below

    // Guid counter = new Guid("c864af69-6e7d-e511-bc3b-005056830006");

    if I use this it works fine for me but this will be static. I need it dynamic.

  • Royal King Profile Picture
    27,686 on at

    You can access only fields that are part of primary entity in the plugin context Target parameter.In order to access other entity record you have to query system to fetch.Here is sample code to show how to retrieve another record in the plugin. Replace entityname as well change the condition based on your requirement.

    var query = new QueryExpression { EntityName = "enittyNmae", ColumnSet = new ColumnSet() };

               query.Criteria.AddCondition(TransactionEntity.DOC_ID, ConditionOperator.Equal, refdoc_id);

               var response =service.RetrieveMultiple(query);

               if (response != null && response.Entities.Count>0)

               {

                   return response.Entities[0].ToEntityReference().Id;

               }

  • chikhaleankush Profile Picture
    547 on at

    Thank you very much @chitrasan Duraisamy.

    I tried to work on your code and here is my version of code.

    -----------------------------------------------------

    var query = new QueryExpression { EntityName = "abaxis_prefixcounter", ColumnSet = new ColumnSet() }

    var response = service.RetrieveMultiple(query);

    string xx = response.ToString();

    string yy = query.ToString();

    var zz = response.Entities[0].ToEntityReference().Id;

    entity.Attributes["new_medid"] = xx;

    entity.Attributes["new_medid"] = yy;

    entity.Attributes["new_medid"] = zz;

    when I tried to get zz value nothing comes up and

    Just for checking what is being catch by query and response variable I converted in string and tried to see what it gives and what I got is just

    "Microsoft.Xrm.Sdk.Query.QueryExpression"

    "Microsoft.Xrm.Sdk.EntityCollection"

  • Community Member Profile Picture
    on at

    Your query will fetch all of your Counter records.

    This line gives you the Guid of the first record in the EntityCollection that your RetrieveMultiple operation returns:

    var zz = response.Entities[0].ToEntityReference().Id;

    If you want to fetch a single specific counter record by its Name, you can add criteria/condition to your QueryExpression, or use a QueryByAttribute instead of a QueryExpression.

  • chikhaleankush Profile Picture
    547 on at

    QueryByAttribute query = new QueryByAttribute { EntityName = "abaxis_prefixcounter", ColumnSet = new ColumnSet() };

                           EntityCollection result = service.RetrieveMultiple(query);

                           var zz = result.Entities[0].ToEntityReference().Id;

                           string xy = zz.ToString();

    entity.Attributes["new_medid"] = result;

    entity.Attributes["new_medid"] = zz;

    entity.Attributes["new_medid"] = xy;

    ------------------------------------------------

    Above is my code and I am getting the below error

    --------------------------------------------------

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: An error occurred in the plug-in.Detail:

    <OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance&quot; xmlns="schemas.microsoft.com/.../Contracts&quot;>

     <ErrorCode>-2147220891</ErrorCode>

     <ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic&quot;>

       <KeyValuePairOfstringanyType>

         <d2p1:key>CallStack</d2p1:key>

         <d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema&quot; i:type="d4p1:string">   at Microsoft.Crm.Application.Platform.ServiceCommands.PlatformCommand.XrmExecuteInternal()

      at Microsoft.Crm.Application.Platform.ServiceCommands.CreateCommand.Execute()

      at Microsoft.Crm.Application.Platform.EntityProxy.Create(Boolean performDuplicateCheck, Guid auditingTransactionId)

      at Microsoft.Crm.Application.Platform.EntityProxy.Create(Boolean performDuplicateCheck)

      at Microsoft.Crm.Application.Forms.AppForm.SaveEntity(EntityProxy entity, FormEventId eventType, String redirectPath, Boolean performDuplicateCheck)</d2p1:value>

       </KeyValuePairOfstringanyType>

       <KeyValuePairOfstringanyType>

         <d2p1:key>OperationStatus</d2p1:key>

         <d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema&quot; i:type="d4p1:string">0</d2p1:value>

       </KeyValuePairOfstringanyType>

     </ErrorDetails>

     <Message>An error occurred in the plug-in.</Message>

     <Timestamp>2015-11-03T11:58:52.015625Z</Timestamp>

     <InnerFault i:nil="true" />

     <TraceText>

    [CrmPackage20.Plugins1: CrmPackage20.Plugins1.PretestingCrm1Create]

    [363d7630-9a7c-e511-849f-005056830006: PretestingCrm1Create]

    Entered CrmPackage20.Plugins1.PretestingCrm1Create.Execute(), Correlation Id: bcd5e411-9954-40b7-aa1e-2415710574b7, Initiating User: b0cca85b-1168-e511-807d-005056830006

    CrmPackage20.Plugins1.PretestingCrm1Create is firing for Entity: new_testingcrm1, Message: Create, Correlation Id: bcd5e411-9954-40b7-aa1e-2415710574b7, Initiating User: b0cca85b-1168-e511-807d-005056830006

    Exiting CrmPackage20.Plugins1.PretestingCrm1Create.Execute(), Correlation Id: bcd5e411-9954-40b7-aa1e-2415710574b7, Initiating User: b0cca85b-1168-e511-807d-005056830006

    </TraceText>

    </OrganizationServiceFault>

    -----------------------------------------------------

    I could not figure out what is going wrong. Any help would be appreciated!!!

    Thanks,

    Ankush

  • Suggested answer
    Royal King Profile Picture
    27,686 on at

    Try with below code that should work. For lookup attribute you have to set Entity reference.

    QueryByAttribute query = new QueryByAttribute { EntityName = "abaxis_prefixcounter", ColumnSet = new ColumnSet("abaxis_prefixcounterid") };

                          EntityCollection result = service.RetrieveMultiple(query);

                          var zz = result.Entities[0].ToEntityReference();                    

                          entity.Attributes["new_medid"] = zz;

  • chikhaleankush Profile Picture
    547 on at

    QueryByAttribute query = new QueryByAttribute { EntityName = "abaxis_prefixcounter", ColumnSet = new ColumnSet("abaxis_medcounter") };

                           EntityCollection result = service.RetrieveMultiple(query);

                           var zz = result.Entities[0].ToEntityReference();

                           entity.Attributes["new_medid"] = zz;

                           /* foreach (Entity result1 in result.Entities)

                           {

                               entity.Attributes["new_callid"] = result1["abaxis_prefix1"];

                           }*/

                       }

                       catch (FaultException ex)

                       {

                           throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);

                       }

    -----------------------------------------------------

    above code still does not work gives me plugin error. I am not sure what is causing error.

    I have no lookup filed all the fields are normal text or decimal field.

  • Verified answer
    chikhaleankush Profile Picture
    547 on at

    Hello Guys I have found the solution to the problem. I have used query by expression. I dont know hwy Query by Attribute did not worked it might be my mistake somewhere but as pf now query By expression is doing my work and I am happy.

    here is my code

    -------------------------------------

    // TODO: Implement your custom Plug-in business logic.

               IPluginExecutionContext context = localContext.PluginExecutionContext;

               IOrganizationService service = localContext.OrganizationService;

               if (context.InputParameters.Contains("Target") &&

              context.InputParameters["Target"] is Entity)

               {

                   // Obtain the target entity from the input parmameters.

                   Entity entity = (Entity)context.InputParameters["Target"];

                   if (entity.LogicalName == "new_testingcrm")

                   {

                       try

                       {

                           String x = entity.FormattedValues["new_gender"].ToString();

                           QueryExpression qe = new QueryExpression("prefixcounter");

                           qe.ColumnSet = new ColumnSet();

                           EntityCollection SearchContactResult = service.RetrieveMultiple(qe);

                           //if (SearchContactResult.Entities.Count == 1)

                           // {

                           // entity.Attributes["new_medicid"] = SearchContactResult.Entities;

                           /* if (SearchContactResult.EntityName = "abaxis_prefixcounter")

                            {

                                entity.Attributes["new_medicid"] = 1234;

                            } */

                           //entity.Attributes["new_medicid"] = SearchContactResult.TotalRecordCount;

                           Guid counter = new Guid();

                           foreach (var result in SearchContactResult.Entities)

                           {

                               counter = result.Id;

                               //entity.Attributes["new_callid"] = result.Id.ToString();

                               // RecordId = result.GetAttributeValue<Guid>("abaxis_prefix1");

                           }

                            Entity member = service.Retrieve("abaxis_prefixcounter", counter, new Microsoft.Xrm.Sdk.Query.ColumnSet(true));

                            var prefix1 = member.Attributes["abaxis_prefix1"].ToString();

                            var prefix2 = member.Attributes["abaxis_prefix2"].ToString();

                            var medcounter = member.Attributes["abaxis_medcounter"].ToString();

                            var vetcounter = member.Attributes["abaxis_vetcounter"].ToString();

                            decimal medcounter2 = Convert.ToDecimal(medcounter);

                            decimal vetcounter2 = Convert.ToDecimal(vetcounter);

                            decimal xx = Math.Truncate((medcounter2));

                            string xy = xx.ToString();

                            decimal yy = Math.Truncate((vetcounter2));

                            string yx = yy.ToString();

                            if (x.Contains("MED"))

                            {

                                entity.Attributes["new_callid"] = prefix1 + xy;

                                member.Attributes["abaxis_medcounter"] = medcounter2 + 1;

                            }

                            else

                            {

                                entity.Attributes["new_callid"] = prefix2 + yx;

                                member.Attributes["abaxis_vetcounter"] = vetcounter2 + 1;

                            }

                            service.Update(member);

                        }

                       catch (FaultException ex)

                       {

                           throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);

                       }

    -----------------------------------------------------------------------

    Thank you guys for the help!!!!

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans