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)

Custom Workflow error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

(0) ShareShare
ReportReport
Posted on by 12,119 Moderator

Hi all 

I configure a custom work flow and I bind this work flow to my custom button. I have three admin Users A, T, U. When I use this button with the help A and T users my buttons works fine but when I use this button with the help of U user. It is prompting me error in the work flow. Error shown below:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Plugin Trace:

[Integration: Integration.CRMIntegration]
[Integration (1.0.0.0): Integration.CRMIntegration]

Error Message:

Unhandled Exception: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
at System.Collections.Generic.List`1.get_Item(Int32 index)
at Integration.CRMIntegration.Execute(CodeActivityContext context)
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)

There is no record issue I enter same records for all three users and all these users are system admin. Please help me in investigating the issue.

Thank You

*This post is locked for comments

I have the same question (0)
  • Bas van de Sande Profile Picture
    4,383 on at

    Hi Abdul,

    it looks like the error is caused in the Integration.CRMIntegration plugin. Do you happen to use a custom workflow activity? If yes, do you have the source code of it?

    Perhaps you can share some more with us, in order for us to help you

    Bas

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi Bas van de Sande

    This is my whole code which I use in my custom work flow:

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using System.Net;

    using System.IO;

    using Newtonsoft.Json;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Workflow;

    using System.Activities;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Xrm.Sdk.Messages;//RetrieveRequest naemspace

    namespace Integration

    {

       public class CRMIntegration : CodeActivity

       {

           protected override void Execute(CodeActivityContext context)

           {

               ITracingService tracingService = context.GetExtension<ITracingService>();

               IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();

               IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();

               IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

               Guid Id = workflowContext.PrimaryEntityId;

               // Create the request object and set the monikers with the

               //Create the request

               RetrieveRequest request = new RetrieveRequest();

               request.ColumnSet = new ColumnSet(new string[] { aw__Attributes.name, aw__Attributes.FromName, aw__Attributes.Subject, aw__Attributes.Fromemail });

               request.Target = new EntityReference(EntityName.aw_, Id);

               Entity entity = (Entity)((RetrieveResponse)service.Execute(request)).Entity;

               EntityCollection ec = null;

               var userid = workflowContext.UserId.ToString();

               ec = GetEntityCollection(service, EntityName.aw__User, aw__User_Attributes.User, userid, new ColumnSet(aw__User_Attributes.Address, aw__User_Attributes.BusinessUnitId, aw__User_Attributes.City, aw__User_Attributes.PostalCode, aw__User_Attributes.State, aw__User_Attributes.Country));

               if (entity.Contains(aw__Attributes.name) && entity.Contains(aw__Attributes.FromName) && entity.Contains(aw__Attributes.Subject) && entity.Contains(aw__Attributes.Fromemail) && ec.Entities[0].Contains(aw__User_Attributes.Address) && ec.Entities[0].Contains(aw__User_Attributes.BusinessUnitId) && ec.Entities[0].Contains(aw__User_Attributes.City) && ec.Entities[0].Contains(aw__User_Attributes.Country) && ec.Entities[0].Contains(aw__User_Attributes.PostalCode) && ec.Entities[0].Contains(aw__User_Attributes.State))

               {

                   //</Creating error log for list entity>

                   string ListName = string.Empty;

                   ListName = entity.Attributes[aw__Attributes.name].ToString();

                   //</Creating error log for list entity>

                   var sampleList = JsonConvert.SerializeObject(

                   new

                   {

                       name = ListName,

                       contact = new

                       {

                           company = ec.Entities[0].Attributes[aw__User_Attributes.BusinessUnitId],

                           address1 = ec.Entities[0].Attributes[aw__User_Attributes.Address],

                           city = ec.Entities[0].Attributes[aw__User_Attributes.City],

                           state = ec.Entities[0].Attributes[aw__User_Attributes.State],

                           zip = ec.Entities[0].Attributes[aw__User_Attributes.PostalCode],

                           country = ec.Entities[0].Attributes[aw__User_Attributes.Country],

                       },

                       permission_reminder = "You'\''re receiving this email because you signed up for updates about Freddie'\''s newest hats.",

                       campaign_defaults = new

                       {

                           from_name = entity.Attributes[aw__Attributes.FromName],

                           from_email = entity.Attributes[aw__Attributes.Fromemail],

                           subject = entity.Attributes[aw__Attributes.Subject],

                           language = "en",

                       },

                       email_type_option = true

                   });

                   var uri = string.Format("https://{0}.api..com/3.0/lists", "u4");

                   try

                   {

                       using (var webClient = new WebClient())

                       {

                           webClient.Headers.Add("Accept", "application/json");

                           webClient.Headers.Add("Authorization", "apikey " + "ab15c4d1");

                           string Response = string.Empty;

                           Response = webClient.UploadString(uri, "POST", sampleList);

                           string listId = string.Empty;

                           listId = Response.Substring(7, 10);

                           Entity updateEntity = new Entity(EntityName.aw_);

                           updateEntity.Id = Id;

                           updateEntity[aw__Attributes.CreateListStatus] = "Sent";

                           updateEntity[aw__Attributes.ListId] = listId;

                           service.Update(updateEntity);

                           //<Creating error log for list entity>

                           Entity Entity = new Entity(EntityName.ListError);

                           Entity[ListError_Attributes.ResponseDetail] = Response;

                           Entity[ListError_Attributes.Response] = "successful";

                           Entity[ListError_Attributes.IntegrationType] = "Create List";

                           Entity[ListError_Attributes.DateTime] = DateTime.Now;

                           Entity[ListError_Attributes.IntegrationDescription] = ListName;

                           Guid ListErrorID = service.Create(Entity);

                           //</Creating error log for list entity>

                           AssociateRequest ListToListError = new AssociateRequest

                           {

                               //The contact record

                               Target = new EntityReference(updateEntity.LogicalName, Id),

                               //The list of account you would like the contact to be linked with (in this case we have only one account)

                               RelatedEntities = new EntityReferenceCollection

                                   {

                                   new EntityReference(Entity.LogicalName, ListErrorID)

                                   },

                               Relationship = new Relationship("aw_listerror")

                           };

                           service.Execute(ListToListError);

                       }

                   }

                   catch (WebException we)

                   {

                       if (we.Response!=null)

                       {

                           using (var sr = new StreamReader(we.Response.GetResponseStream()))

                           {

                               Entity updateEntityA = new Entity(EntityName.aw_);

                               updateEntityA.Id = Id;

                               updateEntityA[aw__Attributes.CreateListStatus] = "Pending Sent";

                               service.Update(updateEntityA);

                               //<Creating error log for list entity>

                               Entity EntityB = new Entity(EntityName.ListError);

                               EntityB[ListError_Attributes.ResponseDetail] = sr.ReadToEnd();

                               EntityB[ListError_Attributes.Response] = "unsuccessful";

                               EntityB[ListError_Attributes.IntegrationType] = "Create List";

                               EntityB[ListError_Attributes.DateTime] = DateTime.Now;

                               EntityB[ListError_Attributes.IntegrationDescription] = ListName;

                               Guid ListErrorIDB = service.Create(EntityB);

                               AssociateRequest ListToListErrorr = new AssociateRequest

                               {

                                   //The contact record

                                   Target = new EntityReference(updateEntityA.LogicalName, Id),

                                   //The list of account you would like the contact to be linked with (in this case we have only one account)

                                   RelatedEntities = new EntityReferenceCollection

                                   {

                                       new EntityReference(EntityB.LogicalName, ListErrorIDB)

                                   },

                                   Relationship = new Relationship("aw_listerror")

                               };

                               service.Execute(ListToListErrorr);

                               //</Creating error log for list entity>

                           }

                       }

                       else

                       {

                           Entity updateEntity = new Entity(EntityName.aw_);

                           updateEntity.Id = Id;

                           updateEntity[aw__Attributes.CreateListStatus] = "Pending Sent";

                           service.Update(updateEntity);

                           //<Creating error log for list entity>

                           Entity Entity = new Entity(EntityName.ListError);

                           Entity[ListError_Attributes.ResponseDetail] = we.Response;

                           Entity[ListError_Attributes.Response] = "unsuccessful";

                           Entity[ListError_Attributes.IntegrationType] = "Create List";

                           Entity[ListError_Attributes.IntegrationDescription] = ListName;

                           Entity[ListError_Attributes.DateTime] = DateTime.Now;

                           Guid ListErrorID = service.Create(Entity);

                           AssociateRequest ListToListError = new AssociateRequest

                           {

                               //The contact record

                               Target = new EntityReference(updateEntity.LogicalName, Id),

                               //The list of account you would like the contact to be linked with (in this case we have only one account)

                               RelatedEntities = new EntityReferenceCollection

                                   {

                                       new EntityReference(Entity.LogicalName, ListErrorID)

                                   },

                               Relationship = new Relationship("aw_listerror")

                           };

                           service.Execute(ListToListError);

                           //</Creating error log for list entity>

                       }

                   }

               }

           }

           private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)

           {

               QueryExpression query = new QueryExpression

               {

                   EntityName = entityName,

                   ColumnSet = cols,

                   Criteria = new FilterExpression

                   {

                       Conditions =

                       {

                           new ConditionExpression

                           {

                               AttributeName = attributeName,

                               Operator = ConditionOperator.Equal,

                               Values = { attributeValue }

                           }

                       }

                   }

               };

               return service.RetrieveMultiple(query);

           }

       }

       public static class EntityName

       {

           public const string aw_ = "aw_";

           public const string aw__User = "aw_user";

           //<Creating error log for list entity>

           public const string ListError = "aw__listerror";

           //<Creating error log for list entity>

       }

       public static class aw__Attributes

       {

           public const string name = "aw_name";

           public const string Campaign = "aw_campaign";

           public const string FromName = "aw_fromname";

           public const string Subject = "aw_subject";

           public const string Fromemail = "aw_fromemail";

           public const string CreateListStatus = "aw_sent";

           public const string ListId = "aw_listid";

       }

       public static class aw__User_Attributes

       {

           public const string User = "aw__user";

           public const string Address = "aw__address";

           public const string City = "aw__city";

           public const string State = "aw__state";

           public const string PostalCode = "aw__postalcode";

           public const string BusinessUnitId = "aw__companyname";

           public const string Country = "aw__countrycode";

       }

       //<Creating error log for list entity>

       public static class ListError_Attributes

       {

           public const string ListID = "aw_listid";

           public const string Response = "aw_response";

           public const string IntegrationType = "aw_responsetype";

           public const string Status = "aw_status";

           public const string IntegrationDescription = "aw_description";

           public const string ResponseDetail = "aw_errordetail";

           public const string DateTime = "aw_datetime";

       }

       //<Creating error log for list entity>

    }

    Thank You

  • Verified answer
    Jonathon Nachman Profile Picture
    997 on at

    Hi Abdul

    This error could occur when you are trying a field such as an optionsset value or an array?

    I would use the tracingservice to work through the code and check on values while running. 

    http://www.nachman-consulting.com/mscrm-2011-useful-itracingservice-addiion-when-creating-plugin-assemblies/

  • Verified answer
    Aiden Kaskela Profile Picture
    19,696 on at

    Hi Abdul,

    The bad news is that you have an awful lot of code that could be causing the problem. The good news is that you have an easily replicatable error. Here's the quickest way you'll find it:

    - Comment out half your code and reregister your plugins

    - Log in as the user and click the button.

    If it works, something in the commented code is giving the error, so uncomment half of it and retry, repeat.

    If doesn't work, comment out more code and retry (I think you can see where this is going).

    Once you find the line that's causing the error, it'll be pretty easy to see what the root problem is. For example, if "ec.Entities[0].Contains(aw__User_Attributes.Address)" fails with an index OOB error, you probably don't have any items in the ec xollection.

    Hope this helps! I'd appreciate if you'd mark this as Answering your question.

    Thanks,

     Aiden

  • Verified answer
    PS Profile Picture
    23,577 on at
  • Community Member Profile Picture
    on at

    Hello,, i think your error is in line

     listId = Response.Substring(7, 10);


    Are you sure that response is that long?

    For reference:

    https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx

  • Suggested answer
    Nithya Gopinath Profile Picture
    17,078 on at

    Hi Abdul Wahab,

    MS CRM web.config file overrides setting of your web application, so you need to specifically change web.config file of MS CRM.

    See: mahenderpal.wordpress.com/.../index-was-out-of-range-must-be-non-negative-and-less-than-the-size-of-the-collection-ms-crm-4-0

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi Jonathan, Aiden, Prashant, Agust and Nithya

    My problem is When I use user U, I have this error, I use all the same privilege with U that I was give to A and T. When I use A and T my code is working fine. I think there is some user limitation problem or something else. Error is not in my code. If there is an error in my code so why A and T user are able to do the same operations that user U is not able to do?

    Thank You

  • Community Member Profile Picture
    on at

    Did you check the security role for all the user ? Is there an entity that user U unable to read/write ? Check the entity that you use on that Code, and make sure user U has permission like user A and T on those Entity.

  • Abdul Wahab Profile Picture
    12,119 Moderator on at

    Hi Fikri

    All three users are Sys Admins.

    Thank You

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