web api internal error 500 - web

I am using the laatest version of web api.
I am returning a IQuerable value and i am getting this error:
iisexpress.exe Error: 0 : Operation=QueryableAttribute.ActionExecuted, Status=200 (OK), Exception=System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateStructuralTypeBody(EdmStructuredType type, IStructuralTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateEntityTypeBody(EdmEntityType type, IEntityTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateEdmTypeBody(IStructuralTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.<GetEdmTypes>d__0.MoveNext()
at System.Linq.Enumerable.<OfTypeIterator>d__aa`1.MoveNext()
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at System.Linq.Enumerable.ToDictionary[TSource,TKey](IEnumerable`1 source, Func`2 keySelector)
at System.Web.Http.OData.Builder.EdmModelHelperMethods.BuildEdmModel(String containerNamespace, String containerName, IEnumerable`1 entityTypeConfigurations, IEnumerable`1 entitySetConfigurations)
at System.Web.Http.OData.Builder.ODataModelBuilder.GetEdmModel()
at System.Web.Http.OData.Builder.ODataConventionModelBuilder.GetEdmModel()
at System.Web.Http.HttpActionDescriptorExtensions.<>c__DisplayClass1.<GetEdmModel>b__0(Object _)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Web.Http.HttpActionDescriptorExtensions.GetEdmModel(HttpActionDescriptor actionDescriptor, Type entityClrType)
at System.Web.Http.QueryableAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
at System.Web.Http.Tracing.Tracers.ActionFilterAttributeTracer.<>c__DisplayClass4.<OnActionExecuted>b__1()
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Action execute, Action`1 endTrace, Action`1 errorTrace)
iisexpress.exe Error: 0 : Operation=InteractionDataController.ExecuteAsync, Exception=System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateStructuralTypeBody(EdmStructuredType type, IStructuralTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateEntityTypeBody(EdmEntityType type, IEntityTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.CreateEdmTypeBody(IStructuralTypeConfiguration config)
at System.Web.Http.OData.Builder.EdmTypeBuilder.<GetEdmTypes>d__0.MoveNext()
at System.Linq.Enumerable.<OfTypeIterator>d__aa`1.MoveNext()
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at System.Linq.Enumerable.ToDictionary[TSource,TKey](IEnumerable`1 source, Func`2 keySelector)
at System.Web.Http.OData.Builder.EdmModelHelperMethods.BuildEdmModel(String containerNamespace, String containerName, IEnumerable`1 entityTypeConfigurations, IEnumerable`1 entitySetConfigurations)
at System.Web.Http.OData.Builder.ODataModelBuilder.GetEdmModel()
at System.Web.Http.OData.Builder.ODataConventionModelBuilder.GetEdmModel()
at System.Web.Http.HttpActionDescriptorExtensions.<>c__DisplayClass1.<GetEdmModel>b__0(Object _)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Web.Http.HttpActionDescriptorExtensions.GetEdmModel(HttpActionDescriptor actionDescriptor, Type entityClrType)
at System.Web.Http.QueryableAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
at System.Web.Http.Tracing.Tracers.ActionFilterAttributeTracer.<>c__DisplayClass4.<OnActionExecuted>b__1()
at System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Action execute, Action`1 endTrace, Action`1 errorTrace)
at System.Web.Http.Tracing.Tracers.ActionFilterAttributeTracer.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
at System.Web.Http.Filters.ActionFilterAttribute.CallOnActionExecuted(HttpActionContext actionContext, HttpResponseMessage response, Exception exception)
at System.Web.Http.Filters.ActionFilterAttribute.<>c__DisplayClass2.<System.Web.Http.Filters.IActionFilter.ExecuteActionFilterAsync>b__0(HttpResponseMessage response)
at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass41`2.<Then>b__40(Task`1 t)
at System.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)
Can someone explain me what the problem is ?

I was getting this same error. I traced it down to when ODataModelBuilder calls GetEdmModel(). I'm using ODataConventionModelBuilder and I'm declaring EntitySets to create my model. In my case, I have a parent class with a child collection. I tried different types of collections, IList, List, ICollection, IEnumerable, and I continued to get this error. I know this isn't the best solution, but I declare the child collection as object. I assign the collection as IEnumerable using Linq. I'll keep looking into this, but at least I can continue with my project. I'll have to keep researching the ODataConventionModelBuilder. I hope this at least points you in the right direction.
-Jason

This seems to be a known issue in WebApi.OData package (0.1.0-alpha-120815). See http://aspnetwebstack.codeplex.com/discussions/394626

Related

Sitecore Logs - Azure Search

Currently I'm seeing the following a lot in my logs, I'm using Sitecore 8.2 rev 2 with azure. The issue only started recently when I added some new indexes to the site for a new microsite. Any ideas of where to start investigating, I've raised with Sitecore too?
ManagedPoolThread #17 22:03:10 ERROR Exception
Exception: System.Reflection.TargetInvocationException
Message: Exception has been thrown by the target of an invocation.
Source: mscorlib
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 Sitecore.Reflection.ReflectionUtil.InvokeMethod(MethodInfo method, Object[] parameters, Object obj)
at Sitecore.Jobs.JobRunner.RunMethod(JobArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain)
at Sitecore.Jobs.Job.ThreadEntry(Object state)
Nested Exception
Exception: System.AggregateException
Message: One or more errors occurred.
Source: mscorlib
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, ParallelOptions parallelOptions, Action`2 body)
at Sitecore.ContentSearch.AbstractSearchIndex.PerformUpdate(IEnumerable`1 indexableInfo, IndexingOptions indexingOptions)
Nested Exception
Exception: System.InvalidOperationException
Message: Sequence contains no elements
Source: System.Core
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Sitecore.ContentSearch.Azure.CloudSearchUpdateContext.Delete(IIndexableId id)
at Sitecore.ContentSearch.SitecoreItemCrawler.Update(IProviderUpdateContext context, IIndexableUniqueId indexableUniqueId, IndexEntryOperationContext operationContext, IndexingOptions indexingOptions)
at Sitecore.ContentSearch.AbstractSearchIndex.<>c__DisplayClass93_2.<PerformUpdate>b__0(IndexableInfo info, ParallelLoopState parallelLoopState)
at System.Threading.Tasks.Parallel.<>c__DisplayClass17_0`1.<ForWorker>b__1()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass176_0.<ExecuteSelfReplicating>b__0(Object )
For those with the same issue,
The patch is Sitecore.Support.158988 found here:
https://github.com/SitecoreSupport/Sitecore.Support.158988
Versions cover Sitecore 8.2 update 1 and update 2.
164633 The CloudSearchUpdateContext.Delete(IIndexableId) fails with an exception in case the search index does not contain any matching documents.
Thanks.
Looks like there is a patch for this from Sitecore, hopefully this will resolve the issue.

Acumatica Error: 'AP Sub.' cannot be empty

In Acumatica I am trying to update payment instructions on a location for a supplier and it wont allow me to save saying Error: 'AP Sub.' cannot be empty.
I am not using sub accounts at all and the GL accounts tab is filled out.
After getting the message a trace shows the following:
Error: Error: 'AP Sub.' cannot be empty. Send
Raised At: 26/06/2017 1:19:58 AM Screen: AP.30.30.10 Command: Save
26/06/2017 1:19:58 AM Error:
Error: 'AP Sub.' cannot be empty.
at MYOB.AdvancedLive.Core.Extensions.AP.VendorLocationMaintExtension.Location_RowPersisting(PXCache sender, PXRowPersistingEventArgs args, PXRowPersisting handler)
at PX.Data.PXRowPersisting.Invoke(PXCache sender, PXRowPersistingEventArgs e)
at PX.Data.PXCache.OnRowPersisting(Object item, PXDBOperation operation)
at PX.Data.PXCache`1.PersistUpdated(Object row)
at PX.Data.PXCache`1.Persist(PXDBOperation operation)
at PX.Data.PXGraph.Persist(Type cacheType, PXDBOperation operation)
at PX.Data.PXGraph.Persist()
at PX.Objects.CR.LocationMaint.Persist()
at PX.Objects.AP.VendorLocationMaint.Persist()
at PX.Data.PXSave`1.d__2.MoveNext()
at PX.Data.PXAction`1.d__31.MoveNext()
at PX.Data.PXAction`1.d__31.MoveNext()
at PX.Web.UI.PXBaseDataSource.tryExecutePendingCommand(String viewName, String[] sortcolumns, Boolean[] descendings, Object[] searches, Object[] parameters, PXFilterRow[] filters, DataSourceSelectArguments arguments, Boolean& closeWindowRequired, Int32& adapterStartRow, Int32& adapterTotalRows)
at PX.Web.UI.PXBaseDataSource.ExecuteSelect(String viewName, DataSourceSelectArguments arguments, PXDSSelectArguments pxarguments)
Based on attached stack trace, the exception is thrown inside Location_RowPersisting event handler declared within the MYOB.AdvancedLive.Core.Extensions.AP.VendorLocationMaintExtension class. I would recommend contacting MYOB support and ask them to further review this issue.

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.

Unable to use PostFile to upload image

I am trying to use PostFile to upload an image. As a simple example I have the following DTO:
[Route("/Pictures/{Id}", "GET, PUT, DELETE")]
public class Picture
{
public int Id { get; set; }
}
public class PictureResponse : IHasResponseStatus
{
public int Id { get; set; }
#region Implementation of IHasResponseStatus
public ResponseStatus ResponseStatus { get; set; }
#endregion
}
My GET works fine:
public override object OnGet(Picture request)
{
var memoryStream = new MemoryStream();
PictureRepository.Get(request.Id).Save(memoryStream, ImageFormat.Png);
return new HttpResult(memoryStream, "image/png");
}
But my PostFile blows up:
var imagePathInfo = new FileInfo(#"C:\Users\Mark\Downloads\avatars\symang.jpg");
var serviceClient = new JsonServiceClient("http://localhost:52712/api")
serviceClient.PostFile<PictureResponse>("/Pictures/{0}".Fmt(id), imagePathInfo, MimeTypes.GetMimeType(imagePathInfo.Name));
Here's the error and stack trace:
Server Error in '/' Application.
An existing connection was forcibly closed by the remote host
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Source Error:
Line 32: var imagePathInfo = new FileInfo(#"C:\Users\Mark\Downloads\avatars\symang.jpg");
Line 33: var serviceClient = new JsonServiceClient("http://localhost:52712/api");
Line 34: serviceClient.PostFile<PictureResponse>("/Pictures/{0}".Fmt(id), imagePathInfo, MimeTypes.GetMimeType(imagePathInfo.Name));
Line 35: RedirectToAction("Index");
Line 36: return View();
Source File: C:\Users\Mark\Documents\Visual Studio 2010\Projects\Sandbox\UploadFileAttachments\UploadFileAttachments\Controllers\HomeController.cs Line: 34
Stack Trace:
[SocketException (0x2746): An existing connection was forcibly closed by the remote host]
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +6210712
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +134
[IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.]
System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size) +318
System.Net.HttpWebRequest.MakeMemoryStream(Stream stream) +221
[WebException: The underlying connection was closed: An unexpected error occurred on a receive.]
System.Net.HttpWebRequest.GetResponse() +6115603
ServiceStack.ServiceClient.Web.ServiceClientBase.PostFile(String relativeOrAbsoluteUrl, Stream fileToUpload, String fileName, String mimeType) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceClient.Web\ServiceClientBase.cs:815
ServiceStack.ServiceClient.Web.ServiceClientBase.PostFile(String relativeOrAbsoluteUrl, FileInfo fileToUpload, String mimeType) in C:\src\ServiceStack\src\ServiceStack.Common\ServiceClient.Web\ServiceClientBase.cs:790
UploadFileAttachments.Controllers.HomeController.ChangePicture(Int32 id) in C:\Users\Mark\Documents\Visual Studio 2010\Projects\Sandbox\UploadFileAttachments\UploadFileAttachments\Controllers\HomeController.cs:34
lambda_method(Closure , ControllerBase , Object[] ) +150
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
I'm sure I must be misunderstanding how to use PostFile. By the way, I never hit my OnPost method on my service. Thanks for any insights.
PostFile does a HTTP POST.
But your service only allows GET, PUT and DELETE because of your route in the first line of your example code:
[Route("/Pictures/{Id}", "GET, PUT, DELETE")]
Solution:
Either include POST in your route:
[Route("/Pictures/{Id}", "GET, PUT, DELETE, POST")]
...or just omit the HTTP verbs:
[Route("/Pictures/{Id}")]

Unable to update OptionSetValue field on CRM 2011 custom Entity

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...

Resources