locked
CRM 2011 - QueryExpression - RetrieveMultiple - NullReferenceException RRS feed

  • Question

  • Hi,

    This is driving me crazy! With the following code I get a NullReferenceException when the method "RetrieveMultiple" is triggerd on the end of the code. I tried everything but  still getting this NullReferenceException!! Where goes it wrong?

     

                var connection =  CrmConnection.Parse("xx");
                var service = new OrganizationService(connection);
                var context = new CrmOrganizationServiceContext(connection);

     

                // Create a column set that holds the names of the columns to be retrieved.
                string[] columnset = { "x", "y" };

                // Create the ConditionExpression.
                ConditionExpression conditionAccount = new ConditionExpression();

                // Set the ConditionExpressions Properties
                conditionAccount.AttributeName = "name";
                conditionAccount.Operator = ConditionOperator.Equal;
                string [] condition = { "xx" };
                conditionAccount.Values.Add(condition);

                // Create the FilterExpression.
                FilterExpression filterAccount = new FilterExpression();

                // Set the properties of the FilterExpression.
                filterAccount.FilterOperator = LogicalOperator.And;
                filterAccount.Conditions.Add(conditionAccount);

                // Create the QueryExpression.
                QueryExpression queryAccount = new QueryExpression();

                // Set the properties of the QueryExpression.
                queryAccount.EntityName = "account";
                queryAccount.ColumnSet = new ColumnSet(columnset);
                queryAccount.Criteria = filterAccount;

                // Retrieve (NULLREFERENCEEXCEPTION)
                EntityCollection retrievedData = context.RetrieveMultiple(queryAccount);

    Thursday, August 4, 2011 12:22 PM

Answers

  • Hi,

    Change this line var service = new OrganizationService(connection);

    to

    var service = new IOrganizationService(connection);
    

    try also the old code it shoudl work also now.


    Jehanzeb Javeed

    http://worldofdynamics.blogspot.com
    Linked-In Profile |CodePlex Profile

    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".
    • Proposed as answer by Jim Glass Jr Thursday, August 4, 2011 3:32 PM
    • Marked as answer by m83 Friday, August 5, 2011 7:32 AM
    Thursday, August 4, 2011 3:04 PM
  • I found the problem. I had to change to following lines:

     

                string[] condition = { "bro" };
                conditionexpre.Values.Add(condition);

     

                ==> conditionexpre.Values.Add("bro");

     

    AND

               queryAccount.ColumnSet = new ColumnSet(columnset);

     

               ==> queryAccount.ColumnSet.AddColumn("name")


     

     

     

    • Marked as answer by m83 Friday, August 5, 2011 7:31 AM
    Friday, August 5, 2011 7:31 AM

All replies

  • Hi,

    Try update the following line EntityCollection retrievedData = context.RetrieveMultiple(queryAccount); with one below:

    EntityCollection retrievedData = service.RetrieveMultiple(queryAccount);
    


    Jehanzeb Javeed

    http://worldofdynamics.blogspot.com
    Linked-In Profile |CodePlex Profile

    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".
    • Proposed as answer by Jehanzeb.Javeed Thursday, August 4, 2011 1:16 PM
    • Marked as answer by m83 Thursday, August 4, 2011 2:23 PM
    • Unmarked as answer by m83 Thursday, August 4, 2011 2:25 PM
    Thursday, August 4, 2011 1:16 PM
  • Ok, thanks!

    But now I'm getting the following error:

     

    Collection was modified; enumeration operation may not execute.



    How can that be possible, I'm just retrieving the collection ...??
    Thursday, August 4, 2011 2:20 PM
  • Try createring RetrieveMultipleRequest and pass to Service.Execute method instead of calling RetrieveMultiple method i.e

     

    RetrieveMultipleRequest jj_Request = new RetrieveMultipleRequest();
    
    RetrieveMultipleResponse jj_response = null;
    
    // You code will come here
    
    jj_Request.Query = queryAccount;
    
    jj_response = (RetrieveMultipleResponse)service.Execute(jj_Request);
    
    EntityCollection jj_RtrnEntyColl = jj_response.EntityCollection;
    

     

     


    Jehanzeb Javeed

    http://worldofdynamics.blogspot.com
    Linked-In Profile |CodePlex Profile

    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".


    Thursday, August 4, 2011 2:41 PM
  • Then I'm getting back a NullReferenceException...
    Thursday, August 4, 2011 2:49 PM
  • Where are you getting the exception and post your full code here.
    Jehanzeb Javeed

    http://worldofdynamics.blogspot.com
    Linked-In Profile |CodePlex Profile

    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".
    Thursday, August 4, 2011 2:51 PM
  • I'm getting the exception on the second last line (the execute methode):

     

                var connection =  CrmConnection.Parse("xx");
                var service = new OrganizationService(connection);
                var context = new CrmOrganizationServiceContext(connection);




                RetrieveMultipleRequest jj_Request = new RetrieveMultipleRequest();

                RetrieveMultipleResponse jj_response = null;




                // You code will come here
                // Create a column set that holds the names of the columns to be retrieved.
                string[] columnset = { "name" };

                // Create the ConditionExpression.
                ConditionExpression conditionexpre = new ConditionExpression();

                // Set the ConditionExpressions Properties
                conditionexpre.AttributeName = "name";
                conditionexpre.Operator = ConditionOperator.Contains;
                string[] condition = { "bro" };
                conditionexpre.Values.Add(condition);

                // Create the FilterExpression.
                FilterExpression filterAccount = new FilterExpression();

                // Set the properties of the FilterExpression.
                filterAccount.Conditions.Add(conditionexpre);

                // Create the QueryExpression.
                QueryExpression queryAccount = new QueryExpression();

                // Set the properties of the QueryExpression.
                queryAccount.EntityName = "account";
                queryAccount.ColumnSet = new ColumnSet(columnset);
                queryAccount.Criteria = filterAccount;



                jj_Request.Query = queryAccount;

                jj_response = (RetrieveMultipleResponse)context.Execute(jj_Request);

                EntityCollection jj_RtrnEntyColl = jj_response.EntityCollection;

    Thursday, August 4, 2011 2:53 PM
  • Hi, change back to:

     jj_response = (RetrieveMultipleResponse)service.Execute(jj_Request);
    


    Jehanzeb Javeed

    http://worldofdynamics.blogspot.com
    Linked-In Profile |CodePlex Profile

    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".
    Thursday, August 4, 2011 2:57 PM
  • Yes I did but I'm also get the NullReferenceException..

    This is the stacktrace:


    Server stack trace:
       at Microsoft.Xrm.Sdk.AppDomainBasedKnownProxyTypesProvider.AddTypeMapping(Assembly assembly, Type type, String proxyName)
       at Microsoft.Xrm.Sdk.KnownProxyTypesProvider.LoadKnownTypes(Assembly assembly)
       at Microsoft.Xrm.Sdk.KnownProxyTypesProvider.RegisterAssembly(Assembly assembly)
       at Microsoft.Xrm.Sdk.KnownProxyTypesProvider.InitializeLoadedAssemblies()
       at Microsoft.Xrm.Sdk.AppDomainBasedKnownProxyTypesProvider..ctor()
       at Microsoft.Xrm.Sdk.KnownProxyTypesProvider.GetInstance(Boolean supportIndividualAssemblies)
       at Microsoft.Xrm.Sdk.ProxySerializationSurrogate.System.Runtime.Serialization.IDataContractSurrogate.GetObjectToSerialize(Object obj, Type targetType)
       at System.Runtime.Serialization.DataContractSerializer.SurrogateToDataContractType(IDataContractSurrogate dataContractSurrogate, Object oldObj, Type surrogatedDeclaredType, Type& objType)
       at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionaryWriter writer, Object graph)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameterPart(XmlDictionaryWriter writer, PartInfo part, Object graph)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameter(XmlDictionaryWriter writer, PartInfo part, Object graph)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, Object[] parameters)
       at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.SerializeBody(XmlDictionaryWriter writer, MessageVersion version, String action, MessageDescription messageDescription, Object returnValue, Object[] parameters, Boolean isRequest)
       at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(XmlDictionaryWriter writer, MessageVersion version, Object[] parameters, Object returnValue, Boolean isRequest)
       at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessage.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
       at System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWriter writer)
       at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
       at System.ServiceModel.Channels.Message.WriteBodyContents(XmlDictionaryWriter writer)
       at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteBodyContents(XmlDictionaryWriter writer)
       at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteMessage(XmlDictionaryWriter writer)
       at System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer)
       at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota)
       at System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
       at System.ServiceModel.Channels.HttpOutput.SerializeBufferedMessage(Message message)
       at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
       at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.SendRequest(Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
       at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

    Exception rethrown at [0]:
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
       at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
       at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Execute(OrganizationRequest request)
       at Microsoft.Xrm.Client.Services.OrganizationService.<>c__DisplayClass19.<Execute>b__18(IOrganizationService s)
       at Microsoft.Xrm.Client.Services.OrganizationService.InnerOrganizationService.UsingService[TResult](Func`2 action)
       at Microsoft.Xrm.Client.Services.OrganizationService.Execute(OrganizationRequest request)
       at CRM2BOB.frm_CRM2BOB.btnPreviewCases_Click(Object sender, EventArgs e) in C:\Users\bjorn.baecke\Desktop\CRM2BOB new\CRM2BOB - Bjorn\CRM2BOB\Frm_CRM2BOB.cs:line 718
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at CRM2BOB.Program.Main() in C:\Users\bjorn.baecke\Desktop\CRM2BOB new\CRM2BOB - Bjorn\CRM2BOB\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

    Thursday, August 4, 2011 2:59 PM
  • Hi,

    Change this line var service = new OrganizationService(connection);

    to

    var service = new IOrganizationService(connection);
    

    try also the old code it shoudl work also now.


    Jehanzeb Javeed

    http://worldofdynamics.blogspot.com
    Linked-In Profile |CodePlex Profile

    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".
    • Proposed as answer by Jim Glass Jr Thursday, August 4, 2011 3:32 PM
    • Marked as answer by m83 Friday, August 5, 2011 7:32 AM
    Thursday, August 4, 2011 3:04 PM
  • I cannot create an instance of the IOrganizationService, it's an abstract class..
    Thursday, August 4, 2011 3:13 PM
  • Hi,

    You can use it like this:

     

     IOrganizationService service = (IOrganizationService)GetCRMServiceObject("username", "password", "domain", "organizationname", "crmurl");
    

     private IOrganizationService GetCRMServiceObject(string prmUserName, string prmPassword, string prmDomain, string prmOrgName, string prmServergUrl)
            {
                OrganizationServiceProxy lclCrmServiceProxy = null;

     

                IOrganizationService lclCrmService = null;

                ClientCredentials lclClientCredentials = new ClientCredentials();

                Uri lclOrganizationUri = null;

                string lclCRMServiceUrl = string.Empty;

                try
                {
                    lclClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(prmUserName, prmPassword, prmDomain);

                    lclCRMServiceUrl = string.Concat(prmServergUrl, "/", prmOrgName, "/XRMServices/2011/Organization.svc");

                    lclOrganizationUri = new Uri(lclCRMServiceUrl);

                    lclCrmServiceProxy = new OrganizationServiceProxy(lclOrganizationUri, lclOrganizationUri, lclClientCredentials, null);

                    lclCrmService = (IOrganizationService)lclCrmServiceProxy;

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


                return lclCrmService;
            }

     

    or can also use like this:

    IOrganizationService service = (IOrganizationService)new OrganizationServiceProxy(connection);


    Jehanzeb Javeed

    http://worldofdynamics.blogspot.com
    Linked-In Profile |CodePlex Profile

    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".

    • Proposed as answer by Jim Glass Jr Thursday, August 4, 2011 3:32 PM
    Thursday, August 4, 2011 3:24 PM
  • Try changing the Condition Operator to Like:

    conditionexpre.Operator = ConditionOperator.Like;
    string[] condition = { "%tes%" };
    
    
    Contains will only work if Full Text Indexing has been enabled.

     


    --pogo (pat) @ pogo69.wordpress.com
    Thursday, August 4, 2011 8:31 PM
  • I'm still getting that "Collection was modified; enumeration operation may not execute." error!

     

    I'm really confused now...


    Friday, August 5, 2011 7:11 AM
  • I found the problem. I had to change to following lines:

     

                string[] condition = { "bro" };
                conditionexpre.Values.Add(condition);

     

                ==> conditionexpre.Values.Add("bro");

     

    AND

               queryAccount.ColumnSet = new ColumnSet(columnset);

     

               ==> queryAccount.ColumnSet.AddColumn("name")


     

     

     

    • Marked as answer by m83 Friday, August 5, 2011 7:31 AM
    Friday, August 5, 2011 7:31 AM