Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

WCF InvalidOperationException in service

Posted on 2011-05-09
4
Medium Priority
?
2,073 Views
Last Modified: 2012-05-11
Hi,

My WCF service is throwing exception as follows:

This operation would deadlock because the reply cannot be received until the current Message completes processing. If you want to allow out-of-order message processing, specify ConcurrencyMode of Reentrant or Multiple on CallbackBehaviorAttribute.

Service Code is as follows :

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class CalculatorService : IWebMxAccessServerService
    {
public int Register(string tag)
        {
            int tagHandle = 0;
            try
            {
                tagHandle = wmxServer.Advise(param1,param2);
                return tagHandle;
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("WCF Service", ex.Message + Environment.NewLine + ex.StackTrace);
                throw;
            }
        }
}

Open in new window



[ServiceContract(Namespace = "", SessionMode = SessionMode.Required,
    CallbackContract = typeof(IWebMxAccessServerServiceCallback))]
    public interface IWebMxAccessServerService
    {
[OperationContract]
int Register(string tag);
}

Open in new window



 
public interface IWebMxAccessServerServiceCallback
    {

        [OperationContract(IsOneWay = true)]
        void ReceiveMxData(TagUpdatedEventArgs tagDetails);

    }

Open in new window



WCF Consumer UI class

Implementing CallBack on client side
[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
    public class WebMxAccess : IWebMxAccessServerServiceCallback
    {
       
}

I am getting above mentioned error when i am calling Register operation contract of service.

Any help would be appreciated.
0
Comment
Question by:SanjaySutar
  • 2
  • 2
4 Comments
 
LVL 18

Expert Comment

by:DarrenD
ID: 35727075
Hi,

On the Service add ConcurrencyMode=ConcurrencyMode.Reentrant to the attributes.

Hope this helps,

Darren

0
 

Author Comment

by:SanjaySutar
ID: 35727908
Hi Darren, I have added the attribute, but now started getting different error.

Please find below the stack trace :

Message: The message could not be transferred within the allotted timeout of 00:01:00. There was no space available in the reliable channel's transfer window. The time allotted to this operation may have been a portion of a longer timeout.
Source: mscorlib
Stack Trace: 
Server stack trace: 
   at System.ServiceModel.Channels.TransmissionStrategy.WaitQueueAdder.Wait(TimeSpan timeout)
   at System.ServiceModel.Channels.TransmissionStrategy.InternalAdd(Message message, Boolean isLast, TimeSpan timeout, Object state, MessageAttemptInfo& attemptInfo)
   at System.ServiceModel.Channels.ReliableOutputConnection.InternalAddMessage(Message message, TimeSpan timeout, Object state, Boolean isLast)
   at System.ServiceModel.Channels.ReliableDuplexSessionChannel.OnSend(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.DuplexChannel.Send(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.DuplexChannelBinder.Send(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Open in new window

0
 
LVL 18

Accepted Solution

by:
DarrenD earned 2000 total points
ID: 35736046
Hi,

I have a small test app that I will put up. It's a simple variation of the Subscribe/Unsubscribe example seen here
http://www.codeproject.com/KB/cs/WCF_Client_Callbacks.aspx
and
http://idunno.org/archive/2008/05/29/wcf-callbacks-a-beginners-guide.aspx



 
//Console Client Application:
using System;
using System.ServiceModel;
using C_Sharp_WCF_Call_Back_Console.ServiceReference1;

namespace C_Sharp_WCF_Call_Back_Console
{
    class Program
    {
        static void Main(string[] args)
        {
            Sender mySender = new Sender();
            mySender.Open();
            Console.Read();
        }

        public class Sender
        {

            private Service1Client messageClient;

            public void Open()
            {
                try
                {
                    InstanceContext context = new InstanceContext(new Listner());

                    messageClient = new Service1Client(context);
                    messageClient.AddMessage("Hmmmmmmmmmm");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }

        public class Listner : IService1Callback, IDisposable
        {
            void IDisposable.Dispose()
            {
             
            }

            void IService1Callback.OnMessageAdded(string message, DateTime timestamp)
            {
                Console.WriteLine(message + " " + timestamp.ToString());
            }
        }
    }
}

//IService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace C_Sharp_WCF_Call_Back
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
    [ServiceContract(SessionMode=SessionMode.Required, CallbackContract = typeof(IMessageCallBack))]
    public interface IService1
    {

        [OperationContract]
        void AddMessage(string value);
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    public interface IMessageCallBack
    {
        [OperationContract(IsOneWay = true)]
        void OnMessageAdded(string message, DateTime timestamp);
    }
}


//Service Implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace C_Sharp_WCF_Call_Back
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class Service1 : IService1
    {
        public void AddMessage(string value)
        {
            try
            {

                IMessageCallBack callback = OperationContext.Current.GetCallbackChannel<IMessageCallBack>();
                callback.OnMessageAdded("ahhhhhhhhhhhhhhhhhhhhh", DateTime.Now);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}

Open in new window



App.Config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.serviceModel>
    <bindings>
      <wsDualHttpBinding>
        <binding clientBaseAddress="http://localhost:3942/" name="WSDualHttpBinding_IService1" closeTimeout="00:01:00" openTimeout="00:01:00"
                 receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false"
                 hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
                 textEncoding="utf-8" useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00" />
          <security mode="Message">
            <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" />
          </security>
        </binding>
      </wsDualHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:3941/Service1.svc" binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_IService1" contract="ServiceReference1.IService1" name="WSDualHttpBinding_IService1">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>

Web.Config:

<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
      <configSections>
            <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                  <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
                              <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
                              <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                              <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                              <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
                        </sectionGroup>
                  </sectionGroup>
            </sectionGroup>
      </configSections>
      <appSettings/>
      <connectionStrings/>
      <system.web>
            <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.
        -->
            <compilation debug="true">
                  <assemblies>
                        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
                        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                  </assemblies>
            </compilation>
            <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
            <authentication mode="Windows"/>
            <!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
            <pages>
                  <controls>
                        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                  </controls>
            </pages>
            <httpHandlers>
                  <remove verb="*" path="*.asmx"/>
                  <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                  <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                  <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
            </httpHandlers>
            <httpModules>
                  <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            </httpModules>
      </system.web>
      <system.codedom>
            <compilers>
                  <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
                        <providerOption name="CompilerVersion" value="v3.5"/>
                        <providerOption name="WarnAsError" value="false"/>
                  </compiler>
            </compilers>
      </system.codedom>
      <system.web.extensions>
            <scripting>
                  <webServices>
                        <!--
              Uncomment this section to enable the authentication service. Include
              requireSSL="true" if appropriate.

          <authenticationService enabled="true" requireSSL = "true|false"/>
          -->
                        <!--
              Uncomment these lines to enable the profile service, and to choose the
              profile properties that can be retrieved and modified in ASP.NET AJAX
              applications.

          <profileService enabled="true"
                          readAccessProperties="propertyname1,propertyname2"
                          writeAccessProperties="propertyname1,propertyname2" />
          -->
                        <!--
              Uncomment this section to enable the role service.

          <roleService enabled="true"/>
          -->
                  </webServices>
                  <!--
        <scriptResourceHandler enableCompression="true" enableCaching="true" />
        -->
            </scripting>
      </system.web.extensions>
      <!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
      <system.webServer>
            <validation validateIntegratedModeConfiguration="false"/>
            <modules>
                  <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            </modules>
            <handlers>
                  <remove name="WebServiceHandlerFactory-Integrated"/>
                  <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                  <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
                  <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            </handlers>
      </system.webServer>
      <system.serviceModel>
            <services>
                  <service name="C_Sharp_WCF_Call_Back.Service1" behaviorConfiguration="C_Sharp_WCF_Call_Back.Service1Behavior">
                        <!-- Service Endpoints -->
                        <endpoint address="" binding="wsDualHttpBinding" contract="C_Sharp_WCF_Call_Back.IService1">
                              <!--
              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
          -->
                              <identity>
                                    <dns value="localhost"/>
                              </identity>
                        </endpoint>
                        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
                  </service>
            </services>
            <behaviors>
                  <serviceBehaviors>
                        <behavior name="C_Sharp_WCF_Call_Back.Service1Behavior">
                              <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                              <serviceMetadata httpGetEnabled="true"/>
                              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                              <serviceDebug includeExceptionDetailInFaults="true"/>
                        </behavior>
                  </serviceBehaviors>
            </behaviors>
      </system.serviceModel>
</configuration>


You will have to add the service reference to the console application and the ports will change so make sure you change them correctly.



Hope this helps,

Darren
0
 

Author Comment

by:SanjaySutar
ID: 35743784
Hi Darren, thanks for the example.

I have fixed the problem of Timout.

Along with the attribute mentioned by you earlier, I have added UseSynchronizationContext = false and it started working.


[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, UseSynchronizationContext = false)]

Open in new window



Thanks again.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial will show you how to add an attribute to an XML (http://en.wikipedia.org/wiki/XML) stream returned from a Windows Communication Foundation (http://en.wikipedia.org/wiki/Windows_Communication_Foundation) (WCF) Web Service.  Some knowled…
While working on Silverlight and WCF application, I faced one issue where fault exception occurred at WCF operation contract is not getting propagated to Silverlight client. So after searching net I came to know that it was behavior by default for s…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Loops Section Overview
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question