When I am trying to export metadata I am getting error.My binding code is
HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
// the transport security binding element will be configured to require a username token
TransportSecurityBindingElement transportSecurity = new TransportSecurityBindingElement();
transportSecurity.EndpointSupportingTokenParameters.Signed.Add(new UsernameTokenParameters());
//transportSecurity.ProtectTokens = true;
// transportSecurity.ProtectTokens = true;
// transportSecurity.EndpointSupportingTokenParameters.SignedEncrypted.Add(new UsernameTokenParameters());
transportSecurity.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
transportSecurity.IncludeTimestamp = true;
//transportSecurity.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.EncryptBeforeSign;
// here you can require secure transport, in which case you'd probably replace HTTP with HTTPS as well
transportSecurity.AllowInsecureTransport = true;
//transportSecurity.IncludeTimestamp = false;
TextMessageEncodingBindingElement me = new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8);
return new CustomBinding(transportSecurity, httpTransport);
Following is the error and trace.Please help...
The service encountered an error.
An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
System.InvalidOperationException: An exception was thrown in a call to a policy export extension.
Extension: System.ServiceModel.Channels.TransportSecurityBindingElement
Error: Specified argument was out of the range of valid values.
Parameter name: parameters ----> System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: parameters
at System.ServiceModel.Security.WSSecurityPolicy.CreateTokenAssertion(MetadataExporter exporter, SecurityTokenParameters parameters, Boolean isOptional)
at System.ServiceModel.Security.WSSecurityPolicy.CreateTokenAssertion(MetadataExporter exporter, SecurityTokenParameters parameters)
at System.ServiceModel.Security.WSSecurityPolicy.CreateWsspSignedSupportingTokensAssertion(MetadataExporter exporter, Collection`1 signed, Collection`1 signedEncrypted, Collection`1 optionalSigned, Collection`1 optionalSignedEncrypted)
at System.ServiceModel.Security.WSSecurityPolicy.CreateWsspSupportingTokensAssertion(MetadataExporter exporter, Collection`1 signed, Collection`1 signedEncrypted, Collection`1 endorsing, Collection`1 signedEndorsing, Collection`1 optionalSigned, Collection`1 optionalSignedEncrypted, Collection`1 optionalEndorsing, Collection`1 optionalSignedEndorsing, AddressingVersion addressingVersion)
at System.ServiceModel.Channels.SecurityBindingElement.ExportTransportSecurityBindingElement(TransportSecurityBindingElement binding, ITransportTokenAssertionProvider transportTokenAssertionProvider, MetadataExporter exporter, PolicyConversionContext policyContext)
at System.ServiceModel.Channels.SecurityBindingElement.ExportPolicyForTransportTokenAssertionProviders(MetadataExporter exporter, PolicyConversionContext context)
at System.ServiceModel.Channels.TransportSecurityBindingElement.System.ServiceModel.Description.IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext policyContext)
at System.ServiceModel.Description.MetadataExporter.ExportPolicy(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
--- End of inner ExceptionDetail stack trace ---
at System.ServiceModel.Description.MetadataExporter.ExportPolicy(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
at System.ServiceModel.Description.WsdlExporter.ExportEndpoint(ServiceEndpoint endpoint, XmlQualifiedName wsdlServiceQName, BindingParameterCollection bindingParameters)
at System.ServiceModel.Description.WsdlExporter.ExportEndpoints(IEnumerable`1 endpoints, XmlQualifiedName wsdlServiceQName, BindingParameterCollection bindingParameters)
at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleDocumentationRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.Get(Message message)
at SyncInvokeGet(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.ProcessMessage41(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
Related
I've create a Project which Host WCF Services it is with EF 6.1 , DevArt Oracle Connector, Unit. I'm able to run this project And Ny *.svc URL is also working. Now I Tried to Use this service in my Prism 4.1 Silverlight Project This is also communicating with this wcf project.
But when I try to get data in 1 module of my App I'm getting this error:
Please guide where I'm going wrong?
Error
Microsoft.Practices.Unity.ResolutionFailedException was unhandled by user code
HResult=-2146233088
Message=Resolution of the dependency failed, type = "Abs.Web.DomainServices.UserWcfService", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Data.Entity.DbContext,System.Object]], is an interface and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was:
Resolving Abs.Web.DomainServices.UserWcfService,(none)
Resolving parameter "Uw" of constructor Abs.Web.DomainServices.UserWcfService(Abs.Data.Contracts.IAbsDataRepoositoryWorkUnit Uw)
Resolving Abs.Data.AbsDataRepoositoryWorkUnit,(none) (mapped from Abs.Data.Contracts.IAbsDataRepoositoryWorkUnit, (none))
Resolving parameter "repositoryProvider" of constructor Abs.Data.AbsDataRepoositoryWorkUnit(Abs.Data.Helpers.IRepositoryProvider repositoryProvider)
Resolving Abs.Data.Helpers.RepositoryProvider,(none) (mapped from Abs.Data.Helpers.IRepositoryProvider, (none))
Resolving parameter "repositoryFactories" of constructor Abs.Data.Helpers.RepositoryProvider(Abs.Data.Helpers.RepositoryFactories repositoryFactories)
Resolving Abs.Data.Helpers.RepositoryFactories,(none)
Resolving parameter "factories" of constructor Abs.Data.Helpers.RepositoryFactories(System.Collections.Generic.IDictionary`2[[System.Type, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Func`2[[System.Data.Entity.DbContext, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] factories)
Resolving System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Data.Entity.DbContext,System.Object]],(none)
Source=Microsoft.Practices.Unity
TypeRequested=UserWcfService
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides)
at Abs.Web.Ioc.UnityInstanceProvider.GetInstance(InstanceContext instanceContext, Message message) in d:\ProjectAbsWork\Abs.Web\Ioc\UnityInstanceProvider.cs:line 29
at System.ServiceModel.Dispatcher.InstanceBehavior.GetInstance(InstanceContext instanceContext, Message request)
at System.ServiceModel.InstanceContext.GetServiceInstance(Message message)
at System.ServiceModel.Dispatcher.InstanceBehavior.EnsureServiceInstance(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The current type, System.Collections.Generic.IDictionary`2[System.Type,System.Func`2[System.Data.Entity.DbContext,System.Object]], is an interface and cannot be constructed. Are you missing a type mapping?
Source=Microsoft.Practices.Unity
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:
This I copied from from UnityInstanceProvide : IInstanceProvider Class
followed this eg: http://jamesheppinstall.wordpress.com/2012/06/20/windows-communication-foundation-resolving-wcf-service-dependencies-with-unity/
public object GetInstance(InstanceContext instanceContext, Message message)
{
return Container.Resolve(ServiceType);
}
when I Prism Module Try to Load data from the WCF Hosted Project.
and at Prism UI project I'm getting
System.TimeoutException was unhandled by user code
Message=The HTTP request to 'http://localhost:62269/DomainServices/UserWcfService.svc' has exceeded the allotted timeout. The time allotted to this operation may have been a portion of a longer timeout.
StackTrace:
at System.ServiceModel.Channels.Remoting.RealProxy.Invoke(Object[] args)
at proxy_2.EndgetAllUser(IAsyncResult )
at Abs.Tabtest.ViewModel.TabViewModel._AlUserCallBack(IAsyncResult ar)
at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
InnerException: System.Net.WebException
Message=""
StackTrace:
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
InnerException: System.Net.WebException
Message=""
StackTrace:
at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassa.<EndGetResponse>b__9(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)
InnerException:
My Module Code is Like this : For Registering the Service In module.
this.container.RegisterType<UserWcfService>(
new ContainerControlledLifetimeManager(),
new InjectionFactory(
(c) => new ChannelFactory<UserWcfService>("CustomBinding_UserWcfService").CreateChannel()));
And in ViewModel Use :
IEventAggregator _eventAggregator;
UserWcfService _Userservice;
public TabViewModel(ITabView view, IEventAggregator eventAggregator , UserWcfService service)
: base(view)
{
_eventAggregator = eventAggregator;
_Userservice = service;
// var evt = _eventAggregator.GetEvent<UserUpdatedEvent>();
// if(evt!=null )evt.Subscribe(UserUpdatedJob);
ButtonLabelText = "Holy Cow !!";
_Userservice.BegingetAllUser(_AlUserCallBack, null);
}
public object asyncState { get; set; }
private void _AlUserCallBack(IAsyncResult ar)
{
var a=_Userservice.EndgetAllUser(ar);
_UserDetailsDataGridContext = a;
}
Don't know where I'm Going wrong.
This is the type that's messing it up for you: Abs.Data.Helpers.RepositoryFactories. It has a constructor parameter of IDictionary<Type,Func<DbContext,Object>>. You need to map this interface to an implementation in order for Unity to resolve the dependency graph.
we had a wcf service and send lots of data for calculation.the code is standardized.
wsHttpBinding is used as communication protocal, and reliable session is enbaled.
The exception is occured occasionally. I catched the trace and got the exception wcf raised, wihch has no clue with root cause.
The exception
System.ServiceModel.CommunicationObjectAbortedException: requestContext has been aborted。
The stack trace
在 System.ServiceModel.Channels.RequestContextBase.ThrowIfInvalidReply()
在 System.ServiceModel.Channels.RequestContextBase.Reply(Message message, TimeSpan timeout)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Reply(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage9(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage8(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
在 System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
在 System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
在 System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
在 System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
在 System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result)
在 System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
在 System.ServiceModel.Diagnostics.TraceUtility.<>c__DisplayClass4.<CallbackGenerator>b__2(AsyncCallback callback, IAsyncResult result)
在 System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
在 System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
在 System.Runtime.InputQueue`1.Dispatch()
在 System.ServiceModel.Channels.ReliableReplySessionChannel.ProcessSequencedMessage(RequestContext context, String action, WsrmSequencedMessageInfo info)
在 System.ServiceModel.Channels.ReliableReplySessionChannel.ProcessRequest(RequestContext context, WsrmMessageInfo info)
在 System.ServiceModel.Channels.ReliableReplySessionChannel.ProcessDemuxedRequest(RequestContext context, WsrmMessageInfo info)
在 System.ServiceModel.Channels.ReliableReplyListenerOverReply.ProcessSequencedItem(ReliableReplySessionChannel reliableChannel, RequestContext context, WsrmMessageInfo info)
在 System.ServiceModel.Channels.ReliableListenerOverDatagram`4.HandleReceiveComplete(TItem item, TInnerChannel channel)
在 System.ServiceModel.Channels.ReliableListenerOverDatagram`4.OnTryReceiveComplete(IAsyncResult result)
在 System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
在 System.ServiceModel.Diagnostics.TraceUtility.<>c__DisplayClass4.<CallbackGenerator>b__2(AsyncCallback callback, IAsyncResult result)
在 System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
在 System.Runtime.InputQueue`1.AsyncQueueReader.Set(Item item)
在 System.Runtime.InputQueue`1.EnqueueAndDispatch(Item item, Boolean canDispatchOnThisThread)
在 System.Runtime.InputQueue`1.EnqueueAndDispatch(T item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
在 System.ServiceModel.Channels.SingletonChannelAcceptor`3.Enqueue(QueueItemType item, Action dequeuedCallback, Boolean canDispatchOnThisThread)
在 System.ServiceModel.Channels.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback)
在 System.ServiceModel.Activation.HostedHttpTransportManager.HttpContextReceived(HostedHttpRequestAsyncResult result)
在 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
在 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest()
在 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.OnBeginRequest(Object state)
在 System.Runtime.IOThreadScheduler.ScheduledOverlapped.IOCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
在 System.Runtime.Fx.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
在 System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
I get this error message when trying to initialize my database connection using SimpleMembership. The first initialize statement goes through, while the second does not. The goal is to use connection strings defined in the Azure service configuration when running Azure emulator or when deployed.
Web.config:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-**********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-**********.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Azure .cscfg configuration files:
<Setting name="SqlConnectionString" value="Server=Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-********.mdf" />
SimpleMembershipInitializer:
string connectionStringName = "DefaultConnection";
string connectionString = CloudConfigurationManager.GetSetting("SqlConnectionString");
const string userTableName = "UserProfile";
const string providerName = "System.Data.SqlClient";
const string userIdColumn = "UserId";
const string userNameColumn = "UserName";
// This works fine.
// WebSecurity.InitializeDatabaseConnection(connectionStringName, userTableName, userIdColumn, userNameColumn, autoCreateTables: true);
// This throws exception.
// WebSecurity.InitializeDatabaseConnection(connectionString, providerName, userTableName, userIdColumn, userNameColumn, autoCreateTables: true);
Environment: Visual Studio 2012, EntityFramework 5.0 and MVC4 RTM with default SimpleMembership structure.
Full stacktrace:
[ArgumentException: Invalid value for key 'attachdbfilename'.]
System.Data.SqlClient.SqlConnectionString.VerifyLocalHostAndFixup(String& host, Boolean enforceLocalHost, Boolean fixup) +888986
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +5330002
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +24
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +167
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +61
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +66
WebMatrix.Data.DbProviderFactoryWrapper.CreateConnection(String connectionString) +96
WebMatrix.Data.<>c__DisplayClass15.<OpenConnectionStringInternal>b__14() +16
WebMatrix.Data.Database.get_Connection() +19
WebMatrix.Data.Database.EnsureConnectionOpen() +12
WebMatrix.Data.<QueryInternal>d__0.MoveNext() +66
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +164
WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +103
WebMatrix.WebData.DatabaseWrapper.QuerySingle(String commandText, Object[] parameters) +14
WebMatrix.WebData.SimpleMembershipProvider.CheckTableExists(IDatabase db, String tableName) +57
WebMatrix.WebData.SimpleMembershipProvider.CreateTablesIfNeeded() +49
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +73
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionString, String providerName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +63
MyProject.Filters.SimpleMembershipInitializer..ctor() in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:55
[InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588]
MyProject.Filters.SimpleMembershipInitializer..ctor() in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:59
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
System.Threading.LazyHelpers`1.ActivatorFactorySelector() +68
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +106
MyProject.Filters.InitializeSimpleMembershipAttribute.OnActionExecuting(ActionExecutingContext filterContext) in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:23
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +69
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +489
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +191
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +197
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
It seems to me you might be suffering from the lack of double-escaping (do \\v11.0 instead of \v11.0), as discussed in this post.
I'm ashamed to realize I had a typo in my connection strings. I was getting connection strings from Azure Deployment configuration files, such as:
<Setting name="SqlConnectionString" value="Server=Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-********.mdf" />
The typo was included here, at the start of the value string. It must've been a copy'n'paste bug.
This string was duplicated in Azure configuration files Local.cscfg and Cloud.cscfg, for Azure emulator and Azure deployment respectively, as well as in web.config for running locally outside emulator. The typo was only in the Local.cscfg file, which made me very confused when trying to figure out why it did not work in certain scenarios. In addition the typo was for some reason very hard for me to spot. In hindsight I don't see how I didn't figure this out sooner.
I don't have a solution yet, but here is my own investigation and theory so far:
I took a look at the source code of WebSecurity.InitializeDatabaseConnection() and think maybe I have found a bug. It doesn't seem to ever set the DatabaseConnectionInfo.Type property, which defaults to ConnectionStringName, which could explain why it doesn't like my connection string, since it would interpret it as a connection string name instead.
WebSecurity class:
public static void InitializeDatabaseConnection(string connectionString, string providerName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)
{
WebSecurity.InitializeProviders(new DatabaseConnectionInfo()
{
ConnectionString = connectionString,
ProviderName = providerName
}, userTableName, userIdColumn, userNameColumn, autoCreateTables);
}
DatabaseConnectionInfo class:
public Database Connect()
{
switch (this.Type)
{
case DatabaseConnectionInfo.ConnectionType.ConnectionStringName:
return Database.Open(this.ConnectionStringName);
case DatabaseConnectionInfo.ConnectionType.ConnectionString:
return Database.OpenConnectionString(this.ConnectionString, this.ProviderName);
default:
return (Database) null;
}
}
private enum ConnectionType
{
ConnectionStringName,
ConnectionString,
}
I am trying to get ServiceStacks Authentication to work on an MVC site. My controllers are like this:
public abstract class ControllerBase : ServiceStackController<AuthUserSession> {
//TODO: override LoginRedirectUrl
}
public class IndexController : ControllerBase {
[Authenticate]
public ActionResult Index() {
return View();
}
}
The first time I test the code by starting the site from Visual Studio, a redirect to the /login route is made.
Now if I start the site again from Visual Studio, the null reference exception shown below is thrown, and this happens on every restart until I delete all cookies in my browser.
Looks like an error?
NullReferenceException: Object reference not set to an instance of an object.]
ServiceStack.Mvc.ServiceStackController`1.get_UserSession() in C:\src\ServiceStack\src\ServiceStack.FluentValidation.Mvc3\Mvc\ServiceStackController.cs:28
ServiceStack.Mvc.ServiceStackController`1.get_AuthSession() in C:\src\ServiceStack\src\ServiceStack.FluentValidation.Mvc3\Mvc\ServiceStackController.cs:39
ServiceStack.Mvc.ExecuteServiceStackFiltersAttribute.OnActionExecuting(ActionExecutingContext filterContext) in C:\src\ServiceStack\src\ServiceStack.FluentValidation.Mvc3\Mvc\ExecuteServiceStackFiltersAttribute.cs:21
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +47
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
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
Ok never mind. The errors I experienced was probably because I had not implemented the login route yet.
I have the same problem that is listed in the following thread.
WSDL first WCF server where client does not send SOAPAction
I performed the steps that are listed in the same thread (also shown below)
1) Download the Microsoft WCF examples.
Add the following files to your project from WF_WCF_Samples\WCF\Extensibility\Interop\RouteByBody\CS\service
DispatchByBodyOperationSelector.cs
DispatchByBodyBehaviorAttribute.cs
2) Add the following attributes to your interface (next to your ServiceContract)
XmlSerializerFormat
DispatchByBodyBehavior
3) Add the following to your service interface
[OperationContract(Action = "")]
public void DoNothing()
{
}
4) For my service the WrapperName and Wrappernamespace are null for all messages. I had to go into DispatchByBodyBehaviorAttribute and edit ApplyDispatchBehavior() to add the following lines to check for this:
if (qname.IsEmpty) {
qname = new XmlQualifiedName(operationDescription.Messages[0].Body.Parts[0].Name, operationDescription.Messages[0].Body.Parts[0].Namespace);
}
Now, I am getting an error message "This message cannot support the operation because it has been read". I turned the tracing on and captured the stack trace (below). If anyone has any idea on how this can be resolved, I appreciate if you could post some comments. Thanks for any help!
at System.ServiceModel.Channels.Message.GetReaderAtBodyContents()
at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeBodyContents(Message message, Object[] parameters, Boolean isRequest)
at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(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.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(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.HttpChannelListener.HttpContextReceived(HttpRequestContext context, Action callback)
at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContextCore(IAsyncResult result)
at System.ServiceModel.Channels.SharedHttpTransportManager.OnGetContext(IAsyncResult result)
at System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.ListenerAsyncResult.WaitCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</StackTrace>
class DispatchByBodyElementOperationSelector : IDispatchOperationSelector
{
Dictionary<XmlQualifiedName, string> dispatchDictionary;
public DispatchByBodyElementOperationSelector(Dictionary<XmlQualifiedName, string> dispatchDictionary)
{
this.dispatchDictionary = dispatchDictionary;
}
#region IDispatchOperationSelector Members
private Message CreateMessageCopy(Message message, XmlDictionaryReader body)
{
//Message copy = Message.CreateMessage(message.Version, message.Headers.Action, body);
//copy.Headers.CopyHeaderFrom(message, 0);
//copy.Properties.CopyProperties(message.Properties);
//return copy;
MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);
Message copy = buffer.CreateMessage();
buffer.Close();
copy.Headers.CopyHeaderFrom(message, 0);
copy.Properties.CopyProperties(message.Properties);
return copy;
}
public string SelectOperation(ref System.ServiceModel.Channels.Message message)
{
XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents();
XmlQualifiedName lookupQName = new XmlQualifiedName(bodyReader.LocalName, bodyReader.NamespaceURI);
message = CreateMessageCopy(message,bodyReader);
if (dispatchDictionary.ContainsKey(lookupQName))
{
return dispatchDictionary[lookupQName];
}
else
{
return null;
}
}
#endregion
}
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Interface)]
sealed class DispatchByBodyBehaviorAttribute : Attribute, IContractBehavior
{
#region IContractBehavior Members
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
// no binding parameters need to be set here
return;
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
// this is a dispatch-side behavior which doesn't require
// any action on the client
return;
}
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.DispatchRuntime dispatchRuntime)
{
// We iterate over the operation descriptions in the contract and
// record the QName of the request body child element and corresponding operation name
// to the dictionary to be used for dispatch
Dictionary<XmlQualifiedName,string> dispatchDictionary = new Dictionary<XmlQualifiedName,string>();
foreach( OperationDescription operationDescription in contractDescription.Operations )
{
XmlQualifiedName qname =
new XmlQualifiedName(operationDescription.Messages[0].Body.WrapperName, operationDescription.Messages[0].Body.WrapperNamespace);
if (qname.IsEmpty)
{
qname = new XmlQualifiedName(operationDescription.Messages[0].Body.Parts[0].Name, operationDescription.Messages[0].Body.Parts[0].Namespace);
}
dispatchDictionary.Add(qname, operationDescription.Name);
}
// Lastly, we create and assign and instance of our operation selector that
// gets the dispatch dictionary we've just created.
dispatchRuntime.OperationSelector =
new DispatchByBodyElementOperationSelector(dispatchDictionary);
}
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
//
}
#endregion
}
You should use MessageBuffer.CreateMessage:
The body of a Message instance can only be consumed or written once.
If you wish to consume a Message instance more than once, you should
use the MessageBuffer class to completely store an entire Message
instance into memory.
http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.messagebuffer.aspx
Code from my current project:
public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
reply = buffer.CreateMessage();
Message m = buffer.CreateMessage();
LogMessage(m, " Response => ");
}
Add ref for Message param and return new message.
private Message CreateMessageCopy(ref Message message, XmlDictionaryReader body)
{
...
message = buffer.CreateMessage();
I had a very similar issue, using code from WCF Samples (RouteByBody to be precise) as well, and was able to solve it in a different way so I'll post it here in case it helps anybody.
Situation:
The client application (consumer) would work in Release, however, when the debugger was attached it would always fail with the error "This message cannot support the operation because it has been read".
After much tracing and logging WCF messages, the only solution that worked for me turned out to be so simple:
My Service was hosted on IIS, and with debug="true" in the <compilation> section of the web.config.
Changing it to debug="false" on the service fixed all my problems.
Dmitry Harnitski's answer does not work if you are debugging the service (It will give you a "This message cannot support the operation because it has been copied." error.)
This works even in debug mode:
XmlDictionaryReader GetReader(ref Message message)
{
MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);
message = buffer.CreateMessage();
newMessage = buffer.CreateMessage();
XmlDictionaryReader rv = buffer.CreateMessage().GetReaderAtBodyContents();
buffer.Close();
return rv;
}
static System.ServiceModel.Channels.Message newMessage = null;
static System.ServiceModel.Channels.Message lastMessage = null;
public string SelectOperation(ref System.ServiceModel.Channels.Message message)
{
try
{
if(message == lastMessage)
message = newMessage;
XmlDictionaryReader bodyReader = GetReader(ref message);
lastMessage = message;
XmlQualifiedName lookupQName = new XmlQualifiedName(bodyReader.LocalName, bodyReader.NamespaceURI);
if (dispatchDictionary.ContainsKey(lookupQName))
{
return dispatchDictionary[lookupQName];
}
else
{
return null;
}
}
catch(Exception ex)
{
throw ex;
}
}