Unable to use PostFile to upload image - servicestack

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}")]

Related

CRM trying re-create 'Business Closure Calendar' calendar every minute

We are getting following error in event log because InternalOperationPlugin is trying to create 'Business Closure Calendar' in Calender entity almost every minute.
InternalOperationPlugin is a core system plugin which is registered on Stage 30 (non-customizable). Can anyone give an idea why core plugin is trying to create this record every minute.
We are on Roll up 8 and not in position to install latest.
Thanks in Advance
The Web Service plug-in failed in OrganizationId: 07ae1f6f-237f-e111-83c6-005056b41d30; SdkMessageProcessingStepId: 22ccbb1b-ea3e-db11-86a7-000a3a5473e8;
EntityName: calendar;
Stage: 30;
MessageName: RetrieveMultiple;
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._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
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.ArgumentException: Item has already been added. Key in dictionary: '7fdf4980-237f-e111-83c6-005056b41d30' Key being added: '7fdf4980-237f-e111-83c6-005056b41d30'
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
at Microsoft.Crm.ObjectModel.CalendarService.RetrieveMultiple(EntityExpression entityExpression, ExecutionContext context)
** Error from Event Log **
at VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
at Pipeline.Execute(PipelineExecutionContext context)
at MessageProcessor.Execute(PipelineExecutionContext context)
at InternalMessageDispatcher.Execute(PipelineExecutionContext context)
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)
at OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at InprocessServiceProxy.ExecuteCore(OrganizationRequest request)
at SandboxSdkListener.Execute(SandboxCallInfo callInfo, SandboxSdkContext requestContext, String operation, Byte[] serializedRequest)
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 TryReceiveAsyncResult.OnReceive(IAsyncResult result)
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at AsyncResult.Complete(Boolean completedSynchronously)
at ReceiveAsyncResult.OnReceiveComplete(Object state)
at SessionConnectionReader.OnAsyncReadComplete(Object state)
at AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at LazyAsyncResult.Complete(IntPtr userToken)
at NegotiateStream.ProcessFrameBody(Int32 readBytes, Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at NegotiateStream.ReadCallback(AsyncProtocolRequest asyncRequest)
at FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
at FixedSizeReader.ReadCallback(IAsyncResult transportResult)
at AsyncResult.Complete(Boolean completedSynchronously)
at ReadAsyncResult.OnAsyncReadComplete(Object state)
at SocketConnection.AsyncReadCallback(Boolean haveResult, Int32 error, Int32 bytesRead)
at IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at _IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Web Service Plug-in failed in SdkMessageProcessingStepId: {22CCBB1B-EA3E-DB11-86A7-000A3A5473E8}; EntityName: calendar; Stage: 30; MessageName: RetrieveMultiple; 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._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
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.ArgumentException: Item has already been added. Key in dictionary: '7fdf4980-237f-e111-83c6-005056b41d30' Key being added: '7fdf4980-237f-e111-83c6-005056b41d30'
at System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add)
at Microsoft.Crm.ObjectModel.CalendarService.RetrieveMultiple(EntityExpression entityExpression, ExecutionContext context)
.
UPDATE
I have already checked Calendar Entity. There is only one record with Id equals to '7fdf4980-237f-e111-83c6-005056b41d30'. Mpreover, I have searched whole database to find out if there is any other record using same Id.

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.

Sharepoint 2013 Access App - Request Not Completed - Access Denied

In a project context: SQL Server 2012, SP 2013 (build version: 15.0.4481.1005)
I added Access Apps downloaded from the SharePoint Store to a SharePoint sub-site but I keep on having this issue: "Request Not Completed - You do not have permission to view the records. To obtain permission, contact your site administrator." while trying to open them.
This is happening whatever the Access App is: I tried "Recruiting Helper" and "Orders and Products". For information, they are working correctly when I'm adding them to the SharePoint root site!
Do you have any idea where this can come from?
ResponseTimeUsageProvider: Writing log usage succeeded for Operation: ExecuteScalar. System: SQLCallFromADS. DatabaseName: ... . StartTime: 11/07/2013 11:01:51. EndTime: 11/07/2013 11:01:51. Notes: UlsCorrelationID: f942549c-a3cf-5096-f9b9-504710cde05f; CommandText: SELECT COUNT(*) FROM sys.fulltext_catalogs;
Unknown SPRequest error occurred. More information: 0x80070005
SPRequest.GetUsersDataAsSafeArray: UserPrincipalName=, AppPrincipalName=... ,bstrUrl=... ,dwUsersScope=5 ,dwUserCollectionFlags=0 ,bstrValue= ,dwValue=1073741823
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)), StackTrace:
at Microsoft.SharePoint.SPUser.InitMember()
at Microsoft.SharePoint.SPUser..ctor(SPWeb web, SPSecurableObject scope, String strIdentifier, Object[,] arrUsersData, UInt32 index, Int32 iByParamId, String strByParamSID, String strByParamEmail, SPUserCollectionType userCollectionType, SPUserCollectionFlags ucf, Boolean isSiteAuditor)
at Microsoft.SharePoint.SPUserCollection.GetByIDNoThrow(Int32 id)
at Microsoft.SharePoint.SPSite.get_SystemAccount()
at Microsoft.Office.Access.Services.Host.MossHostHelperMethods.RunAsSiteSystemAccount(SafeSPWeb web, Action`1 method)
at Microsoft.Office.Access.Services.MossHost.MossApplicationPeer.set_FullTextEnabled(Nullable`1 value)
at Microsoft.Office.Access.Services.OM.Application.get_FullTextEnabled()
at Microsoft.Office.Access.Services.Data.SqlDataProvider.GetData(Application application, CurrentUserBase user, AccessObjectSchema objectSchema, IEnumerable`1 fields, String restriction, FilterInfoEx filter, String sortExpression, IDictionary`2 queryParameters, Int32 startRow, Int32 endRow, Boolean retrieveExactRowCount, Int32& totalRowCount)
at Microsoft.Office.Access.Services.DataServer.CachedResultSet.RetrieveData(Int32 startRow, Int32 endRow)
at Microsoft.Office.Access.Services.DataServer.WebService.AccessServiceSoap.OpenResultSetInternal(CommandParameter parameter, FieldList fields, String restriction, KeyValuePair[] queryParameters, String sortExpression, FilterInfo filter, String moniker, Int32 startRowIndex, Int32 maximumRows, Boolean lockSession, Boolean autoResync, Boolean retrieveExactRowCount, DataTable& tempTable, Int32& tempTotalRowCount)
at Microsoft.Office.Access.Services.DataServer.WebService.AccessServiceSoap.c__DisplayClassbe.b__bb()
at Microsoft.Office.Access.Services.DataServer.WebService.AccessServiceSoap.ExecuteDataServerOperation(CommandParameter parameter, String protocolVersion, String moniker, AccessDataServerOperation op, WebMethodType webMethodType, PCID pcidTimeAvg, PCID pcidTimeAvgBase, Guid userCookieId, Boolean isApplicationDesignOperation, Boolean isDatabaseProviderOperation, String container)
at Microsoft.Office.Access.Services.DataServer.WebService.AccessServiceSoap.OpenResultSet(CommandParameter parameter, FieldList fields, String container, String restriction, KeyValuePair[] queryParameters, String sortExpression, FilterInfo filter, String source, Int32 startRowIndex, Int32 maximumRows, Boolean autoResync, Boolean retrieveExactRowCount, String& tableXml, Int32& totalRowCount, Guid userCookieId)
at SyncInvokeOpenResultSet(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
at System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
at System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
at System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.ServiceModel.Channels.SecurityChannelListener`1.ReceiveItemAndVerifySecurityAsyncResult`2.InnerTryReceiveCompletedCallback(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
at System.Runtime.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
at System.Runtime.InputQueue`1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
at System.ServiceModel.Channels.SingletonChannelAcceptor`3.Enqueue(QueueItemType item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.CompleteParseAndEnqueue(IAsyncResult result)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.HandleParseIncomingMessage(IAsyncResult result)
at System.Runtime.AsyncResult.SyncContinue(IAsyncResult result)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginProcessInboundRequest(ReplyChannelAcceptor replyChannelAcceptor, Action dequeuedCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1.ProcessHttpContextAsync()
at System.ServiceModel.Channels.HttpChannelListener`1.BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
at System.ServiceModel.AspNetPartialTrustHelpers.PartialTrustInvoke(ContextCallback callback, Object state)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequestWithFlow(Object state)
at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Unknown SPRequest error occurred. More information: 0x80070005
SPRequest.GetUsersDataAsSafeArray: UserPrincipalName=, AppPrincipalName= ,bstrUrl=... ,dwUsersScope=5 ,dwUserCollectionFlags=0 ,bstrValue= ,dwValue=1073741823
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)), StackTrace:
at Microsoft.SharePoint.SPUser.InitMember()
at Microsoft.SharePoint.SPUser..ctor(SPWeb web, SPSecurableObject scope, String strIdentifier, Object[,] arrUsersData, UInt32 index, Int32 iByParamId, String strByParamSID, String strByParamEmail, SPUserCollectionType userCollectionType, SPUserCollectionFlags ucf, Boolean isSiteAuditor)
at Microsoft.SharePoint.SPUserCollection.GetByIDNoThrow(Int32 id)
at Microsoft.SharePoint.SPSite.get_SystemAccount()
at Microsoft.Office.Access.Services.Host.MossHostHelperMethods.c__DisplayClass2.b__0()
at Microsoft.SharePoint.SPSecurity.c__DisplayClass5.b__3()
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
at Microsoft.Office.Access.Services.Host.MossHostHelperMethods.RunAsSiteSystemAccount(SafeSPWeb web, Action`1 method)
at Microsoft.Office.Access.Services.MossHost.MossApplicationPeer.set_FullTextEnabled(Nullable`1 value)
at Microsoft.Office.Access.Services.OM.Application.get_FullTextEnabled()
at Microsoft.Office.Access.Services.Data.SqlDataProvider.GetData(Application application, CurrentUserBase user, AccessObjectSchema objectSchema, IEnumerable`1 fields, String restriction, FilterInfoEx filter, String sortExpression, IDictionary`2 queryParameters, Int32 startRow, Int32 endRow, Boolean retrieveExactRowCount, Int32& totalRowCount)
at Microsoft.Office.Access.Services.DataServer.CachedResultSet.RetrieveData(Int32 startRow, Int32 endRow)
at Microsoft.Office.Access.Services.DataServer.WebService.AccessServiceSoap.OpenResultSetInternal(CommandParameter parameter, FieldList fields, String restriction, KeyValuePair[] queryParameters, String sortExpression, FilterInfo filter, String moniker, Int32 startRowIndex, Int32 maximumRows, Boolean lockSession, Boolean autoResync, Boolean retrieveExactRowCount, DataTable& tempTable, Int32& tempTotalRowCount)
at Microsoft.Office.Access.Services.DataServer.WebService.AccessServiceSoap.c__DisplayClassbe.b__bb()
at Microsoft.Office.Access.Services.DataServer.WebService.AccessServiceSoap.ExecuteDataServerOperation(CommandParameter parameter, String protocolVersion, String moniker, AccessDataServerOperation op, WebMethodType webMethodType, PCID pcidTimeAvg, PCID pcidTimeAvgBase, Guid userCookieId, Boolean isApplicationDesignOperation, Boolean isDatabaseProviderOperation, String container)
at Microsoft.Office.Access.Services.DataServer.WebService.AccessServiceSoap.OpenResultSet(CommandParameter parameter, FieldList fields, String container, String restriction, KeyValuePair[] queryParameters, String sortExpression, FilterInfo filter, String source, Int32 startRowIndex, Int32 maximumRows, Boolean autoResync, Boolean retrieveExactRowCount, String& tableXml, Int32& totalRowCount, Guid userCookieId)
at SyncInvokeOpenResultSet(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
at System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
at System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
at System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.ServiceModel.Channels.SecurityChannelListener`1.ReceiveItemAndVerifySecurityAsyncResult`2.InnerTryReceiveCompletedCallback(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
at System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
at System.Runtime.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
at System.Runtime.InputQueue`1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
at System.ServiceModel.Channels.SingletonChannelAcceptor`3.Enqueue(QueueItemType item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.CompleteParseAndEnqueue(IAsyncResult result)
at System.ServiceModel.Channels.HttpPipeline.EnqueueMessageAsyncResult.HandleParseIncomingMessage(IAsyncResult result)
at System.Runtime.AsyncResult.SyncContinue(IAsyncResult result)
at System.ServiceModel.Channels.HttpPipeline.EmptyHttpPipeline.BeginProcessInboundRequest(ReplyChannelAcceptor replyChannelAcceptor, Action dequeuedCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Channels.HttpChannelListener`1.HttpContextReceivedAsyncResult`1.ProcessHttpContextAsync()
at System.ServiceModel.Channels.HttpChannelListener`1.BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, Object state)
at System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
at System.ServiceModel.AspNetPartialTrustHelpers.PartialTrustInvoke(ContextCallback callback, Object state)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequestWithFlow(Object state)
at System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
SqlDataProvider.GetData: Exception thrown: {System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at Microsoft.SharePoint.SPGlobal.HandleUnauthorizedAccessException(UnauthorizedAccessException ex)
at Microsoft.SharePoint.Library.SPRequest.GetUsersDataAsSafeArray(String bstrUrl, UInt32 dwUsersScope, UInt32 dwUserCollectionFlags, String bstrValue, UInt32 dwValue, UInt32& pdwColCount, UInt32& pdwRowCount, Object& pvarDataSet)
at Microsoft.SharePoint.SPUser.InitMember()
at Microsoft.SharePoint.SPUser..ctor(SPWeb web, SPSecurableObject scope, String strIdentifier, Object[,] arrUsersData, UInt32 index, Int32 iByParamId, String strByParamSID, String strByParamEmail, SPUserCollectionType userCollectionType, SPUserCollectionFlags ucf, Boolean isSiteAuditor)
at Microsoft.SharePoint.SPUserCollection.GetByIDNoThrow(Int32 id)
at Microsoft.SharePoint.SPSite.get_SystemAccount()
at Microsoft.Office.Access.Services.Host.MossHostHelperMethods.c__DisplayClass2.b__0()
at Microsoft.SharePoint.SPSecurity.c__DisplayClass5.b__3()
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
at Microsoft.Office.Access.Services.Host.MossHostHelperMethods.RunAsSiteSystemAccount(SafeSPWeb web, Action`1 method)
at Microsoft.Office.Access.Services.MossHost.MossApplicationPeer.set_FullTextEnabled(Nullable`1 value)
at Microsoft.Office.Access.Services.OM.Application.get_FullTextEnabled()
at Microsoft.Office.Access.Services.Data.SqlDataProvider.GetData(Application application, CurrentUserBase user, AccessObjectSchema objectSchema, IEnumerable`1 fields, String restriction, FilterInfoEx filter, String sortExpression, IDictionary`2 queryParameters, Int32 startRow, Int32 endRow, Boolean retrieveExactRowCount, Int32& totalRowCount)}
ResponseTimeUsageProvider: Writing log usage succeeded for Operation: GetData:ExecuteReader. System: SQLCallFromADS. DatabaseName: .... StartTime: 11/07/2013 11:01:51. EndTime: 11/07/2013 11:01:51. Notes: UlsCorrelationID: f942549c-a3cf-5096-f9b9-504710cde05f;

Service Bus queue token issue

I am getting this error when i am giving the key for creating the queue
System.UnauthorizedAccessException was unhandled Message=The token
provider was unable to provide a security token while accessing
'https://sharan-sb.accesscontrol.windows.net/WRAPv0.9/'. Token
provider returned message: 'Error:Code:401:SubCode:T0:Detail:ACS50009:
SWT token is
invalid.:TraceID:afb424d9-d69c-4460-90d4-23ddd49ad950:TimeStamp:2013-07-23
16:08:29Z'. Source=Microsoft.ServiceBus StackTrace:
Server stack trace:
at Microsoft.ServiceBus.TokenProviderUtility.GetMessagingWebToken(ITokenProvider
tokenProvider, String appliesTo, String action, Boolean bypassCache,
TimeSpan timeout)
at Microsoft.ServiceBus.Messaging.HttpWebRequestExtensions.AddAuthorizationHeader(HttpWebRequest
request, ITokenProvider tokenProvider, String action)
at Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations.CreateAsyncResult1.<GetAsyncSteps>d__2.MoveNext()
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult1.MoveNextStep()
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult1.EnumerateSteps(CurrentThreadType
state)
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult1.Start()
Exception rethrown at [0]:
at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult
result)
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult1.End(IAsyncResult
asyncResult)
at Microsoft.ServiceBus.Messaging.ServiceBusResourceOperations.EndCreate[T](IAsyncResult
asyncResult)
at Microsoft.ServiceBus.NamespaceManager.CreateQueueAsyncResult.CreateDescription(CreateQueueAsyncResult
thisPtr, IAsyncResult r)
at Microsoft.ServiceBus.NamespaceManager.CreateQueueAsyncResult.<GetAsyncSteps>b__a(CreateQueueAsyncResult
thisPtr, IAsyncResult r)
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult1.EnumerateSteps(CurrentThreadType
state)
Exception rethrown at [1]:
at Microsoft.ServiceBus.Common.AsyncResult.End[TAsyncResult](IAsyncResult
result)
at Microsoft.ServiceBus.Messaging.IteratorAsyncResult`1.End(IAsyncResult
asyncResult)
at Microsoft.ServiceBus.NamespaceManager.OnEndCreateQueue(IAsyncResult
result)
at Microsoft.ServiceBus.NamespaceManager.EndCreateQueue(IAsyncResult
result)
at Microsoft.ServiceBus.NamespaceManager.CreateQueue(QueueDescription
description)
at BasicQueueDemo.Program.Main(String[] args) in D:\Azure\PluralSight\Azure Videos\9-Windows Azure Service
Bus\materials\demos\after\BasicQueueDemo\BasicQueueDemo\Program.cs:line
20
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() InnerException: System.IdentityModel.Tokens.SecurityTokenException
Message=The token provider was unable to provide a security token while accessing
'https://sharan-sb.accesscontrol.windows.net/WRAPv0.9/'. Token
provider returned message: 'Error:Code:401:SubCode:T0:Detail:ACS50009:
SWT token is
invalid.:TraceID:afb424d9-d69c-4460-90d4-23ddd49ad950:TimeStamp:2013-07-23
16:08:29Z'.
Source=Microsoft.ServiceBus
StackTrace:
at Microsoft.ServiceBus.TokenProviderHelper.ThrowException(Uri
requestUri, WebException exception)
at Microsoft.ServiceBus.TokenProviderHelper.GetAccessTokenCore(Uri
requestUri, String appliesTo, String requestToken, String
simpleAuthAssertionFormat, TimeSpan timeout, String& expiresIn)
at Microsoft.ServiceBus.TokenProviderHelper.GetHttpAuthAccessTokenByAssertion(Uri
requestUri, String appliesTo, String requestToken, String
simpleAuthAssertionFormat, TimeSpan timeout)
at Microsoft.ServiceBus.SharedSecretTokenProvider.OnBeginGetWebToken(String
appliesTo, String action, TimeSpan timeout, AsyncCallback callback,
Object state)
at Microsoft.ServiceBus.TokenProvider.GetWebTokenAsyncResult..ctor(TokenProvider
tokenProvider, String appliesTo, String action, Boolean bypassCache,
TimeSpan timeout, AsyncCallback callback, Object state)
at Microsoft.ServiceBus.TokenProvider.BeginGetWebToken(String appliesTo,
String action, Boolean bypassCache, TimeSpan timeout, AsyncCallback
callback, Object state)
at Microsoft.ServiceBus.TokenProviderUtility.GetMessagingWebToken(ITokenProvider
tokenProvider, String appliesTo, String action, Boolean bypassCache,
TimeSpan timeout)
InnerException: System.Net.WebException
Message=The remote server returned an error: (401) Unauthorized.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at Microsoft.ServiceBus.TokenProviderHelper.GetAccessTokenCore(Uri
requestUri, String appliesTo, String requestToken, String
simpleAuthAssertionFormat, TimeSpan timeout, String& expiresIn)
InnerException:

Authenticated WCF Data Service through Azure Service Bus

I'm stuck on this. I have a WCF Data Service that successfully creates an HTTPS endpoint in the Azure Service Bus.
I originally set the service up for testing using <security relayClientAuthenticationType="None" /> and I was able to consume the service just fine in a client.
The data going through this service will be sensitive, however, so to lock it down I switched to <security relayClientAuthenticationType="RelayAccessToken" /> in the Web.Config file of the service.
I am using the following code to obtain my token:
static string GetToken(string serviceNamespace, string issuerName, string issuerPassword)
{
if (_token == null)
{
string acsEndpoint = "https://" + serviceNamespace + "-sb.accesscontrol.windows.net/WRAPv0.9";
string relyingPartyAddress = "http://" + serviceNamespace + ".servicebus.windows.net";
NameValueCollection postData = new NameValueCollection
{
{ "wrap_scope", relyingPartyAddress },
{ "wrap_name", issuerName },
{ "wrap_password", issuerPassword },
};
WebClient webClient = new WebClient();
byte[] responseBuffer = webClient.UploadValues(acsEndpoint, "POST", postData);
string response = Encoding.UTF8.GetString(responseBuffer);
response = Uri.UnescapeDataString(response);
string[] tokenVariables = response.Split('&');
int tokenIndex = Array.FindIndex(tokenVariables, s => s.StartsWith("HMACSHA256"));
string[] tokenVariable = tokenVariables[tokenIndex].Split('=');
_token = HttpUtility.UrlDecode(tokenVariable[1]);
}
return _token;
}
static string _token = null;
And then I use context.SendingRequest += new EventHandler<SendingRequestEventArgs>(OnSendingRequest); and the following to add my token to the header of my REST request:
static void OnSendingRequest(object sender, SendingRequestEventArgs e)
{
e.RequestHeaders.Add(
"Authorization",
string.Format("WRAP access_token=\"{0}\"", GetToken("MyNamespace", "owner", "MySecret") )
);
}
And then my request takes the following form (Which worked perfectly before the security was added)
try
{
var results = (from b in context.Banks where b.Bank1 != "Bank1" select b).Take(200).ToList();
ViewBag.Results = results;
}
catch (DataServiceQueryException ex)
{
ViewBag.Message = "Authentication failed. A new token will be requested.";
var code = ex.Response.StatusCode;
if (code == 401)
_token = null;
}
While I was developing the code to get and attach the token I ran in to plenty of token errors, so I believe that I am successfully getting a token now, but now I get the following error:
500TrackingId:38940805-f9b3-4444-a8e3-2a00b2309cf6_G0, Timestamp:11/11/2012 11:48:33 AM
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.Data.Services.Client.DataServiceClientException: 500TrackingId:38940805-f9b3-4444-a8e3-2a00b2309cf6_G0, Timestamp:11/11/2012 11:48:33 AM
Source Error:
Line 31: context.SendingRequest += new EventHandler(OnSendingRequest);
Line 32:
Line 33: var results = (from b in context.Banks where b.Bank1 != "Bank1" select b).Take(200).ToList();
Line 34:
Line 35: try
Source File: c:\Users\v-tadam.REDMOND\Documents\Visual Studio 2012\Projects\CFARPOC\CFARPOCClient\Controllers\HomeController.cs Line: 33
Stack Trace:
[DataServiceClientException: 500TrackingId:38940805-f9b3-4444-a8e3-2a00b2309cf6_G0, Timestamp:11/11/2012 11:48:33 AM]
System.Data.Services.Client.QueryResult.Execute() +414618
System.Data.Services.Client.DataServiceRequest.Execute(DataServiceContext context, QueryComponents queryComponents) +131
[DataServiceQueryException: An error occurred while processing this request.]
System.Data.Services.Client.DataServiceRequest.Execute(DataServiceContext context, QueryComponents queryComponents) +432
System.Data.Services.Client.DataServiceQuery`1.Execute() +77
System.Data.Services.Client.DataServiceQuery`1.GetEnumerator() +13
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +369
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
CFARPOCClient.Controllers.HomeController.Banks() in c:\Users\v-tadam.REDMOND\Documents\Visual Studio 2012\Projects\CFARPOC\CFARPOCClient\Controllers\HomeController.cs:33
lambda_method(Closure , ControllerBase , Object[] ) +101
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.c__DisplayClass42.b__41() +28
System.Web.Mvc.Async.c__DisplayClass8`1.b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.c__DisplayClass39.b__33() +57
System.Web.Mvc.Async.c__DisplayClass4f.b__49() +223
System.Web.Mvc.Async.c__DisplayClass37.b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.c__DisplayClass2a.b__20() +24
System.Web.Mvc.Async.c__DisplayClass25.b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.c__DisplayClass1d.b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.c__DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.c__DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.c__DisplayClass8.b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.c__DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
This error is not helping me find the problem. What am I doing wrong? Consuming the service worked flawlessly before the security was implemented, and I've done all the research I can in to how to get the token and attach it to my request. Does anything jump out that I have done incorrectly?
I found my mistake. I had a fundamental misunderstanding of what constituted the token. For some reason I got it in my head that it was the text that followed "HMACSHA256" when in fact the token was everything in the response that follows "wrap_access_token=" (which seems obvious now...)
Anyway, if anyone else has this issue, the 500 error code is being thrown because the token is being correctly retrieved but the wrong token is being added to the request header. I tested this by attaching "GARBAGETOKEN" and observing the same behavior.
The following is a valid GetToken method:
static string GetToken(string serviceNamespace, string issuerName, string issuerPassword)
{
if (_token == null)
{
string acsEndpoint = "https://" + serviceNamespace + "-sb.accesscontrol.windows.net/WRAPv0.9";
string relyingPartyAddress = "http://" + serviceNamespace + ".servicebus.windows.net";
NameValueCollection postData = new NameValueCollection
{
{ "wrap_scope", relyingPartyAddress },
{ "wrap_name", issuerName },
{ "wrap_password", issuerPassword },
};
WebClient webClient = new WebClient();
byte[] responseBuffer = webClient.UploadValues(acsEndpoint, "POST", postData);
string response = Encoding.UTF8.GetString(responseBuffer);
string token = response.Split('&')
.Single(value => value.StartsWith("wrap_access_token=") )
.Split('=')[1];
_token = HttpUtility.UrlDecode(token);
}
return _token;
}
static string _token = null;
Hopefully my folly helps someone else :)

Resources