CRM 2011 SDK - Error while using the Create Method - System.ArgumentNullException: Value cannot be null

If you're using the CRM 2011 SDK with a generated proxy, you may encounter an ArgumentNullException when trying to use the Create method on your service instance. To get around this issue, you must enable proxy types on the service proxy instance as follows: 

 

internal static Guid CreateEntity(Entity entity)
{
if (entity == null)
throw new ArgumentNullException("entity");

try
    {
using (OrganizationServiceProxy serviceProxy = GetProxy())
{
serviceProxy.EnableProxyTypes();
            IOrganizationService service = (IOrganizationService)serviceProxy;
entity.Id = service.Create(entity);
return entity.Id;
}
}
catch (SoapException ex)
{
throw ex;
}

internal static OrganizationServiceProxy GetProxy()
{
    ClientCredentials creds = new ClientCredentials();

    creds.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
    string url = string.Format("https://{0}/{1}/XrmServices/2011/Organization.svc", ConfigurationManager.AppSettings["server"], ConfigurationManager.AppSettings["organization"]);

    return new OrganizationServiceProxy(new Uri (url), null, creds, null);

}

Error thrown if you do not enable proxy types:

System.ArgumentNullException: Value cannot be null.
Parameter name: value

Server stack trace:
at System.Xml.XmlDictionaryString..ctor(IXmlDictionary dictionary, String val
ue, Int32 key)
at Microsoft.Xrm.Sdk.KnownTypesResolver.TryResolveType(Type type, Type declar
edType, DataContractResolver knownTypeResolver, XmlDictionaryString& typeName, X
mlDictionaryString& typeNamespace)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.ResolveType(T
ype objectType, Type declaredType, XmlDictionaryString& typeName, XmlDictionaryS
tring& typeNamespace)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteResolved
TypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteTypeInfo
(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract
)
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWith
XsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Objec
t obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectCon
tent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractR
esolver)
at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(Xm
lWriterDelegator writer, Object graph, DataContractResolver dataContractResolver
)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptio
ns(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractRes
olver)
at System.Runtime.Serialization.XmlObjectSerializer.WriteObject(XmlDictionary
Writer writer, Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.Se
rializeParameterPart(XmlDictionaryWriter writer, PartInfo part, Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.Se
rializeParameter(XmlDictionaryWriter writer, PartInfo part, Object graph)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.Se
rializeParameters(XmlDictionaryWriter writer, PartInfo[] parts, Object[] paramet
ers)
at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.Se
rializeBody(XmlDictionaryWriter writer, MessageVersion version, String action, M
essageDescription messageDescription, Object returnValue, Object[] parameters, B
oolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.SerializeBodyContents(Xm
lDictionaryWriter writer, MessageVersion version, Object[] parameters, Object re
turnValue, Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.OperationFormatterMessag
e.OperationFormatterBodyWriter.OnWriteBodyContents(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.BodyWriter.WriteBodyContents(XmlDictionaryWri
ter writer)
at System.ServiceModel.Channels.BodyWriterMessage.OnWriteBodyContents(XmlDict
ionaryWriter writer)
at System.ServiceModel.Channels.Message.WriteBodyContents(XmlDictionaryWriter
writer)
at System.ServiceModel.Security.SecurityAppliedMessage.WriteBodyToSignThenEnc
ryptWithFragments(Stream stream, Boolean includeComments, String[] inclusivePref
ixes, EncryptedData encryptedData, SymmetricAlgorithm algorithm, XmlDictionaryWr
iter writer)
at System.ServiceModel.Security.WSSecurityOneDotZeroSendSecurityHeader.ApplyB
odySecurity(XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator)
at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteMessage(XmlDict
ionaryWriter writer)
at System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writ
er)
at System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message me
ssage, 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 m
essage)
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpCha
nnelRequest.SendRequest(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeS
pan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChann
el.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message messag
e, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean on
eway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan tim
eout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCall
Message methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage req
Msg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgDa
ta, Int32 type)
at Microsoft.Xrm.Sdk.IOrganizationService.Create(Entity entity)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.CreateCore(Entity entity
)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Create(Entity entity)

Comments

  • Anonymous
    April 07, 2011
    The comment has been removed

  • Anonymous
    April 21, 2011
    How do you get GetProxy() in plugin ?

  • Anonymous
    May 03, 2011
    From a plug-in, you should get an instance to your service proxy by something like this:        public void Execute(IServiceProvider serviceProvider)        {            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));            var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);            ...        }