I have problem with WCF service. When I am downloading 2 files everything works fine ( less than 1 minute), but when I'm trying downloading more than 3 files there is going something bad . I'm waiting and waiting and nothing :/ Every file has about 1 MB.
Dictionary<FileIdentifier, Stream> data = new Dictionary<FileIdentifier, Stream>();
foreach (string path in paths)
{
using (var client = new ServiceClient())
{
var stream = client.GetFile(path);
data[fileIdentifier] = stream;
}
}
Method at WCF Service:
public Stream GetFile(string path)
{
FileStream fs = new FileStream(stream, FileMode.Open);
fs.Close();
return fs;
}
config of WCF service:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<client />
<bindings>
<basicHttpBinding>
<binding name="basicHttpBindingConfiguration" closeTimeout="00:10:00"
openTimeout="00:15:00" receiveTimeout="00:15:00" sendTimeout="00:15:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2097152000" maxBufferPoolSize="524288000" maxReceivedMessageSize="2097152000"
messageEncoding="Text" textEncoding="utf-8" transferMode="Streamed"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="524288000"
maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="FileServer.Service" behaviorConfiguration="FileServer.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8731/Design_Time_Addresses/Server.FileServer/Service/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="" contract="FileServer.IService" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingConfiguration">
<!--
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>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="FileServer.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>
<system.web>
<compilation debug="true" />
<httpRuntime maxRequestLength="2097151" executionTimeout="1000" />
<customErrors mode="RemoteOnly" />
</system.web>
<system.webServer>
<directoryBrowse enabled="false" />
</system.webServer>
</configuration>
You should not close the stream on the service side.
Here is how you would do:
Open stream on service
Return stream to client
Read the stream on the client
Close the stream on the client
WCF will take care of closing the service stream for you
Instead of returning a stream, read the stream into a byte array and then return the byte array.
Related
I have a problem in getting transport security to work.
I have 2 services (A & B) running in the same server. service A will call service B to perform some task. Without any security, I can communicate just fine. But when I turn on transport security with the following settings:
security mode = transport
TransportClientCredentialType = Windows
ProtectionLevel = EncryptAndSign
I got error when service A calls service B:
System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:09.7810000'. ---> System.IO.IOException: The read operation failed, see inner exception. ---> System.ServiceModel.CommunicationException: The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:09.7810000'. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
I tried changing the receive and send timeout to 5 mins but I still get the same error with roughly the same timeout duration. The only difference is I need to wait out the 5 minutes instead of 1 minute.
Can anyone provide an insight to what's the cause and how to resolve this?
Attached is the configuration file for both service:
ServiceA
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<compilation targetFramework="4.5" debug="true" defaultLanguage="c#" />
</system.web>
<system.serviceModel>
<protocolMapping>
<remove scheme="net.tcp" />
<add scheme="net.tcp" binding="netTcpBinding" bindingConfiguration="ReliableTCP" />
</protocolMapping>
<client/>
<behaviors>
<serviceBehaviors>
<behavior name="mexTag">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="tryBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="mexTcp">
<tcpTransport portSharingEnabled="true" />
</binding>
</customBinding>
<netTcpBinding>
<binding name="ReliableTCP" portSharingEnabled="true" sendTimeout="00:05:00" receiveTimeout="00:05:00"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<reliableSession enabled="true" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
</security>
</binding>
</netTcpBinding>
</bindings>
<services>
<service behaviorConfiguration="mexTag" name="Test.Service.ServiceAImpl">
<endpoint address="net.tcp://app-svr:10010/ServiceA/ServiceAImpl/" behaviorConfiguration="tryBehavior"
binding="netTcpBinding" bindingConfiguration="ReliableTCP" contract="Test.Service.IServiceA" />
<endpoint address="net.tcp://app-svr:10012/ServiceA/ServiceAImpl/mex"
binding="customBinding" bindingConfiguration="mexTcp" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
ServiceB
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<compilation targetFramework="4.5" debug="true" defaultLanguage="c#" />
</system.web>
<system.serviceModel>
<client>
<endpoint address="net.tcp://app-svr:10010/ServiceA/ServiceAImpl/"
binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IServiceA"
behaviorConfiguration="tryBehavior"
contract="ServiceAReference.IServiceA" name="NetTcpBinding_IServiceA" />
</client>
<behaviors>
<serviceBehaviors>
<behavior name="MEXGET" >
<!-- Add the following element to your service behavior configuration. -->
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="tryBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="MexTcp">
<tcpTransport portSharingEnabled="true" />
</binding>
</customBinding>
<netTcpBinding>
<binding name="ReliableTCP" portSharingEnabled="true">
<reliableSession enabled="true" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
</security>
</binding>
<binding name="NetTcpBinding_IServiceA" receiveTimeout="00:05:00" sendTimeout="00:05:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<reliableSession enabled="true" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
</security>
</binding>
</netTcpBinding>
<mexTcpBinding>
<binding name="MexTcp" />
</mexTcpBinding>
</bindings>
<services>
<service name="Test.Service.ServiceBImpl" behaviorConfiguration="MEXGET" >
<endpoint address="mex"
binding="customBinding"
bindingConfiguration="MexTcp"
contract="IMetadataExchange" />
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
<endpoint
address="net.tcp://app-svr:10010/ServiceB/ServiceBImpl"
binding="netTcpBinding" behaviorConfiguration="tryBehavior"
bindingConfiguration="ReliableTCP"
contract="Test.Service.ServiceB" />
<host>
<baseAddresses>
<add baseAddress="http://app-svr:10011/ServiceB/ServiceBImpl" />
<add baseAddress="net.tcp://app-svr:10010/ServiceB/ServiceBImpl" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
There is a solution here ...you should try it...
Added these behaviors at both service and client config.
<behaviors>
<endpointBehaviors>
<behavior name="endpointBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</endpointBehaviors>
</behaviors>
Update these values to maximum size in both Client and Server config.
<binding name="tcpBinding" receiveTimeout="00:15:00" sendTimeout="00:15:00" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<security mode="None">
<transport clientCredentialType="None" protectionLevel="None" />
<message clientCredentialType="None" />
</security>
</binding>
Hope it helps.
I had that same error and it was caused by the service credentials being wrong or missing. Since you're using tcp binding first create the binding and set the security properly:
NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport)
{
CloseTimeout = TimeSpan.FromSeconds(timeoutInSeconds),
OpenTimeout = TimeSpan.FromSeconds(timeoutInSeconds),
SendTimeout = TimeSpan.FromSeconds(timeoutInSeconds),
ReceiveTimeout = TimeSpan.FromSeconds(timeoutInSeconds)
};
binding.Security.Transport.ClientCredentialType =
TcpClientCredentialType.Windows;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;
binding.MaxBufferPoolSize = int.MaxValue;
Make sure to set the username and password after creating the client:
var serviceClient = new MyServiceClient(binding, endpointYouDefine);
serviceClient.ClientCredentials.Windows.ClientCredential = new NetworkCredential("usernameInActiveDirectory", "passwordForTheADUser", "yourdomain.com");
Don't do anything else to the client after that. I've seen weird behavior like setting reader quotas programmatically after assigning the credentials, and the credentials get wiped out.
I managed to solve this problem by doing the following in the server where the net.tcp web service was hosted:
Restart NET TCP port sharing service from services.msc
Open command prompt as administrator and run the IIS Reset
I've created extension method for this.
One for NetTcpBinding and one for NetNamedPipeBinding. Only to be used on internal services of course. Timings too as when a default service is not used during the night it will fail on the first call in the morning.
public static void ActivateMaxValues(this NetTcpBinding b)
{
b.OpenTimeout = TimeSpan.FromHours(10);
b.CloseTimeout = TimeSpan.FromMinutes(10);
b.ReceiveTimeout = TimeSpan.FromHours(10);
b.SendTimeout = TimeSpan.FromHours(10);
b.MaxBufferSize = int.MaxValue;
b.MaxReceivedMessageSize = int.MaxValue;
b.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
{
MaxArrayLength = int.MaxValue,
MaxBytesPerRead = int.MaxValue,
MaxDepth = int.MaxValue,
MaxNameTableCharCount = int.MaxValue,
MaxStringContentLength = int.MaxValue
};
}
public static void ActivateMaxValues(this NetNamedPipeBinding b)
{
b.TransactionFlow = true;
b.OpenTimeout = TimeSpan.FromHours(1);
b.CloseTimeout = TimeSpan.FromMinutes(10);
b.ReceiveTimeout = TimeSpan.FromHours(1);
b.SendTimeout = TimeSpan.FromHours(1);
b.MaxBufferSize = int.MaxValue;
b.MaxReceivedMessageSize = int.MaxValue;
b.ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
{
MaxArrayLength = int.MaxValue,
MaxBytesPerRead = int.MaxValue,
MaxDepth = int.MaxValue,
MaxNameTableCharCount = int.MaxValue,
MaxStringContentLength = int.MaxValue
};
}
when I try to upload file size is more than 47Kb it will display the below error
Error : The remote server returned an unexpected response: (400) Bad Request.
wcf service is hosted in the iis 6 server
Please Help me to rectify this issue
Actual coding as mentioned below.
Regards
Wiraj
web.config codeing ........................................
<?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>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
<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" targetFramework="4.0">
</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>
-->
<!--<httpRuntime maxRequestLength="920971500" useFullyQualifiedRedirectUrl="true"
executionTimeout="914400" />-->
<httpRuntime
executionTimeout="90"
maxRequestLength="9994096"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="100"
enableVersionHeader="true"
/>
<pages controlRenderingCompatibilityVersion="4.5" clientIDMode="AutoID"/>
</system.web>
<!--
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.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ITransferService" closeTimeout="10:01:00"
openTimeout="10:01:00" receiveTimeout="10:10:00" sendTimeout="10:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest"
useDefaultWebProxy="true">
<readerQuotas maxDepth="128" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
<binding name="BasicHttpBinding_ITransferService1" closeTimeout="10:01:00"
openTimeout="10:01:00" receiveTimeout="10:10:00" sendTimeout="10:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="StreamedRequest"
useDefaultWebProxy="true">
<readerQuotas maxDepth="128" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://midoc-server-bk.milnetfinity.com/test1/wcfservice.TransferService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITransferService"
contract="wcfservice.ITransferService" name="BasicHttpBinding_ITransferService" />
<endpoint address="http://midoc-server-bk.milnetfinity.com/test1/wcfservice.TransferService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITransferService1"
contract="ITransferService.ITransferService" name="BasicHttpBinding_ITransferService1" />
</client>
<protocolMapping>
<add binding="basicHttpBinding" scheme="http" bindingConfiguration="BasicHttpBinding_ITransferService"/>
</protocolMapping>
</system.serviceModel>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
</configuration>
app.config codes -----------------------------------------------------
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
<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>
<!--<netTcpBinding>
<binding name="netTcpBinding_ITransferService" maxReceivedMessageSize="10485760" transferMode="Streamed" messageEncoding="Mtom"/>
</netTcpBinding>-->
<basicHttpBinding>
<!--<binding name="BasicHttpBinding_ITransferService" maxReceivedMessageSize="910485760" sendTimeout="04:10:00" messageEncoding="Mtom" transferMode="StreamedRequest" />-->
<binding name="BasicHttpBinding_ITransferService" closeTimeout="10:01:00"
openTimeout="10:01:00" receiveTimeout="10:10:00" sendTimeout="10:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Mtom" textEncoding="utf-8" transferMode="StreamedRequest"
useDefaultWebProxy="true">
<readerQuotas maxDepth="128" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<!--<client >
</client >-->
<services>
<!--<service name="wcfservice.Service1">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732/Design_Time_Addresses/wcfservice/Service1/" />
</baseAddresses>
</host>
--><!-- Service Endpoints --><!--
--><!-- Unless fully qualified, address is relative to base address supplied above --><!--
<endpoint address="" binding="basicHttpBinding" contract="wcfservice.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>
--><!-- Metadata Endpoints --><!--
--><!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. --><!--
--><!-- This endpoint does not use a secure binding and should be secured or removed before deployment --><!--
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>-->
<service name="wcfservice.TransferService">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732/Design_Time_Addresses/wcfservice/TransferService/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="" binding="basicHttpBinding" contract="wcfservice.ITransferService" >
<!--
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>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<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>
</system.serviceModel>
</configuration>
Transfer service.cs codes ----------------------------------------'
public messageout UploadFile(RemoteFileInfo request)
{
messageout strerror = new messageout() ;
strerror.message = "OK";
try
{
strerror.message = "OK1";
FileStream targetStream = null;
Stream sourceStream = request.FileByteStream;
string uploadFolder = #"c:\Uploadfiles\";
string filePath = Path.Combine(uploadFolder, request.FileName);
using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
//read from the input stream in 6K chunks
//and save to output stream
strerror.message = "OK2";
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
strerror.message = "OK3";
}
targetStream.Close();
sourceStream.Close();
}
strerror.message = "OK4";
}
catch (Exception ex)
{
strerror.message = ex.ToString();
}
return strerror;
}
}
}
ITransferservice.cs --------------------------
[ServiceContract]
public interface ITransferService
{
[OperationContract]
RemoteFileInfo DownloadFile(DownloadRequest request);
[OperationContract]
messageout UploadFile(RemoteFileInfo request);
}
[MessageContract]
public class DownloadRequest
{
[MessageBodyMember]
public string FileName;
}
[MessageContract]
public class RemoteFileInfo : IDisposable
{
[MessageHeader(MustUnderstand = true)]
public string FileName;
[MessageHeader(MustUnderstand = true)]
public long Length;
[MessageBodyMember(Order = 1)]
public System.IO.Stream FileByteStream;
public void Dispose()
{
if (FileByteStream != null)
{
FileByteStream.Close();
FileByteStream = null;
}
}
}
[MessageContract]
public class messageout : IDisposable
{
[MessageHeader(MustUnderstand = true)]
public string message;
public void Dispose()
{
message = "";
}
}
I have a duplex WCF, it work perfect in local host (connect my application to this WCF when it run locally).
Now I tried to hosted it in my IIS (Server 2008 R2 standard), I create a windows account "GOD", and an application poll in IIS using the "GOD" identity.
I can access this WCF from my pc (other than the server) from web browser and see the XML of the contract, (click on the link inside the page displayed)
When try to access from my application I get the exception:
Client is unable to finish the security negotiation within the
configured timeout (00:00:00). The current negotiation leg is 1
(00:00:00).
Again when the WCF run locally my app work OK.
I tried to use the trace but all I successful to see is the exception about the time out.
My app.config is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing" propagateActivity="true">
<listeners>
<add name="traceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c:\log\Traces.svclog"/>
</listeners>
</source>
</sources>
</system.diagnostics>
<system.serviceModel>
<bindings>
<wsDualHttpBinding>
<binding name="WSDualHttpBinding_I_BridgeWCFService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
<readerQuotas maxDepth="256" maxStringContentLength="2147483646"
maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646" />
<reliableSession ordered="true" inactivityTimeout="01:10:00" />
<security mode="Message" />
</binding>
</wsDualHttpBinding>
</bindings>
<client>
<endpoint address="http://win-jj/_Bridge1/_BridgeWcfService.svc"
binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_I_BridgeWCFService"
contract="_BridgeWcfServiceReference.I_BridgeWCFService"
name="WSDualHttpBinding_I_BridgeWCFService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</client>
</system.serviceModel>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/>
</startup>
</configuration>
I also tried to change the identity section above to: <userPrincipalName value="GOD" />, but then I got another exception.
My service config file: web.config:
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<bindings>
<wsDualHttpBinding>
<binding name="WSDualHttpBinding_I_BridgeWCFService" closeTimeout="01:01:00" openTimeout="01:01:00" receiveTimeout="01:10:00" sendTimeout="01:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483646" maxReceivedMessageSize="2147483646" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true">
<readerQuotas maxDepth="256" maxStringContentLength="2147483646" maxArrayLength="2147483646" maxBytesPerRead="2147483646" maxNameTableCharCount="2147483646"/>
<reliableSession ordered="true" inactivityTimeout="01:10:00"/>
<security mode="Message">
<message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default"/>
</security>
</binding>
</wsDualHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="_BridgeNameSpace.Service1Behavior" name="_BridgeNameSpace._BridgeWCFService">
<endpoint address="" binding="wsDualHttpBinding" bindingConfiguration="WSDualHttpBinding_I_BridgeWCFService" contract="_BridgeNameSpace.I_BridgeWCFService">
<identity>
<userPrincipalName value="GOD" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="_BridgeNameSpace.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
<!-- 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>
</system.serviceModel>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
I also tried to change the identity section above to: <dns value="localhost"/>, but nothing change
I connect to my service in my application as following:
MyServiceClientProxy Proxy = null;
MyCallbackProxy myCallbackProxy = null;
myCallbackProxy = new MyCallbackProxy();
InstanceContext cntx = new InstanceContext(myCallbackProxy);
Proxy = new MyServiceClientProxy(cntx, "WSDualHttpBinding_I_BridgeWCFService");
Proxy.ClientCredentials.Windows.ClientCredential.UserName = "GOD";
Proxy.ClientCredentials.Windows.ClientCredential.Password = "yy";
try
{
Proxy.Open();
}
catch { return; }
BTW, when tried to change the security to '' got the following exception (wither or not use the ClientCredential.Username&Password as the code above):
The open operation did not complete within the allotted timeout of 00:00:59.1689524. The time allotted to this operation may have been a portion of a longer timeout.
ANY IDEA ?, PLS help!
wsDualHttpBinding tries to open a connection from server to client which will be blocked by firewalls
My advice would be to switch to netTcpBinding - its much simpler for duplex messaging as I blogged here
These scenarios work in their pieces. Its when i put it all together that it breaks.
I have a WCF service using netTCP that uses impersonation to get the callers ID (role based security will be used at this level)
on top of this is a WCF service using basicHTTP with TransportCredientialOnly which also uses impersonation
I then have a client front end that connects to the basicHttp.
the aim of the game is to return the clients username from the netTCP service at the bottom - so ultimatley i can use role based security here.
each service is on a different machine - and each service works when you remove any calls they make to other services when you run a client for them both locally and remotley. IE the problem only manifests when you jump accross more than one machine boundary.
IE the setup breaks when i connect each part together - but they work fine on their own.
I also specify
[OperationBehavior(Impersonation = ImpersonationOption.Required)] in the method and
have IIS setup to only allow windows authentication (actually i have ananymous enabled still, but disabling makes no difference)
This impersonation works fine in the scenario where i have a netTCP Service on Machine A with a client with a basicHttp service on machine B with a clinet for the basicHttp service also on machine B ... however if i move that client to any machine C i get the following error:
The exception is 'The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:10:00''
the inner message is 'An existing connection was forcibly closed by the remote host'
Am beginning to think this is more a network issue than config ... but then im grasping at straws ...
the config files are as follows (heading from the client down to the netTCP layer)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="basicHttpBindingEndpoint" closeTimeout="00:02:00"
openTimeout="00:02:00" receiveTimeout="00:10:00" sendTimeout="00:02:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://panrelease01/WCFTopWindowsTest/Service1.svc"
binding="basicHttpBinding" bindingConfiguration="basicHttpBindingEndpoint"
contract="ServiceReference1.IService1" name="basicHttpBindingEndpoint"
behaviorConfiguration="ImpersonationBehaviour" />
</client>
<behaviors>
<endpointBehaviors>
<behavior name="ImpersonationBehaviour">
<clientCredentials>
<windows allowedImpersonationLevel="Impersonation"/>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
the service for the client (basicHttp service and the client for the netTCP service)
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="netTcpBindingEndpoint" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10" maxBufferPoolSize="524288"
maxBufferSize="65536" maxConnections="10" maxReceivedMessageSize="65536">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
<basicHttpBinding>
<binding name="basicHttpWindows">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"></transport>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="net.tcp://5d2x23j.panint.com/netTCPwindows/Service1.svc"
binding="netTcpBinding"
bindingConfiguration="netTcpBindingEndpoint"
contract="ServiceReference1.IService1"
name="netTcpBindingEndpoint"
behaviorConfiguration="ImpersonationBehaviour">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</client>
<behaviors>
<endpointBehaviors>
<behavior name="ImpersonationBehaviour">
<clientCredentials>
<windows allowedImpersonationLevel="Impersonation" allowNtlm="true"/>
</clientCredentials>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WCFTopWindowsTest.basicHttpWindowsBehaviour">
<!-- 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>
<services>
<service name="WCFTopWindowsTest.Service1"
behaviorConfiguration="WCFTopWindowsTest.basicHttpWindowsBehaviour">
<endpoint address=""
binding="basicHttpBinding"
bindingConfiguration="basicHttpWindows"
name ="basicHttpBindingEndpoint"
contract ="WCFTopWindowsTest.IService1">
</endpoint>
</service>
</services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
then finally the service for the netTCP layer
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<authentication mode="Windows"></authentication>
<authorization>
<allow roles="*"/>
</authorization>
<compilation debug="true" targetFramework="4.0" />
<identity impersonate="true" />
</system.web>
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="netTCPwindows">
<security mode="Transport">
<transport clientCredentialType="Windows"></transport>
</security>
</binding>
</netTcpBinding>
</bindings>
<services>
<service behaviorConfiguration="netTCPwindows.netTCPwindowsBehaviour" name="netTCPwindows.Service1">
<endpoint address="" bindingConfiguration="netTCPwindows" binding="netTcpBinding" name="netTcpBindingEndpoint" contract="netTCPwindows.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mextcp" binding="mexTcpBinding" contract="IMetadataExchange"/>
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:8721/test2" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="netTCPwindows.netTCPwindowsBehaviour">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="false" />
<!-- 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>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
If you need to make a more than one hop, you're going to need to enable delegation for that occur. You can get more information on that here.
That being said, if all you need to do is determine the role of a user that calls the backend service (netTcp), you don't necessarily need impersonation as the TokenImpersonationLevel of the WindowsIdentity should only need to be Information in order to determine role membership. In this case, you would only need to ensure impersonation was taking place in the middle-tier (basicHttp).
I have a WCF service hosted in IIS7 with netTCP enabled.
This is my web.config in %apppath%\ , where the SVC file is.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="Search.Querier.WCF.Querier" behaviorConfiguration="SearcherServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8050/SearcherService"/>
</baseAddresses>
</host>
<endpoint address="net.tcp://localhost:9000/SearcherService"
binding="netTcpBinding"
bindingConfiguration="Binding1"
contract="Search.Querier.WCF.IQuerier" />
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="Binding1"
hostNameComparisonMode="StrongWildcard"
sendTimeout="00:10:00"
maxReceivedMessageSize="65536"
transferMode="Buffered"
portSharingEnabled="false">
<security mode="None">
<transport clientCredentialType="None" />
<message clientCredentialType="None" />
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="SearcherServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl=""/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.web>
<compilation debug="true" />
</system.web>
</configuration>
For some reason, instead of loading on port 8050 as I specified, I see the blue and beige site showing the site at:
http://localhost/SearcherService/searcherservice.svc
and not
http://localhost:8050/SearcherService/searcherservice.svc
Additionally, when I try to run
svcutil.exe http://process.mycomp.com/SearcherService/SearcherService.svc?wsdl
as the page rendered on the URL says, I get an error:
Metadata contains a reference that cannot be resolved: 'http://process.mycomp.com/SearcherService/SearcherService.svc?wsdl'
But I have that specified nowhere else in my web.config
Is there anywhere else it could be?
You are missing a MEX endpoint, have a look at this link:
http://bloggingabout.net/blogs/dennis/archive/2006/11/09/WCF-Part-4-3A00-Make-your-service-visible-through-metadata.aspx