on sending the data to the report this error is shown to me
the businesses object is 5 column of strings named ReportData
public ActionResult GetReport()
{
List ItemExpiredReportViewModelList = new List();
for (int i = 0; i < 10; i++)
{
ItemExpiredReportViewModel ItemExpiredReportViewModela = new ItemExpiredReportViewModel();
ItemExpiredReportViewModela.ItemName = "ItemName ".ToString();
ItemExpiredReportViewModela.ItemCode = "ItemCode ".ToString();
ItemExpiredReportViewModela.ItemUnit = "ItemUnit ".ToString();
ItemExpiredReportViewModela.ExpireDate = "ExpireDate".ToString();
ItemExpiredReportViewModela.Balance = "Balance ".ToString();
ItemExpiredReportViewModelList.Add(ItemExpiredReportViewModela);
}
StiReport report = new StiReport();
report.Load(Server.MapPath("~/Areas/Admin/Reports/TestStimulsoft/Report.mrt"));
report.RegBusinessObject("ReportData", ItemExpiredReportViewModelList);
report.Compile();
CheckReference(report);
return StiMvcViewer.GetReportResult(report);
}
c:\Users\user\AppData\Local\Temp\s3iq5rsq.0.cs(950,13) : error CS0126: An object of a type convertible to 'string' is requiredc:\Users\user\AppData\Local\Temp\s3iq5rsq.0.cs(955,13) : error CS0126: An object of a type convertible to 'string' is requiredc:\Users\user\AppData\Local\Temp\s3iq5rsq.0.cs(960,13) : error CS0126: An object of a type convertible to 'string' is requiredc:\Users\user\AppData\Local\Temp\s3iq5rsq.0.cs(965,13) : error CS0126: An object of a type convertible to 'string' is requiredc:\Users\user\AppData\Local\Temp\s3iq5rsq.0.cs(970,13) : error CS0126: An object of a type convertible to 'string' is required
at Stimulsoft.Report.StiReport.Compile(String path, Stream stream, StiOutputType outputType, Boolean autoCreate, Object standaloneReportType) in D:\Stimulsoft\Stimulsoft.Reports\Stimulsoft.Report\StiReport.Compile.cs:line 435
at Stimulsoft.Report.StiReport.Compile() in D:\Stimulsoft\Stimulsoft.Reports\Stimulsoft.Report\StiReport.Compile.cs:line 134
at HMS.Web.Areas.Admin.Controllers.AddTransactionController.GetReport() in D:\HMS3\HMS.Web\Areas\Admin\Controllers\AddTransactionController.cs:line 405
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__11_0()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_1.b__2()
Related
I have followed the example found here. I have a class as follows:
```
public class FileServiceRequestMappingAction : IMappingAction
{
private readonly IHttpContextAccessor _httpContextAccessor;
public FileServiceRequestMappingAction(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void Process(FileServiceRequest source, FileSearchRequest destination)
{
try
{
destination.Filter = "somevalue";
var storageType = "somestoragetype";
if (_httpContextAccessor.HttpContext.Request.Path.Value.ToLower().Contains("/patha/"))
{
storageType = "someothertypeofstorage";
}
if (!string.IsNullOrWhiteSpace(destination.Filter))
{
destination.Filter += $" and storageType eq {storageType}";
}
else
{
destination.Filter += $"storageType eq {storageType}";
}
}
catch (Exception ex)
{
throw new TranslationException($"Error in filter. {ex.Message}");
}
}
}
```
In my startup I have:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAutoMapper(typeof(FileServiceRequestMappingAction).Assembly);
When I fire up the app and execute my api query where the map is called, I get the following error:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at AutoMapper.Configuration.MappingExpression`2.<>c__60`1.<AfterMap>g__AfterFunction|60_0(TSource src, TDestination dest, ResolutionContext ctxt) in C:\projects\automapper\src\AutoMapper\Configuration\MappingExpression.cs:line 450
at lambda_method(Closure , FileServiceRequest , FileSearchRequest , ResolutionContext )
at lambda_method(Closure , Object , Object , ResolutionContext )
at AutoMapper.Mapper.AutoMapper.IMapper.Map[TDestination](Object source) in C:\projects\automapper\src\AutoMapper\Mapper.cs:line 207
The error message is:
No parameterless constructor defined for this object.
I am sure I'm doing something wrong. Note that in the startup.cs file, I have tried services.AddAutoMapper(typeof(Startup).Assembly); as well. It doesn't work either.
Any thoughts, anyone?
Thanks.
just FYI: I fixed this by switching to using a Profile instead of a direct map.
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.
I am getting the following error when trying to resolve a type:
Cannot choose between multiple constructors with equal length 1 on type 'System.String'. Select the constructor explicitly, with the UsingConstructor() configuration method, when the component is registered.
The type has 1 constructor that takes an IRepository and an ILog so I don't really know where the System.String is coming in to the picture. I'm perplexed. Does anyone have any idea what the problem is?
Here is the stack trace:
at Autofac.Core.Activators.Reflection.MostParametersConstructorSelector.SelectConstructorBinding(ConstructorParameterBinding[] constructorBindings)
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Activators.Reflection.AutowiringParameter.<>c_DisplayClass2.b_0()
at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Activators.Reflection.AutowiringParameter.<>c_DisplayClass2.b_0()
at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Execute()
at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable1 parameters)
at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable1 parameters, Object& instance)
at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable1 parameters)
at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType, IEnumerable1 parameters)
at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType)
at SomeCompany.ComponentModel.Composition.AutofacIocContainer.Resolve(Type type) in c:\SomeCompany.Core\ComponentModel\Composition\AutofacIocContainer.cs:line 17
at SomeCompany.Commands.CommandFactory.Create(String name) in c:\SomeCompany.Core\Commands\CommandFactory.cs:line 28
at SomeCompany.Web.Controllers.CommandsController.Post(String id, String request) in c:\SomeCompany.Web\Controllers\CommandsController.cs:line 49
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func1 func, CancellationToken cancellationToken)
This has nothing to do with multiple constuctors on your own code!
Autofac automatically creates objects for the constructor of your subject when you don't set them explicitly yourself.
However, when your constructor has a String parameter, it can not create a string, as String does not have a parameterless constructor! [1]
You need to set all strings on the constructor of your subject explicitly. You can also use NamedParameters and give Strings an explicit value.
Good luck!
[1] http://msdn.microsoft.com/en-us/library/system.string%28v=vs.110%29.aspx
If you have a database-definition file (.dbml), check for modifications to the code that you didn't make. In my case, the following method
public JudicialDataContext(string connectionString) : base(connectionString, mappingSource)
{
OnCreated();
}
was changed to this:
public JudicialDataContext(string connection) : base(connection, mappingSource)
{
OnCreated();
}
I have no idea why it did this, or what it is trying to accomplish by doing this, or why this change would even be necessary. But discarding the change and recompiling overcame this error.
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 :)
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}")]