simultaneous calls handling in WCF - wcf

I'm new to .net and knows very little about WCF, so bear with me if any silly questions asked. I'm wondering how WCF handles simultaneous calls in SELF-HOST scenario if my code doesn't explicitly spawn any thread. So after read a lot on the stackoverflow, I created a test app but it seems not working. Please advise. Thanks a lot.
Please note ...
My question is only about WCF SELF HOSTING, so please don't refer to any IIS related.
I'm using webHttpBinding.
I understand there are maxConnection and service throttling settings, but I'm only interested in 2 simultaneous calls in my research setup. So there should be no max conn or thread pool concern.
My test service is NOT using session.
Code as below ...
namespace myApp
{
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
public interface ITestService
{
[OperationContract]
[WebGet(UriTemplate="test?id={id}")]
string Test(int id);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
ConcurrencyMode = ConcurrencyMode.Multiple)]
public class TestService : ITestService
{
private static ManualResetEvent done = new ManualResetEvent(false);
public string Test(int id)
{
if (id == 1)
{
done.Reset();
done.WaitOne();
}
else
{
done.Set();
}
}
}
}
app.config ...
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name = "TestEndpointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name = "myApp.TestService">
<endpoint address = "" behaviorConfiguration="TestEndpointBehavior"
binding = "webHttpBinding"
contract = "myApp.ITestService">
</endpoint>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/test/"/>
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
<system.web>
<sessionState mode = "Off" />
</system.web>
How I tested ...
Once had the application running, I opened my browser, FF in case, made one call to http://localhost:8080/test/test?id=1 . This request put the app to suspend waiting for signal, i.e. WaitOne. Then made another call in another browser tab to http://localhost:8080/test/test?id=2. What's expected is that this request will set the signal and thus the server will return for both requests.
But I saw the app hang and the Test function never got entered for the 2nd request. So apparently my code doesn't support simultaneous/concurrent calls. Anything wrong?

You can use single class to setup your wcf service and discard interface. You need to add global.asax file also. After you make the second call, all of them will return "finished".
This configuration does what you want.
Create TestService.cs with :
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,
ConcurrencyMode = ConcurrencyMode.Multiple)]
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
public class TestService
{
private static ManualResetEvent done = new ManualResetEvent(false);
[OperationContract]
[WebGet(UriTemplate = "test?id={id}")]
public string Test(int id)
{
if (id == 1)
{
done.Reset();
done.WaitOne();
}
else
{
done.Set();
}
return "finished";
}
}
web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="false" > </standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- 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="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
Global.asax file:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.Add(new ServiceRoute("testservice", new WebServiceHostFactory(), typeof(TestService)));
}
}

Related

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.?

trying to build a RestFull service with wcf running in the WcfTestClient.exe. The problem is that I get an error:
Failed to add a service. Service metadata may not be accessible.
I added a mex endpoint in the config file but does not solve it:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="MyRest.Service" behaviorConfiguration="ServBehave">
<!--Endpoint for REST-->
<endpoint
address="XMLService"
binding="webHttpBinding"
behaviorConfiguration="restPoxBehavior"
contract="MyRest.IService"/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServBehave" >
<!-- 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="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<!--Behavior for the REST endpoint for Help enability-->
<behavior name="restPoxBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
IService1.cs
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "/Employees", ResponseFormat = WebMessageFormat.Xml)]
Employee[] GetEmployees();
}
[DataContract]
public class Employee
{
[DataMember]
public int EmpNo { get; set; }
[DataMember]
public string EmpName { get; set; }
[DataMember]
public string DeptName { get; set; }
}
Service1.cs
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service1 : IService1
{
public Employee[] GetEmployees()
{
return new Employee[]
{
new Employee() {EmpNo=101,EmpName="Mahesh",DeptName="CTD"},
new Employee() {EmpNo=102,EmpName="Akash",DeptName="HRD"}
};
}
}
With WCF Restful service, do you actually need meta-data to expose service or to work on it? The answer is "NO". It's against the principles of Rest. Meta-data represents the interface(the operations), and for REST interface is fixed(http methods). WcfTestClient is for testing SOAP based Service(as they have to expose their interface through mex bindings).
Testing a RESTFUL service for http get could be vary easy. you just have to invoke it from your browser, using the URL. To test other http methods, you have to build your custom client.
If this seems a big task, then you could also use tools like Fiddler to build request data. An example could be seen here

WCF rest service: unable to call methods

Please tell me I'm doing something stupid in setting up my wcf rest service.
I've create a web application and added a wcf service to it.
Here is my web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="WebApplication1.Service1">
<endpoint address="../Service1" behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WebApplication1.IService1"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
And my service interface:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebGet(UriTemplate = "data/{value}", ResponseFormat = WebMessageFormat.Json)]
Person GetData(string value);
}
And my service code:
public class Service1 : IService1
{
public Person GetData(string value)
{
return new Person()
{
Id = Convert.ToInt32(value),
Name = "John Doe"
};
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
I have no problems browsing to the service
http://localhost/RoleProviderSite/Service1.svc
but as soon as I add the data/10
http://localhost/RoleProviderSite/Service1.svc/data/10
"There was no channel actively listening at 'http://mymachinename/RoleProviderSite/Service1.svc/data/10"
I would have thought that adding the "[WebGet(UriTemplate = "data/{value}", ResponseFormat = WebMessageFormat.Json)]" would mean that this url would be accessible, but maybe I'm missing something?
I'm using :
Internet Information Services, Version: 5.1
and XP OS
Thanks very much for any help.
remove the address in the endpoint and your URI should work as expected. You cannot use relative addressing like that for your endpoint

Have a single connection with netTcpBinding between client and WCF service

I came across a page on MSDN explaining transaction in WCF Services here. I tweaked the binding settings and used netTcpBinding. Here is the serviceModel section of my app.config file:
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="netTcpBindingConfiguration1" transactionFlow="true">
<security mode="Message" />
</binding>
</netTcpBinding>
</bindings>
<services>
<service name="OrderingService.OrderService">
<clear />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"
listenUriMode="Explicit">
</endpoint>
<endpoint address="net.tcp://localhost:8880/OrderingService"
binding="netTcpBinding" bindingConfiguration="netTcpBindingConfiguration1"
contract="OrderingService.IOrderService" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8888/OrderingService/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
I created a windows application as the client of the service. I used netstat command to see the TCP connections between the client and the service (hosted in a console application). I realized for each operation (which was a button click in my client app that places a new order by invoking the methods of the service's proxy class), a new connection is created and all previous connections still remain ESTABLISHED. Obviously, this is not an ideal condition. I wondered what I did wrong and what setting or configuration would work out this problem by reducing the number of connections to only one. By the way, the service class that implements the service interface has InstanceContextMode set to PerSession. Here are the contract interface and the service class:
[ServiceContract(SessionMode=SessionMode.Required)]
public interface IOrderService
{
[OperationContract]
[TransactionFlow(TransactionFlowOption.NotAllowed)]
List<Customer> GetCustomers();
[OperationContract]
[TransactionFlow(TransactionFlowOption.NotAllowed)]
List<Product> GetProducts();
[OperationContract]
[TransactionFlow(TransactionFlowOption.Mandatory)]
string PlaceOrder(Order order);
[OperationContract]
[TransactionFlow(TransactionFlowOption.Mandatory)]
string AdjustInventory(int productId, int quantity);
[OperationContract]
[TransactionFlow(TransactionFlowOption.Mandatory)]
string AdjustBalance(int customerId, decimal amount);
}
[ServiceBehavior(TransactionIsolationLevel = IsolationLevel.Serializable,
TransactionTimeout = "00:00:20",
InstanceContextMode = InstanceContextMode.PerSession,
TransactionAutoCompleteOnSessionClose = true)]
public class OrderService : IOrderService
{...}
Here is the code the uses the proxy class in the client app:
using (TransactionScope scope = new TransactionScope())
{
try
{
proxy = new OrderServiceClient("NetTcpBinding_IOrderService");
result = proxy.PlaceOrder(order);
MessageBox.Show(result);
result = proxy.AdjustInventory(product.ProductId, quantity);
MessageBox.Show(result);
result = proxy.AdjustBalance(customer.CustomerId, product.Price * quantity);
MessageBox.Show(result);
proxy.Close();
scope.Complete();
}
catch (Exception exc)
{
MessageBox.Show("Error occurred: " + exc.Message);
}
}
With regards to the TCP connection remaining ESTABLISHED - are you calling .Close() on your instance of the client when you are finished with it?
If you want to use a single connection you should change the instance context mode to 'Single' and reuse the connection you establish in the client to process all your service calls. This suits an architecture where you want to maintain state within your service.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class Service : IService
{
}
I found this link very helpful when I was learning about context modes in WCF: CodeProject link
As you are currently using PerSession context mode you should be able to limit it to a single connection by adding a setting for maxConcurrentSessions in your behaviors section. You can do it like this:
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
<serviceThrottling maxConcurrentSessions="1" />
</behavior>
</serviceBehaviors>
This would only be a good idea if you have a single client.

aspNetCompatibilityEnabled="true"

I have made a Azure web app that has a ASP.NET web that also contains some JSON WCF services. I really don't know enough about WCF service models to be sure that I'm doing it right, does this look correct to you? Are there other service model configurations that is better for scalability, more maximum concurrent connections, etc?
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.net>
<settings>
<!-- See http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 -->
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
This works but I occasionally get unexpected connection drops (timeouts) with no HTTP error codes in my development environment which worries me.
Update # 24. Nov. 2011
web.config
<system.net>
<connectionManagement>
<!-- See http://social.msdn.microsoft.com/Forums/en-US/windowsazuredata/thread/d84ba34b-b0e0-4961-a167-bbe7618beb83 -->
<add address="*" maxconnection="48" />
</connectionManagement>
</system.net>
I'm suspecting that it may be the Visual Studio web server that causes the Ajax calls to get timeouts, after some minutes the service starts to accept requests again. Here is my complete setup, can you see what the problem is? I only have a single Ajax call to the service.
Inferface
IExample.cs:
using System.ServiceModel;
using System.ServiceModel.Web;
namespace WebPages.Interfaces
{
[ServiceContract]
public interface IExample
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json)]
string GetSomething(string id);
}
}
ExampleService.svc.cs markup
<%# ServiceHost Language="C#" Debug="true" Service="WebPages.Interfaces.ExampleService" CodeBehind="ExampleService.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
ExampleService.svc.cs codebehind
namespace WebPages.Interfaces
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ExampleService : IExample
{
string JsonSerializeSomething(Something something)
{
var serializer = new DataContractJsonSerializer(something.GetType());
var memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, something);
return Encoding.Default.GetString(memoryStream.ToArray());
}
public string GetSomething(string id)
{
var something = DoSomeBusinessLogic(id);
return JsonSerializeSomething(something);
}
}
}
jQuery call from client
function _callServiceInterface(id, delegate) {
var restApiCall = "Interfaces/ExampleService.svc/GetSomething?id="
+ escape(id);
$.getJSON(restApiCall, delegate);
}
function _getSomethingFromService() {
_callServiceInterface('123',
function (result) {
var parsedResult = $.parseJSON(result);
$('#info').html(result.SomethingReturnedFromServiceCall);
}
);
}
Update
I think I know what the problem is now; it seems that WCF services are single threaed by default ( source: http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.SERVICEMODEL.SERVICEBEHAVIORATTRIBUTE.CONCURRENCYMODE);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true ) . That explain why my Ajax calls get timeouts, its blocked by another thread. This code should work a lot better:
ExampleService.svc.cs
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerSession,
IncludeExceptionDetailInFaults = false, MaxItemsInObjectGraph = Int32.MaxValue)]
//[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ExampleService : IExample
web.config
<system.serviceModel>
<protocolMapping>
<add scheme="http" binding="webHttpBinding" bindingConfiguration="" />
</protocolMapping>
<behaviors>
<endpointBehaviors>
<behavior name="">
<webHttp defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
ExampleService.svc
<%# ServiceHost Language="C#" Debug="true" Service="WebPages.Interfaces.TagService" CodeBehind="TagService.svc.cs" %>
Update # 9. Oct. 2011
I think I got the answer I needed here Locking with ConcurrencyMode.Multiple and InstanceContextMode.PerCall
aspNetCompatibilityEnabled="false" means not being able to access HttpContext, ASP.NET Sessions, etc. in my WCF code.
I think I got the answer I needed here Locking with ConcurrencyMode.Multiple and InstanceContextMode.PerCall
aspNetCompatibilityEnabled="false" means not being able to access HttpContext, ASP.NET Sessions, etc. in my WCF code.

WCF callback not being executed

I've been Googling this for a day now and can't seem to find the answer. Hoping someone can shed some light on this. I'm trying to implement a simple WCF client-server callback, with console apps at both the client and server sides. The operation executes on the server and everything seems to work fine except that the callback doesn't execute on the client. I.e. it never writes "Callback called!!!", and a breakpoint placed in the callback never trips. The client simply writes "Done." and waits for user input.
I'm sure it's something simple. Any help would be greatly appreciated. Thanks!
//SERVER CODE:
namespace NodeServiceLib
{
public interface ISomeCallbackContract
{
[OperationContract]
void OnCallback();
}
[ServiceContract(CallbackContract = typeof(ISomeCallbackContract))]
public interface IMyContract
{
[OperationContract]
void DoSomething();
}
public class NodeService : IMyContract
{
public void DoSomething()
{
Console.WriteLine("I'm doing something!!!");
}
}
}
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<bindings/>
<services>
<service name="NodeServiceLib.NodeService" behaviorConfiguration="MEX">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/Node" />
<add baseAddress="net.tcp://localhost:8001/Node" />
</baseAddresses>
</host>
<endpoint
address="MyContract"
binding="netTcpBinding"
contract="NodeServiceLib.IMyContract"
/>
<endpoint
address="MEX"
binding="mexHttpBinding"
contract="IMetadataExchange"
/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MEXGET">
<!-- 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="False"/>
</behavior>
<behavior name="MEX">
<serviceMetadata/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup</configuration>
//CLIENT CODE:
namespace TestConsole
{
[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
class Callback : NodeServices.IMyContractCallback
{
public void OnCallback()
{
Console.WriteLine("Callback called!!!");
}
}
class Program
{
static void Main(string[] args)
{
System.Threading.Thread.Sleep(5000); // Give server time to spin up
Console.WriteLine("=== CLIENT ===");
InstanceContext context = new InstanceContext(new Callback());
NodeServices.MyContractClient proxy = new NodeServices.MyContractClient(context);
proxy.DoSomething();
Console.WriteLine("Done.");
Console.ReadLine();
}
}
}
Shouldn't you be calling the callback method in the server's DoSomething method?