Unable to update OptionSetValue field on CRM 2011 custom Entity - dynamics-crm-2011

I'm getting a "Specified cast is not valid." Exception when trying to update an OptionSetValue attribute of a custom field on a custom entity.
This works:
data = new Xrm.Xyz_data()
{
Xyz_dataId = (Guid)entity["xyz_dataId"],
// Xyz_dataStatus = new OptionSetValue(5),
Xyz_IsSyncReqd = true
};
service.Update(data);
But uncomment the OptionSetValue line and it throws this exception:
System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]: Specified cast is not valid. (Fault Detail is equal to Microsoft.Xrm.Sdk.OrganizationServiceFault).
With this stack trace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
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.Update(Entity entity)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.UpdateCore(Entity entity)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.Update(Entity entity)

That looks right to me - I don't use early bound which it looks like you are doing but can you verify that the data context has been refreshed since the picklist attribute was created and published?
If this is a built in state field you will probably need to first do the update and then perform a UpdateStateValueRequest. Excerpt from CRM 2011 SDK -
#region How to update state value
// Modify the state value label from Active to Open.
// Create the request.
UpdateStateValueRequest updateStateValue = new UpdateStateValueRequest
{
AttributeLogicalName = "statecode",
EntityLogicalName = Contact.EntityLogicalName,
Value = 1,
Label = new Label("Open", _languageCode)
};
// Execute the request.
_serviceProxy.Execute(updateStateValue);
#endregion How to update state value

So I finally figured out what was happening. I turned on server side debugging using the same registry settings as CRM 4.0:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM]
"TraceEnabled"=dword:00000001
"TraceCategories"="*:Error"
"TraceCallStack"=dword:00000001
"TraceRefresh"=dword:00000001
I reran my test that was failing, and found this error:
[2011-10-24 18:19:37.990] Process: w3wp |Organization:00000000-0000-0000-0000-000000000000 |Thread: 14 |Category: Platform |User: 00000000-0000-0000-0000-000000000000 |Level: Error | ExceptionConverter.ConvertMessageAndErrorCode
at ExceptionConverter.ConvertMessageAndErrorCode(Exception exception, Int32& errorCode)
at ExceptionConverter.ToSingleFaultOther(Exception exception)
at ExceptionConverter.ToSingleFaultUntyped(Exception exception)
at ExceptionConverter.ConvertToFault(Exception exception)
at ExceptionConverter.TryConvertToFaultExceptionInternal(Exception exception, Boolean createNewFaultException, FaultException`1& faultException)
at FaultHelper.ConvertToFault(Exception exception)
at OrganizationSdkServiceInternal.Update(Entity entity, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at
at SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at MessageRpc.Process(Boolean isOperationContextSet)
at ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
at ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
at ChannelHandler.AsyncMessagePump(IAsyncResult result)
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at AsyncResult.Complete(Boolean completedSynchronously)
at ReceiveItemAndVerifySecurityAsyncResult`2.InnerTryReceiveCompletedCallback(IAsyncResult result)
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at AsyncResult.Complete(Boolean completedSynchronously)
at AsyncQueueReader.Set(Item item)
at InputQueue`1.Dispatch()
at ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at _IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
>System.InvalidCastException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #9F125FAE: System.InvalidCastException: Specified cast is not valid.
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry.IntentionalRethrow(Exception chainException, Exception originalException)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry.RethrowRecommended(Exception chainException, Exception originalException)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyEntry.Handle(Exception exceptionToHandle)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl.HandleException(Exception exceptionToHandle)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName, ExceptionPolicyFactory policyFactory)
> at Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
> at Common.Services.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
> at XYZ.CRM.Common.Services.ExceptionPolicy.HandleException(Exception exceptionToHandle, String policyName)
> at XYZ.CRM.Plugin.Common.PluginBase.OnError(Exception ex)
> at XYZ.CRM.Plugin.Common.PluginBase.Execute(IServiceProvider serviceProvider)
> at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
> at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
And since I was debugging my plugin via a unit test, I realized that another plugin was getting fired when those fields were updated by my plugin, and that plugin was apparently causing an exception. But even worse was that the exception handler was causing another exception, that was getting returned, masking the true exception. I tested a really simple fix by eating any exceptions that the exception handler might throw, and it is working great now! Now to discover why my other plugin is failing...

Related

Connecting to WCF service from Azure Functions and trouble-shooting assembly bindings

Where can I see the Assembly that Azure functions is trying to load ? (Like fuslogvw on windows)
Update
Update the title as requested to better reflect the accepted answer
Update
Changed my code to 'manually' construct the SOAP request using WebClient and it works ... so me thinks somewhere the WCF service proxy is not playing well within the sandbox that is Azure Functions ... Nevertheless I would still like an answer as to how we can see the Assembly binding log views.
Original Post
I keep getting the same error :
2016-11-17T10:32:44.392 System.IO.FileNotFoundException: The filename,
directory name, or volume label syntax is incorrect. (Exception from
HRESULT: 0x8007007B)
Server stack trace:
at
System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32
errorCode, IntPtr errorInfo)
at Microsoft.Win32.Fusion.ReadCache(ArrayList alAssems, String
name, UInt32 nFlag)
at System.Reflection.RuntimeAssembly.EnumerateCache(AssemblyName
partialName)
at
System.Reflection.RuntimeAssembly.LoadWithPartialNameInternal(AssemblyName
an, Evidence securityEvidence, StackCrawlMark& stackMark)
at System.Reflection.Assembly.LoadWithPartialName(String
partialName, Evidence securityEvidence)
at System.Xml.Serialization.TempAssembly.LoadGeneratedAssembly(Type
type, String defaultNamespace, XmlSerializerImplementation& contract)
at System.Xml.Serialization.XmlSerializer.FromMappings(XmlMapping[]
mappings, Type type)
at
System.ServiceModel.Description.XmlSerializerOperationBehavior.Reflector.SerializerGenerationContext.GenerateSerializers()
at
System.ServiceModel.Description.XmlSerializerOperationBehavior.Reflector.SerializerGenerationContext.GetSerializer(Int32
handle)
at
System.ServiceModel.Description.XmlSerializerOperationBehavior.Reflector.MessageInfo.get_BodySerializer()
at
System.ServiceModel.Dispatcher.XmlSerializerOperationFormatter.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.BodyWriterMessage.OnWriteBodyContents(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.Message.OnWriteMessage(XmlDictionaryWriter
writer)
at
System.ServiceModel.Channels.TextMessageEncoderFactory.TextMessageEncoder.WriteMessage(Message
message, Stream stream)
at
System.ServiceModel.Channels.HttpOutput.WriteStreamedMessage(TimeSpan
timeout)
at System.ServiceModel.Channels.HttpOutput.Send(TimeSpan timeout)
at
System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.SendRequest(Message
message, TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.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)
Currently, there is no support to view assembly binding logs. Enabling diagnostic logs will help debug most of the errors. Also take a look at logging tips and tricks.
Here is a sample for connecting to a WCF service hosted in Azure from your function:
Got to Function App Settings --> Go to Kudu --> Go to D:\home\site\wwwroot\YourFunction
Create folder bin
Upload System.ServiceModel.dll
Upload WCF service contract IService1.csx. You can do this from either Kudu or View Files on the portal
#r "System.ServiceModel.dll"
using System.ServiceModel;
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetData(int value);
[OperationContract]
string WelComeMessage(String name);
}
Sample queue trigger that invokes WCF endpoint:
#r "System.ServiceModel.dll"
#load "IService1.csx"
using System;
using System.ServiceModel;
public static void Run(string myQueueItem, TraceWriter log)
{
log.Info($"C# Queue trigger function processed: {myQueueItem}");
BasicHttpBinding b = new BasicHttpBinding();
EndpointAddress ea = new EndpointAddress("http://YourServiceAddress/service1.svc?wsdl");
var myChannelFactory = new ChannelFactory<IService1>(b, ea);
IService1 client = myChannelFactory.CreateChannel();
var msg= client.WelComeMessage("HelloWorld");
((ICommunicationObject)client).Close();
log.Info($"Hello from WCF: {msg}");
}
Hope this helps!

CRM 2011 - Custom field causes CRM error when set and saved

I have added, as per user requirements, a custom field to the Quote Product entity (quotedetail) of CRM, allowing integration with our financial system (which is not currently in the scope of this problem). The field is named Summary Text Code, and is a lookup to a custom record type that exists purely for this purpose. In our development instance of CRM, this works perfectly, but in the Staging/UAT environment, all users (from the most limited up to SysAdmins) get the following error when attempting to save a record with a value set in this field:
Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: An unexpected error occurred.Detail:
<OrganizationServiceFault xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/xrm/2011/Contracts">
<ErrorCode>-2147220970</ErrorCode>
<ErrorDetails xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<KeyValuePairOfstringanyType>
<d2p1:key>CallStack</d2p1:key>
<d2p1:value xmlns:d4p1="http://www.w3.org/2001/XMLSchema" i:type="d4p1:string"> at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.ExecuteInternal(IInProcessOrganizationServiceFactory serviceFactory, IPlatformMessageDispatcherFactory dispatcherFactory, String messageName, String requestName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, ParameterCollection fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId, Guid transactionContextId, Int32 invocationSource, Nullable`1 requestId, Version endpointVersion)
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, UserAuth userAuth, Guid targetUserId, Boolean traceRequest, OrganizationContext context, Boolean returnResponse)
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)</d2p1:value>
</KeyValuePairOfstringanyType>
</ErrorDetails>
<Message>An unexpected error occurred.</Message>
<Timestamp>2014-07-23T21:56:55.0044932Z</Timestamp>
<InnerFault i:nil="true" />
<TraceText i:nil="true" />
</OrganizationServiceFault>
A little Google-fu turned up the implication that this was a plugin problem. However, we have text file logging of our plugins, especially the one we have for Quote Products, and the plugin is not even entered in this situation.
What's even weirder is that the error does not occur when the value of this field is not set, so it's really hard for me to assert that I'm not at fault.
A little deeper digging into the event viewer and WER logs returns the following, more detailed error with a stack trace crossing the web service boundary:
Exception generated at: 7/23/2014 5:13:54 PM
Error Type: System.InvalidCastException
Error Message: Specified cast is not valid.
Error Stack Trace:
at SecurityAttributes..ctor(SecurityTraits traits, Guid objectId, Boolean allowNonUniqueRows, ArrayList attributes, ExecutionContext context) ilOffset = 0xB1
at SecurityAttributes..ctor(SecurityTraits traits, Guid objectId, ArrayList attributes, ExecutionContext context) ilOffset = 0x7
at SecurityExtension.GetSecurityAttributes(BusinessEntity entity, AttributeMetadata attribute, ExtensionEventArgs e, Relationship& relationship, SecurityTraits& traits) ilOffset = 0x5E
at SecurityExtension.CheckAppendAccess(BusinessEntity entity, ExtensionEventArgs e) ilOffset = 0x29
at SecurityExtension.PreUpdateHandlerAppendAppendToPrivilegeCheck(Object sender, SecurityTraits traits, SecurityAttributes attributes, ExtensionEventArgs e) ilOffset = 0x28
at SecurityExtension.PreUpdateHandler(ExtensionEventArgs e, Object sender) ilOffset = 0x39
at PreUpdateEventHandler.Invoke(Object sender, ExtensionEventArgs e) ilOffset = 0xFFFFFFFF
at BusinessProcessObject.UpdateWithPipelineAndExtensions(IBusinessEntity entity, ExecutionContext context) ilOffset = 0x6F
at QOIDetailService.Update(IBusinessEntity qoiDetail, ExecutionContext context, Boolean calculatePrice, Boolean checkState, BusinessEntity parentQoi) ilOffset = 0x5B
at QuoteDetailService.Update(IBusinessEntity quoteDetail, ExecutionContext context) ilOffset = 0x78
Stack Frame:
at Pipeline.Execute(PipelineExecutionContext context) ilOffset = 0x65
at MessageProcessor.Execute(PipelineExecutionContext context) ilOffset = 0x1C5
at InternalMessageDispatcher.Execute(PipelineExecutionContext context) ilOffset = 0xE4
at ExternalMessageDispatcher.ExecuteInternal(IInProcessOrganizationServiceFactory serviceFactory, IPlatformMessageDispatcherFactory dispatcherFactory, String messageName, String requestName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, ParameterCollection fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId, Guid transactionContextId, Int32 invocationSource, Nullable`1 requestId, Version endpointVersion) ilOffset = 0x156
at OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, UserAuth userAuth, Guid targetUserId, Boolean traceRequest, OrganizationContext context, Boolean returnResponse) ilOffset = 0x145
at OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType) ilOffset = 0x3D
at OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType) ilOffset = 0x24
at InprocessServiceProxy.ExecuteCore(OrganizationRequest request) ilOffset = 0x34
at PlatformCommand.XrmExecuteInternal() ilOffset = 0xF6
at UpdateCommand.Execute() ilOffset = 0x7
at DataSource.Update(EntityProxy entity, Boolean performDuplicateCheck, Guid auditingTransactionId, IOrganizationContext context) ilOffset = 0x11
at EntityProxy.Update(Boolean performDuplicateCheck, Guid auditingTransactionId) ilOffset = 0x0
at EntityProxy.Update(Boolean performDuplicateCheck) ilOffset = 0x7
at AppForm.SaveEntity(EntityProxy entity, FormEventId eventType, String redirectPath, Boolean performDuplicateCheck) ilOffset = 0x2A
at AppForm.Save(Boolean& gridRefreshCallbackAdded) ilOffset = 0x47
at AppForm.FormSaveEvent() ilOffset = 0xD
at AppForm.RaiseDataEvent(FormEventId eventId) ilOffset = 0xCF
at EndUserForm.Initialize(Entity entity) ilOffset = 0x1F
at CustomizableForm.Execute(Entity entity, FormDescriptor fd) ilOffset = 0x62
at QuoteDetailRecordPageHandler.ConfigureFormHandler() ilOffset = 0x98
at RecordPageHandler.ConfigureFormWrapper() ilOffset = 0xC
at GenericEventProcessor.RaiseEvent(String eventName) ilOffset = 0x2D
at PageManager.OnPreRender(EventArgs e) ilOffset = 0x47
at Control.PreRenderRecursiveInternal() ilOffset = 0x54
at Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) ilOffset = 0x6D3
at Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) ilOffset = 0x3C
at Page.ProcessRequest() ilOffset = 0x14
at Page.ProcessRequest(HttpContext context) ilOffset = 0x33
at CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() ilOffset = 0x18D
at HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) ilOffset = 0x15
at ApplicationStepManager.ResumeSteps(Exception error) ilOffset = 0x10A
at HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) ilOffset = 0x5C
at HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) ilOffset = 0x16A
at ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType) ilOffset = 0x4B
Exception Data:
1: Key type: System.String, value: PluginTrace
Custom Message: Web Service Plug-in failed in SdkMessageProcessingStepId: a8cdbb1b-ea3e-db11-86a7-000a3a5473e8; EntityName: quotedetail; Stage: 30; MessageName: Update; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: System.InvalidCastException: Specified cast is not valid.
at Microsoft.Crm.BusinessEntities.SecurityAttributes..ctor(SecurityTraits traits, Guid objectId, Boolean allowNonUniqueRows, ArrayList attributes, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.SecurityAttributes..ctor(SecurityTraits traits, Guid objectId, ArrayList attributes, ExecutionContext context)
at Microsoft.Crm.BusinessEntities.SecurityExtension.GetSecurityAttributes(BusinessEntity entity, AttributeMetadata attribute, ExtensionEventArgs e, Relationship& relationship, SecurityTraits& traits)
at Microsoft.Crm.BusinessEntities.SecurityExtension.CheckAppendAccess(BusinessEntity entity, ExtensionEventArgs e)
at Microsoft.Crm.BusinessEntities.SecurityExtension.PreUpdateHandlerAppendAppendToPrivilegeCheck(Object sender, SecurityTraits traits, SecurityAttributes attributes, ExtensionEventArgs e)
at Microsoft.Crm.BusinessEntities.SecurityExtension.PreUpdateHandler(ExtensionEventArgs e, Object sender)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.PreUpdateEventHandler.Invoke(Object sender, ExtensionEventArgs e)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.UpdateWithPipelineAndExtensions(IBusinessEntity entity, ExecutionContext context)
at Microsoft.Crm.ObjectModel.QOIDetailService.Update(IBusinessEntity qoiDetail, ExecutionContext context, Boolean calculatePrice, Boolean checkState, BusinessEntity parentQoi)
at Microsoft.Crm.ObjectModel.QuoteDetailService.Update(IBusinessEntity quoteDetail, ExecutionContext context)
At this point I'm stumped. Not a single line of any error trace even goes through custom code, much less terminating at one, so this appears to be 100% CRM throwing a fit for reasons I cannot yet understand.
The root cause appears to be a bug in the SSIS import job used to populate the lookup table; the job was using the wrong OrgID (or none at all) and so CRM was throwing a fit that the data being linked together weren't part of the same logical organization schema, even though they were in the same DB. Lesson learned.

Post Updating of ServiceAppointment entity giving strange error

We're trying to update CRM 2011 from RU 11 to RU 14 to be able to install RU 15 when RU 14 is all ready to go. Been fixing various issues concerning this update since Microsoft did quite some changes due to the Cross Platform and obviously since were moving from the 11 to the 14.
Now, my main issue is that I have a plugin that's running synchronously on the create of a service appointment. It's in charge of doing several things, like comparing values or using values from other entities to populate data in the Service Activity record. Regarding what the strange error is, since changes are being done on a Post Operations, a _service.Update(entity) has to be done in order for changes to be seen in the form and database. If I debug the code step by step everything passes smoothly except when the code reaches the .Update. When the update is called CRM throws an Unexpected Error Occured. When I go to the TraceLogs this is what I find:
[2013-12-10 14:49:56.323] Process: w3wp |Organization:3e484d20-6245-e311-8a60-00155d6f6b34 |Thread: 20 |Category: Platform.Sdk |User: 0a51b463-df74-e011-81b3-00155d7a7a17 |Level: Error |ReqId: dca72532-8bed-491c-9295-62211d39a6f6 | VersionedPluginProxyStepBase.Execute ilOffset = 0x65
at VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context) ilOffset = 0x65
at Pipeline.Execute(PipelineExecutionContext context) ilOffset = 0x65
at MessageProcessor.Execute(PipelineExecutionContext context) ilOffset = 0x1C5
at InternalMessageDispatcher.Execute(PipelineExecutionContext context) ilOffset = 0xE4
at ExternalMessageDispatcher.ExecuteInternal(IInProcessOrganizationServiceFactory serviceFactory, IPlatformMessageDispatcherFactory dispatcherFactory, String messageName, String requestName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, ParameterCollection fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId, Guid transactionContextId, Int32 invocationSource, Nullable`1 requestId, Version endpointVersion) ilOffset = 0x156
at OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType, UserAuth userAuth, Guid targetUserId, Boolean traceRequest, OrganizationContext context, Boolean returnResponse) ilOffset = 0x145
at OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType) ilOffset = 0x34
at OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType) ilOffset = 0x24
at InprocessServiceProxy.ExecuteCore(OrganizationRequest request) ilOffset = 0x34
at SandboxSdkListener.Execute(SandboxCallInfo callInfo, SandboxSdkContext requestContext, String operation, Byte[] serializedRequest) ilOffset = 0xAC
at ilOffset = 0xFFFFFFFF
at SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) ilOffset = 0x241
at DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) ilOffset = 0x100
at ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) ilOffset = 0x48
at ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) ilOffset = 0xC6
at MessageRpc.Process(Boolean isOperationContextSet) ilOffset = 0x62
at ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext) ilOffset = 0x256
at ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext) ilOffset = 0xF1
at ChannelHandler.AsyncMessagePump(IAsyncResult result) ilOffset = 0x39
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) ilOffset = 0x0
at AsyncResult.Complete(Boolean completedSynchronously) ilOffset = 0xC2
at TryReceiveAsyncResult.OnReceive(IAsyncResult result) ilOffset = 0x4B
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) ilOffset = 0x0
at AsyncResult.Complete(Boolean completedSynchronously) ilOffset = 0xC2
at ReceiveAsyncResult.OnReceiveComplete(Object state) ilOffset = 0x2B
at SessionConnectionReader.OnAsyncReadComplete(Object state) ilOffset = 0xBC
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result) ilOffset = 0x0
at LazyAsyncResult.Complete(IntPtr userToken) ilOffset = 0x3E
at NegotiateStream.ProcessFrameBody(Int32 readBytes, Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) ilOffset = 0x70
at NegotiateStream.ReadCallback(AsyncProtocolRequest asyncRequest) ilOffset = 0x68
at FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes) ilOffset = 0x5D
at FixedSizeReader.ReadCallback(IAsyncResult transportResult) ilOffset = 0x29
at AsyncResult.Complete(Boolean completedSynchronously) ilOffset = 0xC2
at IOAsyncResult.OnAsyncIOComplete(Object state) ilOffset = 0x26
at SocketConnection.OnReceiveAsync(Object sender, SocketAsyncEventArgs eventArgs) ilOffset = 0x57
at SocketAsyncEventArgs.FinishOperationSuccess(SocketError socketError, Int32 bytesTransferred, SocketFlags flags) ilOffset = 0x5CB
at SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped) ilOffset = 0x10
at _IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP) ilOffset = 0x3C
>Web Service Plug-in failed in SdkMessageProcessingStepId: {B9CDBB1B-EA3E-DB11-86A7-000A3A5473E8}; EntityName: serviceappointment; Stage: 30; MessageName: Update; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: **Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.**
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
**Inner 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.Collections.CollectionBase.System.Collections.IList.get_Item(Int32 index)
at Microsoft.Crm.BusinessEntities.BusinessEntityCollection.get_Item(Int32 index)
at Microsoft.Crm.ObjectModel.CommunicationActivityServiceBase.UpdateCommunicationPartiesInternal(BusinessEntityMoniker moniker, CommunicationActivity activity, ExecutionContext context, ExtensionEventArgs e)
at Microsoft.Crm.ObjectModel.CommunicationActivityServiceBase.UpdateCommunicationParties(Object sender, ExtensionEventArgs e)
at Microsoft.Crm.BusinessEntities.BusinessProcessObject.PostUpdateEventHandler.Invoke(Object sender, ExtensionEventArgs e)
at Microsoft.Crm.ObjectModel.GenericActivityServiceBase.UpdateInternal(IBusinessEntity entityInterface, ExecutionContext context)
at Microsoft.Crm.ObjectModel.CommunicationActivityServiceBase.Update(IBusinessEntity entityInterface, ExecutionContext context)
_______________
I've done different changes trying to figure out what the problem would be, among them, turning off all registered plugins other than Microsoft ones and this one. Turned off all JavaScript in the form in case any values are being changed that are making it throw the error, hard coded State Code and Status Code because of some related issues found online, commented ALL the code in the plugin and only left the _service.Update(entity) in case an invalid value was being passed but update would still throw error, and other things I found online that seemed like a solution. I've been going on this error for some time now and would like to have some more minds thinking this out with me. The plugin has to be run Synchronously and in the Post Operation because of logic tied to the plugin.
Any help is appreciated and if you need any more information to understand what could be going on please let me know.
I've been tearing my hair out of the exact same issue. My same code works fine on other types of entities, so I isolated it only occurring on a activities (i.e. anything that uses ActivityBase). This looks like a bug within CRM's internal object model (present at least in UR11, which is the version I'm running) that occurs in the following circumstance:
You're triggering a plugin that is:
against is an Activity (Appointment, Service Activity, Task, Email, etc) or custom Activity Type
Triggered on the Create message
Run Synchronously
Runs Post-Operation
One of the features that all Activity entities have compared to other entities that is the presence of activity participants (ActivityParties), which are standard fields like 'Attendees', 'Customers', useful email fields ('To', 'CC', 'BCC'), which can contain a number of different types such as 'RequiredAttendee', 'Organizer', 'To', but also importantly it creates one for the record 'Owner' too (see http://msdn.microsoft.com/en-us/library/gg328549.aspx for the full list).
After looking at the SQL that's being executed (and also a sneaky peek in a .NET decompiler within Microsoft.Crm.ObjectModel) it appears that the issue lies with the order in which the Activity Parties are (or aren't) being created or updated. For activities after the usual Create() message processing (including your plugin code) is finished executing, these ActivityParty record(s) (including one for the Owner) are populated from the entity data. On Update() there is also a check that processes any changes required to the ActivityParties, however this (erroneously) assumes that ActivityParty records have already been created.
..so if you're calling Update within the Create message, then the initial Create message hasn't finished before the Update ActivityParty throws it's ArgumentOutOfRangeException as it doesn't have any records yet.
This also explains why it works as expected in Async mode, as the ActivityParties are created successfully right after the usual Create() process but before the Update triggered by the plugin execution code runs a few seconds later.
Depending upon what you're trying to achieve, as a work around it might be possible to rework your plugin to function on the Pre-Operation event instead.

Install-SPUserSolution: Sandboxed code execution request failed

When executing Install-SPUserSolution powershell command the following error is shown:
Install-SPUserSolution : Sandboxed code execution request failed.
At line:1 char:23
+ Install-SPUserSolution <<<< -Identity some_package.wsp -Site http://localhost/sites/test
+ CategoryInfo : InvalidData: (Microsoft.Share...allUserSolution:
SPCmdletInstallUserSolution) [Install-SPUserSolution], SPUserCodeExecu...F
ailedException
+ FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletInstallU
serSolution
When I try to activate the user solution from the SharePoint interface everything works fine. So this doesn't work only from PowerShell. I tried to run user code service under different account (admin account) but this didn't help. Currently this service is running under Network Service account.
Also when I run Add-SPUserSolution or Uninstall-SPUserSolution they work just fine. I was able to reproduce this issue on at least two servers. Please advice.
[UPD] I'm including full stack trace from SharePoint logs
Sandboxed code execution request failed. - Inner Exception: System.InvalidOperationException Server stack trace: at Microsoft.SharePoint.Utilities.Verify.DoFailTag(UInt32 tag, ULSCat category, Type type, String format, Object[] args) at Microsoft.SharePoint.Utilities.Verify.IsTrueTag(UInt32 tag, ULSCat category, Boolean expression, Type type, String format, Object[] args) at Microsoft.SharePoint.UserCode.SPUserCodeExecutionHost.Execute(Type userCodeWrapperType, Guid siteCollectionId, SPUserToken userToken, String affinity, SPUserCodeExecutionContext executionContext) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext) 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.SharePoint.Administration.ISPUserCodeExecutionHostProxy.Execute(Type userCodeWrapperType, Guid siteCollectionId, SPUserToken userToken, String affinityBucketName, SPUserCodeExecutionContext executionContext) at Microsoft.SharePoint.UserCode.SPUserCodeExecutionManager.Execute(Type userCodeWrapperType, SPSite site, SPUserCodeExecutionContext executionContext)

Publishing web project to azure failed: The "IsolatedCSPack" task failed unexpectedly

I have web application that I want to publish and upload to windows azure.
I use Visual Studio 2008.
I click on "publish", chose "Create Service Package Only" in "Publish Cloud Service" window, andclick on "OK".
The publish failed tnd the exception is:
Error 26 The "IsolatedCSPack" task failed unexpectedly.
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
Server stack trace:
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Packaging.SparseMemoryStream.CopyMemoryBlocksToStream(Stream targetStream)
at MS.Internal.IO.Packaging.SparseMemoryStream.WriteToStream(Stream stream)
at MS.Internal.IO.Zip.ZipIOFileItemStream.Save()
at MS.Internal.IO.Zip.ZipIOLocalFileBlock.Save()
at MS.Internal.IO.Zip.ZipIOBlockManager.SaveContainer(Boolean closingFlag)
at MS.Internal.IO.Zip.ZipIOBlockManager.SaveStream(ZipIOLocalFileBlock blockRequestingFlush, Boolean closingFlag)
at MS.Internal.IO.Zip.ZipIOModeEnforcingStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()
at System.IO.Packaging.PackagePart.Close()
at System.IO.Packaging.Package.DoClose(PackagePart p)
at System.IO.Packaging.Package.DoOperationOnEachPart(PartOperation operation)
at System.IO.Packaging.Package.System.IDisposable.Dispose()
at Microsoft.ServiceHosting.Tools.Packaging.PackageCreator.CreateRolePackages(ModelProcessor modelProcessor, PackageManifest applicationManifest, Package applicationPackage)
at Microsoft.ServiceHosting.Tools.Packaging.PackageCreator.CreatePackage(Stream outputStream)
at Microsoft.ServiceHosting.Tools.Packaging.ServiceApplicationPackage.CreateServiceApplicationPackage(String serviceModelFileName, String serviceDescriptionFile, Stream output, IPackageSecurity encrypt, Dictionary`2 namedStreamCollection, String userInfo, EventHandler`1 rolePackagePartAddedHandler)
at Microsoft.ServiceHosting.Tools.Packaging.ServiceApplicationPackage.CreateServiceApplicationPackage(String serviceModelFileName, String serviceDescriptionFile, Stream output, RSACryptoServiceProvider encrypt, Dictionary`2 namedStreamCollection, String userInfo, EventHandler`1 rolePackagePartAddedHandler)
at Microsoft.ServiceHosting.Tools.MSBuildTasks.CSPack.TryCreatePackage(ServiceDefinitionModel sm)
at Microsoft.ServiceHosting.Tools.MSBuildTasks.CSPack.Execute()
at Microsoft.CloudExtensions.MSBuildTasks.IsolatedCSPack.RemoteCSPackBridge.Execute(TaskLoggingHelper log, IBuildEngine buildEngine, ITaskHost hostObject, String serviceHostingTasksPath, String output, String serviceDefinitionFile, ITaskItem[] packRoles, Boolean copyOnly, String generateConfigurationFile, Boolean noEncryptPackage, ITaskItem[]& copiedFiles, ITaskItem[]& outputFiles)
at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)
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.CloudExtensions.MSBuildTasks.IsolatedCSPack.RemoteCSPackBridge.Execute(TaskLoggingHelper log, IBuildEngine buildEngine, ITaskHost hostObject, String serviceHostingTasksPath, String output, String serviceDefinitionFile, ITaskItem[] packRoles, Boolean copyOnly, String generateConfigurationFile, Boolean noEncryptPackage, ITaskItem[]& copiedFiles, ITaskItem[]& outputFiles)
at Microsoft.CloudExtensions.MSBuildTasks.IsolatedCSPack.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) C:\Program Files\MSBuild\Microsoft\Cloud Service\v1.0\Microsoft.CloudService.targets 865 5 Starlims.SDMS.Azure
How can i resolve this?
Happened to me before... try restarting the computer (I know... it's a bit "Technical Support" advice - but it worked for me!
This looks like the same problem someone else posted about on the MSDN Azure forum. Their problem was that a resource was being copied into the project with:
build action = Content
Copy to Output Directory = Copy if Newer.
They changed the latter to Never and the problem went away.

Resources