I got a security negotiation exception in a client using WCF - wcf

I got a security negotiation exception in the client part when I tried to log in to my server on another PC using the WCF client and server. It works in the local area network, but when I make the server online on the Internet using port forwarding and a static IP address I got this exception in the client.
Client configuration:
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="TcpBinding" closeTimeout="00:03:00" openTimeout="00:03:00"
receiveTimeout="00:10:00" sendTimeout="00:03:00" transactionFlow="false"
transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10"
maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="30"
maxReceivedMessageSize="65536">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:30:00"
enabled="false" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign">
<extendedProtectionPolicy policyEnforcement="Never" />
</transport>
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
<wsDualHttpBinding>
<binding name="HttpBinding" closeTimeout="00:03:00" openTimeout="00:03:00"
receiveTimeout="00:10:00" sendTimeout="00:03: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:30:00" />
<security mode="Message">
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" />
</security>
</binding>
</wsDualHttpBinding>
</bindings>
<client>
<endpoint address="net.tcp://41.205.115.225:8000/ChatRoom/service"
binding="netTcpBinding" bindingConfiguration="TcpBinding"
contract="ChatRoom" name="TcpBinding">
<identity>
<servicePrincipalName value="BalaGNisha\Balaji Nisha" />
</identity>
</endpoint>
<endpoint address="http://41.205.115.225:8001/ChatRoom/service" binding="wsDualHttpBinding"
bindingConfiguration="HttpBinding" contract="ChatRoom" name="HttpBinding">
<identity>
<servicePrincipalName value="BalaGNisha\Balaji Nisha" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
This is the exception:
System.ServiceModel.Security.SecurityNegotiationException
was unhandled by user code Message=A
remote side security requirement was
not fulfilled during authentication.
Try increasing the ProtectionLevel
and/or ImpersonationLevel.
Source=mscorlib StackTrace:
Server stack trace:
at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade(Stream stream, SecurityMessageProperty &remoteSecurity)
at System.ServiceModel.Channels.StreamSecurityUpgradeInitiatorBase.InitiateUpgrade(Stream stream)
at System.ServiceModel.Channels.ConnectionUpgradeHelper.InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, IConnection& connection, ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper& timeoutHelper)
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at System.ServiceModel.ICommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.ClientBase`1.System.ServiceModel.ICommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.ClientBase`1.Open()
at lectemplete.ChatControl.ChatWindow_Load()
in D:\Links\Imagin Cup
2011\Client\lectemplete\Client\ClientControl.cs:line
50
at lectemplete.ChatControl.Chat_Control()
in D:\Links\Imagin Cup
2011\Client\lectemplete\Client\ClientControl.cs:line
36
at BitsOfStuff.InkPadWindow.Intialize_Connection()
in D:\Links\Imagin Cup
2011\Client\lectemplete\Windows\InkPadWindow.xaml.cs:line
326
at BitsOfStuff.InkPadWindow.Window_Loaded(Object
sender, RoutedEventArgs e) in
D:\Links\Imagin Cup
2011\Client\lectemplete\Windows\InkPadWindow.xaml.cs:line
43
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
at System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
at MS.Internal.LoadedOrUnloadedOperation.DoWork()
at System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
at System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
at System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Window.Show()
at System.Windows.Window.ShowDialog()
InnerException:
System.Security.Authentication.AuthenticationException
Message=A remote side security requirement was not fulfilled during
authentication. Try increasing the
ProtectionLevel and/or
ImpersonationLevel.
Source=System
StackTrace:
at System.Net.Security.NegoState.ProcessReceivedBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartReceiveBlob(LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.CheckCompletionBeforeNextSend(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.ProcessReceivedBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartReceiveBlob(LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.StartSendBlob(Byte[] message, LazyAsyncResult lazyResult)
at System.Net.Security.NegoState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.NegotiateStream.AuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, String targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
at System.Net.Security.NegotiateStream.AuthenticateAsClient(NetworkCredential credential, String targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
at System.ServiceModel.Channels.WindowsStreamSecurityUpgradeProvider.WindowsStreamSecurityUpgradeInitiator.OnInitiateUpgrade(Stream stream, SecurityMessageProperty& remoteSecurity)
InnerException: System.ComponentModel.Win32Exception
Message=The network logon failed
ErrorCode=-2147467259
NativeErrorCode=1790
InnerException:
Is the problem in the server or client part in this exception?

So your client is accessing the service over the Internet? In such a case you cannot use Windows security. It works only on the local network / same Windows domain.

For this exception, you should make the security mode on both the server and client None:
<security mode="None">
<transport clientCredentialType="None">
</transport>
<message clientCredentialType="None" />
</security>
It worked for me, but I got another exception:
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

Related

The HTTP request is unauthorized with client authentication scheme 'Basic'. The authentication header received from the server was 'Negotiate,NTLM'

I am trying to connect to a service using the following settings.
<bindings>
<basicHttpBinding>
<binding name="EngineSoap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic" proxyCredentialType="None" realm=""/>
<message clientCredentialType="UserName" algorithmSuite="Default"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://addressToService" binding="basicHttpBinding" bindingConfiguration="EngineSoap" contract="TRIMAPI.EngineSoap" name="EngineSoap" />
</client>
The error that I get is as follows:
The HTTP request is unauthorized with client authentication scheme 'Basic'. The authentication header received from the server was 'Negotiate,NTLM'. ---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory factory)
at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(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)
I tried to change clientCredentialType="Basic" to both "Windows" and "Ntlm" but in vain. I can't set the security mode to anything other than "TransportCredentialOnly" as the service doesn't use SSL.
Also, the username is something like 'domain\username'.
What am I missing?
clientCredentialType needs to be Ntlm and not Basic
<bindings>
<basicHttpBinding>
<binding name="EngineSoap">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" proxyCredentialType="None" realm=""/>
</security>
</binding>
</basicHttpBinding>
</bindings>
If it is an HTTPS/SSL connection then change TransportCredentialOnly to Transport.
See <transport> of <basicHttpBinding> for further information.
Basic authentication on the server (IIS) which hosted the service wasn't enabled. Enabling it fixed the issue for me.

WCF call throwing a TimeoutException when client is behind Proxy

I have a WCF Service which is hosted. The service calls takes anywhere between 30 secs or more than a few minutes (but less than 10) to perform its processing as per the business requirements. I am facing a problem when the client is behind the proxy and the processing on the server side is greater than 1 min. If the processing is less than 1 min, the call succeeds without any problem. This indicates that there is no issue with the connenctivity to the server through proxy. However the issue is more with timeout at the proxy server.
I get the following exception
The request channel timed out while waiting for a reply after
00:09:59.9619962.Increase the timeout value passed to the call to
Request or increase the SendTimeout value on the Binding. The time
allotted to this operation may have been a portion of a longer
timeout.
Server stack trace: at
System.ServiceModel.Channels.RequestChannel.Request(Message message,
TimeSpan timeout) at
System.ServiceModel.Dispatcher.RequestChannelBinder.Request(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.ServiceChannelProxy.InvokeService(IMethodCallMessage
methodCall, ProxyOperationRuntime operation) at
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
message)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg) at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type) at
ConsoleApplication1.ServiceReference1.IMyService.GeneratePackage(Guid
clientId) at
ConsoleApplication1.ServiceReference1.MyClient.GeneratePackage(Guid
clientId) in
F:\Code\Samples\ConsoleApplication1\ConsoleApplication1\Service
References\ServiceReference1\Reference.cs:line 398 at
ConsoleApplication1.Program.Main(String[] args) in
F:\Code\Samples\ConsoleApplication1\ConsoleApplication1\Program.cs:line
26
My Configuration section looks like
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true"
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
</diagnostics>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IMyService" closeTimeout="00:10:00"
openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
maxBufferPoolSize="524288" maxReceivedMessageSize="20000000"
messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="200000000"
maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="None">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://TestServer.abc.co.za:8432/TestManager/MyService"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMyService"
contract="ServiceReference1.IMyService" name="WSHttpBinding_IMyService">
<identity>
<dns value="TestServer.abc.co.za" />
</identity>
</endpoint>
</client>
</system.serviceModel>
I have tried the following options:
1) Implemented a MessageInspector and set the "Keep-Alive" to "2000000".
2) Checked the request and response through Fiddler and see HTTP/1.1 504 Connection Timed Out
My understanding is that the proxy is not waiting beyond a minute even though all the timeouts are set at the WCF service level.
How do I ensure that proxy waits till the WCF service call returns?
Would appreciate if I can get inputs to solve this problem.

wcf service to upload/download large files raises exception if returned stream is null

i'm writing a wcf service to handle large files, i've followed the rules explained on msdn and found around on web. The service download method returns a stream and calls a business logic object which searches for documents into an ecm . the ecm api raises an exception when there aren't matching documents and the bl object returns a null stream.
The server side code executes without exceptions, but when the response reaches the client i got a System.ServiceModel.CommunicationException : The underlying connection was closed: The connection was closed unexpectedly .
I've searched the web and all problems related to that exception refer to excessive size of returned values , while i'm having the opposite problem. My question is there's a specific way to handle null return streams ? Is something related to the service or client configuration ? at the moment i'm returning an empty stream , but it doesn't look a smart solution .
Below i've addded sever-client configuration and the trace of the wcf service.
Server configuration:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="httpBindingConf" transferMode="StreamedResponse" messageEncoding="Text"
maxBufferSize="5000000" maxReceivedMessageSize="1073741824"
closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
<!--<security mode="Transport">
<transport clientCredentialType="None"/>
</security>-->
<readerQuotas maxBytesPerRead="4096" maxStringContentLength="65536" maxArrayLength="5000000" />
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="FileNetLoaderService.FileNetLoaderServiceBehavior" name="FileNetLoaderService.FileNetLoaderService">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="httpBindingConf"
contract="FileNetLoaderService.FileNetLoaderService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<!--<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />-->
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="FileNetLoaderService.FileNetLoaderServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<!--<serviceMetadata httpsGetEnabled="true" />-->
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
client configuration :
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_FileNetLoaderService" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="1073741824"
messageEncoding="Text" textEncoding="utf-8" transferMode="StreamedResponse"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:2436/FileNetLoaderService.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_FileNetLoaderService"
contract="localFilenetLoaderService.FileNetLoaderService"
name="BasicHttpBinding_FileNetLoaderService" />
</client>
</system.serviceModel>
trace log
<TraceData><DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/it-IT/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier>
<Description>Throwing an exception.</Description>
<AppDomain>TestForm.vshost.exe</AppDomain>
<Exception>
<ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The underlying connection was closed: The connection was closed unexpectedly.</Message>
<StackTrace>
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(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)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at TestForm.localFilenetLoaderService.FileNetLoaderService.downLoad(String guid, String CodiceAzienda, String TipoLavorazione)
at TestForm.localFilenetLoaderService.FileNetLoaderServiceClient.downLoad(String guid, String CodiceAzienda, String TipoLavorazione)
at TestForm.Form1.button1_Click(Object sender, EventArgs e)
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at TestForm.Program.Main()
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
</StackTrace>
<ExceptionString>System.ServiceModel.CommunicationException: The underlying connection was closed: The connection was closed unexpectedly. ---> System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---</ExceptionString>
<InnerException>
<ExceptionType>System.Net.WebException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The underlying connection was closed: The connection was closed unexpectedly.</Message>
<StackTrace>
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
</StackTrace>
<ExceptionString>System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</ExceptionString>
</InnerException>
</Exception>
</TraceRecord>
</DataItem>
</TraceData>
</ApplicationData>
</E2ETraceEvent>
a piece of code
server
System.IO.Stream s = myDBRead.GetDocumentStream(guid, out filename);
if (s == null)
return new MemoryStream();
return s;
client
try
{
object ss = client.downLoad("297584cf-29c2-4ad5-be37-5219ad04cb74", "5728", "Effetti");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
the answer to my question is here
just my lack of knwoledge of stream class

WCF transport security, wsHttpBinding, message security in load balancer

I have a WCF service that uses message security over HTTPS using wsHttpBinding behind load balancer. When connects to the service on web browser via https, it works. However, Windowns forms client failed, using certificate over https,
Update
The request url is https, but after the exception saying http, below is exception tracing on server side:
For example: the request url is
https://www.server.com/wcf.svc'.
But it becomes
http://www.server.com:81/wcf.svc' on the server side. Is it the load balancer causing it.
System.ServiceModel.EndpointNotFoundException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
There was no channel actively listening at 'http://www.server.com:81/wcf.svc'. This is often caused by an incorrect address URI. Ensure that the address to which the message is sent matches an address on which a service is listening.
Below is the WCF service config:
<system.serviceModel>
<diagnostics>
<messageLogging logEntireMessage="true" logMalformedMessages="true"
logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="false" />
</diagnostics>
<services>
<service behaviorConfiguration="verServiceBehaviour" name="ver.Service">
<endpoint address="ver" binding="wsHttpBinding" bindingConfiguration="wshttpbindingcfg"
contract="ver.Iver" behaviorConfiguration ="verEndpointBehaviour">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" bindingConfiguration="mexhttpbinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="https://www.server.com/" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<mexHttpBinding>
<binding name="mexhttpbinding" />
</mexHttpBinding>
<wsHttpBinding>
<binding name="wshttpbindingcfg" maxReceivedMessageSize="2000000000" sendTimeout="00:10:00">
<readerQuotas maxStringContentLength="2000000000"/>
<reliableSession ordered="true" enabled="false" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Certificate" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="verEndpointBehaviour">
<instanceContextBehavior/>
<verInspectorBehavior/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="verServiceBehaviour">
<dataContractSerializer maxItemsInObjectGraph="100000000"/>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" trustedStoreLocation="LocalMachine" mapClientCertificateToWindowsAccount="false"/>
</clientCertificate>
<serviceCertificate
x509FindType="FindByThumbprint"
findValue="xxxx"
storeLocation="LocalMachine"
storeName="My"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Below is client config:
<configuration>
<appSettings>
<add key="CertificateSubjectName" value="subjectName"/>
</appSettings>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_ver.IverHTTPS" 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"
allowCookies="false">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="TransportWithMessageCredential">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Certificate" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="false" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="https://www.server.com/wcf.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ver.IverHTTPS"
contract="ServiceReference.verIver" name="verEndPoint" />
</client>
</system.serviceModel>
</configuration>
below is code in client using certificate:
var proxyClient = new ServiceReference.VerIVerClient("verEndPoint");
proxyClient.ClientCredentials.ClientCertificate.SetCertificate(
System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
System.Security.Cryptography.X509Certificates.StoreName.My,
System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
subjectName");
proxyClient.CallService()
Below is exception received at client side:
System.ServiceModel.EndpointNotFoundException was unhandled
Message=There was no endpoint listening at https://ver20.server.com/wcf.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(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.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at verClient.ServiceReference.verIver.GetClaimver(GetClaimverClaimApplication ClaimApplication)
at verClient.ServiceReference.verIverClient.GetClaimver(GetClaimverClaimApplication ClaimApplication) in D:\Projects\ver\verClient\Service References\ServiceReference\Reference.cs:line 11330
at verClient.verForm.PostXmlTover(GetClaimverClaimApplication ClaimApplication) in D:\Projects\ver\verClient\verForm.cs:line 1408
at verClient.verForm.PostButton_Click(Object sender, EventArgs e) in D:\Projects\ver\verClient\verForm.cs:line 34
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at verClient.Program.Main() in D:\Projects\ver\verClient\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Net.WebException
Message=The remote server returned an error: (404) Not Found.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
InnerException:
Review the configuration of your load balancer, and make sure that the requests are being for warded to the correct host AND PORT number. If the port number you chose is not standard, make sure to adjust the IIS Site Binding and the base address of your service.
One important thing to understand about transport security is that it has to be configured on a "hop" by "hop" basis. In your example, you have two hops (client) -> (load balancer) and (load balancer) -> (server).
Securing your connection from the client to the load balancer doesn't automatically configure security from the load balancer to the server. You need to install and configure an ssl certificate on both the load balancer and the server.
Your initial https request ended up being an http request on the server, that is a good indication that you did not configure a secure channel between the load balancer and the server.
If you do not wish to secure the connection between the load balancer and the server, then expose your service without transport security. With this, you can still have the communication from the client to the load balancer (the first hop) on ssl.

WCF timedout waiting for System.Diagnostics.Process to finish

We have a WCF Service deployed on Windows Server 2003 that handles file transfers. When file is in Unix format, I am converting it to Dos format in the initialization stage using System.Diagnostics.Process (.WaitForExit()). Client calls the service:
obj_DataSenderService = New DataSendClient()
obj_DataSenderService.InnerChannel.OperationTimeout = New TimeSpan(0, System.Configuration.ConfigurationManager.AppSettings("DatasenderServiceOperationTimeout"), 0)
str_DataSenderGUID = obj_DataSenderService.Initialize(xe_InitDetails.GetXMLNode)
This works fine, however for large files the conversion takes more than 10 minutes and I am getting exception:
A first chance exception of type
'System.ServiceModel.CommunicationException'
occurred in mscorlib.dll
Additional information: 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:59:59.8749992'.
I tried configuring both client:
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="NetTcpBinding_IDataSend" closeTimeout="01:00:00"
openTimeout="01:00:00" receiveTimeout="01:00:00" sendTimeout="01:00: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="None">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>
</bindings>
<client>
<endpoint address="net.tcp://localhost:4000/DataSenderEndPoint"
binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IDataSend"
contract="IDataSend" name="NetTcpBinding_IDataSend">
<identity>
<servicePrincipalName value="host/localhost" />
<!--<servicePrincipalName value="host/axopwrapp01.Corp.Acxiom.net" />-->
</identity>
</endpoint>
</client>
</system.serviceModel>
And service:
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="NetTcpBinding_IDataSend" closeTimeout="01:00:00"
openTimeout="01:00:00" receiveTimeout="01:00:00" sendTimeout="01:00:00"
transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10"
maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
maxReceivedMessageSize="65536">
</binding>
</netTcpBinding>
</bindings>
</system.serviceModel>
but without luck. In the Service trace viewer I can see:
Close process timed out waiting for service dispatch to complete.
with stack trace:
System.ServiceModel.ServiceChannelManager.CloseInput(TimeSpan
timeout)
System.ServiceModel.Dispatcher.InstanceContextManager.CloseInput(TimeSpan
timeout)
System.ServiceModel.ServiceHostBase.OnClose(TimeSpan
timeout)
System.ServiceModel.Channels.CommunicationObject.Close(TimeSpan
timeout)
System.ServiceModel.Channels.CommunicationObject.Close()
DataSenderService.DataSender.OnStop()
System.ServiceProcess.ServiceBase.DeferredStop()
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server,
Int32 methodPtr, Boolean
fExecuteInContext, Object[]&
outArgs)
System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle
md, Object[] args, Object server,
Int32 methodPtr, Boolean
fExecuteInContext, Object[]&
outArgs)
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink)
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.DoAsyncCall()
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object
o)
System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object
state)
System.Threading.ExecutionContext.runTryCode(Object
userData)
System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode
code, CleanupCode backoutCode, Object
userData)
System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback
callback, Object state)
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback
callback, Object state)
System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback
tpWaitCallBack)
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object
state)
Many thanks
Bartek
Does your WCF service actually return the file contents? If so, perhaps you should use WCF's capability for streaming, and change the line endings from Unix to DOS style as you stream it, rather than processing the file and then returning it as you are currently doing. Read in each line, and then stream it out with the correct line ending.