I am trying to call a WCF from my C# desktop app but i get an error. This is my code:
//Client Code
System.ServiceModel.EndpointAddress addressSync = new System.ServiceModel.EndpointAddress("net.tcp://an ip address/Sync2.svc");
Shared.FactorySync = new System.ServiceModel.ChannelFactory<LiteEdition.wsSyncFastest.ISync2Channel>("NetTcpBinding_ISync2", addressSync);
Shared.UpLoadSync = Shared.FactorySync.CreateChannel();
[QUESTION. If I dynamically create a client call to a WCF can I assume i do NOT need to include anything in th app.config file about the bindings?]
//error message on this line:
Shared.UpLoadSync.UploadMotionDynamic2(new byte[1]{0}, 0, 0);
//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:00:59.9349963'
.
//My Service:
public void UploadMotionDynamic2(byte[] jpegData, int status, int framePart)
{
DAL dal = new DAL();
try
{
if (jpegData != null)
{
LiveView2.SetNewFrame(status, framePart, jpegData);
}
}
catch (Exception ex)
{
email.SendError("Sync.UploadMotionDynamic:" + ex.ToString(), "");
}
}
//In my Web.Config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="NetTCPBehaviour">
<serviceTimeouts transactionTimeout="0.00:00:30" />
<serviceDebug includeExceptionDetailInFaults="false" />
<dataContractSerializer maxItemsInObjectGraph="65536" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="testme" behaviorConfiguration="NetTCPBehaviour">
<endpoint address="Sync2.svc" binding="netTcpBinding" contract="ISync" name="wsMotionUploader" bindingConfiguration="NetTCPBindingEndPoint">
<!--<security mode="None"></security>-->
</endpoint>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="NetTCPBindingEndPoint" receiveTimeout="00:15:00" sendTimeout="00:15:00" transferMode="Streamed" closeTimeout="00:02:00" openTimeout="00:02:00"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647">
<readerQuotas maxArrayLength="32768" />
<security mode="None">
<transport clientCredentialType="None" protectionLevel="None" />
<message clientCredentialType="None" />
</security>
</binding>
</netTcpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Amended Code:
System.ServiceModel.NetTcpBinding binding = new System.ServiceModel.NetTcpBinding();
System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress("http:ip/Sync2");
System.ServiceModel.ChannelFactory<System.ServiceModel.Channels.IRequestChannel> factory =
new System.ServiceModel.ChannelFactory<System.ServiceModel.Channels.IRequestChannel>(binding, address);
var channel = factory.CreateChannel();
channel.Open();
UPDATED TO THIS:
System.ServiceModel.NetTcpBinding binding = new System.ServiceModel.NetTcpBinding();
System.ServiceModel.EndpointAddress address = new System.ServiceModel.EndpointAddress("net.tcp://ip/Sync2");
System.ServiceModel.ChannelFactory<WindowsFormsApplication2.ws.ISync2Channel> factory =
new System.ServiceModel.ChannelFactory<WindowsFormsApplication2.ws.ISync2Channel>(binding, address);
factory.Endpoint.Contract.SessionMode = System.ServiceModel.SessionMode.Allowed;
WindowsFormsApplication2.ws.ISync2Channel channel = factory.CreateChannel();
channel.Open();
But get this error 'Object reference not set to an instance of an object.'
on the .Open() method.
Also, the 'WindowsFormsApplication2.ws.ISync2Channel' is defined because I had already added a reference to the Service. If I had not what would I have
used instead?
///******************new settings:
Client code:
ws.Sync2Client wcf = new ws.Sync2Client("NetTcpBinding_ISync2");
wcf.UploadMotionDynamic2(new byte[1]{1},0,0);
Client App.Config:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ISync2" />
</basicHttpBinding>
<netTcpBinding>
<binding name="NetTcpBinding_ISync2" />
</netTcpBinding>
</bindings>
<client>
<endpoint address="http://ip/Sync2.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ISync2"
contract="ws.ISync2" name="BasicHttpBinding_ISync2" />
<endpoint address="net.tcp://ip/Sync2.svc" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_ISync2" contract="ws.ISync2"
name="NetTcpBinding_ISync2">
<identity>
<servicePrincipalName value="host/ip" />
</identity>
</endpoint>
</client>
</system.serviceModel>
Server Web.Config
-->
The error I get is on this line:
wcf.UploadMotionDynamic2(new byte[1]{1},0,0);
The error is:
Object reference not set to an instance of an object.
the stack is:
Server stack trace:
at System.ServiceModel.Channels.SocketConnectionInitiator.Connect(Uri uri, TimeSpan timeout)
at System.ServiceModel.Channels.BufferedConnectionInitiator.Connect(Uri uri, TimeSpan timeout)
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)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(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)
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 WindowsFormsApplication2.ws.ISync2.UploadMotionDynamic2(Byte[] jpegData, Int32 status, Int32 framePart)
at WindowsFormsApplication2.ws.Sync2Client.UploadMotionDynamic2(Byte[] jpegData, Int32 status, Int32 framePart) in m:\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Service References\ws\Reference.cs:line 81
at WindowsFormsApplication2.Form1.button1_Click(Object sender, EventArgs e) in m:\Visual Studio 2013\Projects\WindowsFormsApplication2\WindowsFormsApplication2\Form1.cs:line 581
This all works when I use http binding though...
The port 780 is open on my server.
the Net.Tcp.Listener Adaptor is running
Enabled Protocols in IIS has net.tcp
Still no joy
It looks like your using the wrong constructor for your requirements.
When using the ChannelFactory(String, EndpointAddress) constructor, the first parameter stands for the name of your endpoint configuration (in your config file).
Using the ChannelFactory(Binding, EndpointAddress) constructor will fulfill your requirement of passing the configuration programmatically.
Use this constructor when you want to pass the binding and address information programmatically rather than using an application configuration file.
You can use the ChannelFactory class to call the wcf service, in this case you dont need to have endpoints and bindings in configuration file. Everything(endpoints, behaviors) you can create in the c# something like below code
var channelFactory = new ChannelFactory<IService>(new BasicHttpBinding(), "http://myurl:8080/ServiceFirst");
IService client = channelFactory.CreateChannel();
check out this link
http://msdn.microsoft.com/en-us/library/ms734681(v=vs.110).aspx
Related
I've tried to execute a method of a web service on my console application (c# .Net 4.5.2), but I've received the following error: "(415) Cannot process the message because the content type 'application/xml; charset=utf-8' was not the expected type 'text/xml; charset=utf-8'.."
app.config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="AnotherBindingWS"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647" />
</webHttpBinding>
<basicHttpBinding>
<binding name="BasicHttpBinding_IIntegracion"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"/>
</basicHttpBinding>
</bindings>
<client>
<endpoint
name="BasicHttpBinding_IIntegracion"
address="http://servicios.cruzdelsur.com/Interfaces_Test/Integracion.svc"
binding="webHttpBinding"
bindingConfiguration="AnotherBindingWS"
contract="WSIntegracionCDS.IIntegracion"
behaviorConfiguration="webhttp"/>
</client>
<services>
<service name="WSIntegracionCDS.IIntegracion">
<endpoint
name="AnotherBindingServiceWS"
address="http://servicios.cruzdelsur.com/Interfaces_Test/Integracion.svc"
binding="webHttpBinding"
bindingConfiguration="AnotherBindingWS"
contract="WSIntegracionCDS.IIntegracion"
behaviorConfiguration="webhttp"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webhttp">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
Program.cs
IntegracionClient clientWS = new IntegracionClient();
CrearDespachos_Input inputDespachosWS = new CrearDespachos_Input();
List<Despacho> newDespachos = new List<Despacho>();
foreach (var cbte in comprobantesCDS)
{
Despacho itemDespacho = GetNewDespacho(cbte);
newDespachos.Add(itemDespacho);
}
inputDespachosWS.Despachos = newDespachos.ToArray();
//On the following line I receive the exception
CrearDespachos_Output output = clientWS.CrearDespachos(inputDespachosWS);
I attached the exception on execution CrearDespachos method Exception on runtime
ex.StackTrace
Server stack trace:
en System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
en System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
en System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
en System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
en System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
en System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
en System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
en System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
en System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
en ESAIntegracionesService.WSIntegracionCDS.IIntegracion.CrearDespachos(CrearDespachos_Input Input)
en ESAIntegracionesService.WSIntegracionCDS.IntegracionClient.CrearDespachos(CrearDespachos_Input Input) en C:\dev\esa-web\ESAIntegracionesService\Service References\WSIntegracionCDS\Reference.cs:línea 2691
en ESAIntegracionesService.Program.ActualizarComprobantes(String token) en C:\dev\esa-web\ESAIntegracionesService\Program.cs:línea 121
¿Could you help me?
Thanks a lot!
I'm trying to setup a WCF service with certificate-based authentication, following this guide: https://msdn.microsoft.com/en-au/library/ff648360.aspx?f=255&MSPPError=-2147217396
I've followed all the steps (I think), which in summary are:
1) Generated a self-signed CA certificate and installed it as a machine-level trusted CA:
2) Generated a certificate for the service (signed by the CA certificate, CN=QvxServiceCert) and installed it at machine-level:
3) configured the WCF service endpoint behavior to use the certificate. My service configuration looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<bindings>
<wsHttpBinding>
<binding name="wsHttpEndpointBinding">
<security>
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="QvxServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<serviceCertificate findValue="CN=QvxServiceCert" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="esqQvxScheduler.Service.QvxSchedulerAPI" behaviorConfiguration="QvxServiceBehavior">
<endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpEndpointBinding"
name="wsHttpEndpoint" bindingName="" contract="esqQvxScheduler.Service.IQvxSchedulerAPI" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/QvxSchedulerAPI/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
</configuration>
4) Generated a certificate for the client (again, signed by the CA certificate, this one has CN=QvxClientCert) and installed at user-level:
5) configured the WCF client behavior to use it for authentication. This is my client config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="qvxClientBehavior">
<clientCredentials>
<clientCertificate findValue="CN=QvxClientCert" />
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="wsHttpEndpoint">
<security>
<message clientCredentialType="Certificate" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8733/QvxSchedulerAPI/" binding="wsHttpBinding" behaviorConfiguration="qvxClientBehavior"
bindingConfiguration="wsHttpEndpoint" contract="QvxSchedulerAPI.IQvxSchedulerAPI"
name="wsHttpEndpoint">
<identity>
<certificate encodedValue="[A LONG AUTOGENERATED STRING THE MEANING OF WHICH I HAVE NO IDEA]" />
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
6) Gave the user that runs the client access to the certificate, by issuing the following on the command line: cacls "C:\Users\MyUsername\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-742627442-1779984360-2302642487-1000" /E /G "MyUser-PC\MyUsername":R
This was all done following the guide, without any issue that I could see. Everything seems ok... but when I try to invoke the service from my client, all I get this frustratingly vague and unhelpful exception:
Unhandled Exception: System.ServiceModel.Security.SecurityNegotiationException: The caller was not authenticated by the service. ---> System.ServiceModel.FaultException: The request for security token could not be satisfied because authentication failed.
at System.ServiceModel.Security.SecurityUtils.ThrowIfNegotiationFault(Message message, EndpointAddress target)
at System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingMessageBody(Message incomingMessage, SspiNegotiationTokenProviderState sspiState)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(TimeSpan timeout)
at System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan timeout)
at System.ServiceModel.Security.TlsnegoTokenProvider.OnOpen(TimeSpan timeout)
at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Security.CommunicationObjectSecurityTokenProvider.Open(TimeSpan timeout)
at System.ServiceModel.Security.SymmetricSecurityProtocol.OnOpen(TimeSpan timeout)
at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.ClientSecurityChannel`1.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation operation, EndpointAddress target, Uri via, SecurityToken currentToken, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan timeout)
at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecuritySessionChannel.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)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
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)
Well, after a lot of trial and error, turns out that you either have to have a CRL installed for your CA or you have to specify explicitly that you don't want a revocation check, by adding this to your behavior's ClientCredentials tag:
<serviceCertificate>
<authentication revocationMode="NoCheck"/>
</serviceCertificate>
and vice-versa for the service side:
<clientCertificate>
<authentication certificateValidationMode="ChainTrust" revocationMode="NoCheck"/>
</clientCertificate>
Also, you need to remove the autogenerated certificate tag in the client and replace it with an instruction to look up the certificate:
<identity>
<certificateReference findValue="CN=QvxServiceCert" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
</identity>
I've created wcf service and everything works correctly but when i try to return Type[] (i got it from Assembly.GetTypes()) i have following exception:
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 ---
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.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.IWcfAssembly.GetAssemblyTypes(String a)
at ConsoleApplication1.ServiceReference1.WcfAssemblyClient.GetAssemblyTypes(String a) in D:\Projekty\ConsoleApplication1\ConsoleApplication1\Service References\ServiceReference1\Reference.cs:line 50
at ConsoleApplication1.Program.Main(String[] args) in D:\Projekty\ConsoleApplication1\ConsoleApplication1\Program.cs:line 17
I thought it might be maxItemsInObjectGraph property or maxArrayLenght (and similar) but it didn't help. Still got the same exception. Maybe I did something wrong with the property declaration?
this is my client config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IWcfAssembly" 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="2147483647" maxReceivedMessageSize="2147483647"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="128" maxStringContentLength="2147483647" maxArrayLength="2147483647"
maxBytesPerRead="4096" maxNameTableCharCount="2147483647" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:57040/WcfAssembly.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IWcfAssembly" contract="ServiceReference1.IWcfAssembly"
name="BasicHttpBinding_IWcfAssembly" />
</client>
</system.serviceModel>
</configuration>
and this is my service config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IWcfAssembly" receiveTimeout="00:10:00" sendTimeout="00:10:00" openTimeout="00:10:00" closeTimeout="00:10:00"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647"
maxBufferPoolSize="52428899">
<readerQuotas maxDepth="128"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="4096"
maxNameTableCharCount="2147483647" />
<security mode="None"/>
</binding>
</basicHttpBinding>
</bindings>
<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 multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I have also added [ServiceBehavior(MaxItemsInObjectGraph = int.MaxValue)] as a class attribute. I had it in my service config before but this is one of tries.
Do you have any ideas guys? Why the array returned from Assembly.GetTypes() causes such error? (big array of int[] works OK)
The problem is that the System.RunTimeType is not serialize (which is in the internal implementation of Type)
using this mock:
void Main()
{
var dto = new MyDto();
dto.Tada = new Type[] { this.GetType() };
DataContractSerializer ser =
new DataContractSerializer(typeof(MyDto));
var ms = new MemoryStream();
ser.WriteObject(ms, dto);
ms.Dump();
dto.Dump();
}
public class MyDto
{
public Type[] Tada { get; set; }
}
Throws:
SerializationException: Type 'System.RuntimeType' with data contract
name 'RuntimeType:http://schemas.datacontract.org/2004/07/System' is
not expected. Consider using a DataContractResolver or add any types
not known statically to the list of known types - for example, by
using the KnownTypeAttribute attribute or by adding them to the list
of known types passed to DataContractSerializer.
Which makes sense because RunTimeType is internal (Type itself is abstract). You have to come up with your own serialized type that can convey the info you want.
My service's app.config
<system.serviceModel>
<client>
<endpoint name="DataLocal" address="net.tcp://SomeAddress" binding="netTcpBinding" contract="ISomeContract" bindingConfiguration="TcpCustomSecurity" behaviorConfiguration="SecureBehaviorName">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</client>
<services>
<service name="SomeService">
<host>
<baseAddresses>
<add baseAddress="http://SomeService" />
<add baseAddress="net.tcp://SomeService" />
</baseAddresses>
</host>
<endpoint name="SomeService_Normal" address="Secure" binding="netTcpBinding" contract="ISomeService" bindingConfiguration="TcpNormal"/>
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="TcpNormal" transferMode="Buffered" receiveTimeout="24.20:31:23.6470000">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
<security mode="None" />
</binding>
<binding name="TcpCustomSecurity" transferMode="Buffered" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="24.20:31:23.6470000" sendTimeout="00:01:00" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
<security mode="Message">
<message clientCredentialType="UserName"/>
</security>
</binding>
</netTcpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="SecureBehaviorName">
<clientCredentials>
<serviceCertificate>
<authentication certificateValidationMode="None"/>
</serviceCertificate>
</clientCredentials>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</endpointBehaviors>
</behaviors>
Following are the stack statements for the error i am getting..
> System.dll!System.Net.Sockets.Socket.Send(byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socketFlags) + 0x5a bytes
System.ServiceModel.dll!System.ServiceModel.Channels.SocketConnection.Write(byte[] buffer, int offset, int size, bool immediate, System.TimeSpan timeout) + 0xa7 bytes
System.ServiceModel.dll!System.ServiceModel.Channels.SocketConnection.Write(byte[] buffer, int offset, int size, bool immediate, System.TimeSpan timeout, System.ServiceModel.Channels.BufferManager bufferManager) + 0x34 bytes
System.ServiceModel.dll!System.ServiceModel.Channels.BufferedConnection.WriteNow(byte[] buffer, int offset, int size, System.TimeSpan timeout, System.ServiceModel.Channels.BufferManager bufferManager) + 0x90 bytes
System.ServiceModel.dll!System.ServiceModel.Channels.BufferedConnection.Write(byte[] buffer, int offset, int size, bool immediate, System.TimeSpan timeout, System.ServiceModel.Channels.BufferManager bufferManager) + 0x47 bytes
System.ServiceModel.dll!System.ServiceModel.Channels.FramingDuplexSessionChannel.OnSend(System.ServiceModel.Channels.Message message, System.TimeSpan timeout) + 0x115 bytes
System.ServiceModel.dll!System.ServiceModel.Channels.OutputChannel.Send(System.ServiceModel.Channels.Message message, System.TimeSpan timeout) + 0x81 bytes
System.ServiceModel.dll!System.ServiceModel.Dispatcher.DuplexChannelBinder.Request(System.ServiceModel.Channels.Message message, System.TimeSpan timeout) + 0x154 bytes
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannel.Call(string action, bool oneway, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation, object[] ins, object[] outs, System.TimeSpan timeout) + 0x206 bytes
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(System.Runtime.Remoting.Messaging.IMethodCallMessage methodCall, System.ServiceModel.Dispatcher.ProxyOperationRuntime operation) + 0x59 bytes
System.ServiceModel.dll!System.ServiceModel.Channels.ServiceChannelProxy.Invoke(System.Runtime.Remoting.Messaging.IMessage message) + 0x65 bytes
mscorlib.dll!System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(ref System.Runtime.Remoting.Proxies.MessageData msgData, int type) + 0xee bytes
// First the service call in the above stack...
Service Behavior is this:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
The error occured after few hours of constant testing...unable to reproduce it while debugging..
EDIT:
I've got the tracing results thanks to Dejan...
on the first occurance of error i get this message: Maximum number of pending connections has been reached.
on the second occurance i get this message : The system hit the limit set for throttle 'MaxConcurrentConnections'.Limit for this throttle was set to 200.Throttle value can be changed by modifying attribute 'maxConcurrentSessions' in service throttle element.
So for the second message i did this:
and assigned this service behavior to the service. do i need to set the maxConnections on the binding for the first message.Moreover, which is the root cause for the problem , first one or second one or both. Because in the subsequent messages i always get the second message.
Please guide to update my app.config to avoid such scenario.
UPDATE
I've got the tracing results...
on the first occurance i get this message: Maximum number of pending connections has been reached.
on the second occurance i get this message : The system hit the limit set for throttle 'MaxConcurrentConnections'.Limit for this throttle was set to 200.Throttle value can be changed by modifying attribute 'maxConcurrentSessions' in service throttle element.
So for the second message i did this:
<serviceBehaviors>
<behavior name="tcpNormalBehavior">
<serviceThrottling maxConcurrentSessions="800" maxConcurrentInstances="800" maxConcurrentCalls="200" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
</serviceBehaviors>
and assigned this service behavior to the service.
do i need to set the maxConnections on the binding for the first message.Moreover, which is the root cause for the problem , first one or second one or both. Because in the subsequent messages i always get the second message.
Please guide.
There is a possibilty that you have an unhandled exception such as stack overflow somewhere in your WCF service. If I get it correctly, the service works but stops working after a few hours.
The first step to debugging a WCF service is WCF Tracing. Enable it, try to test your service and after it stops working again, there should be a trace entry in the .svclog file.
EDIT
Regarding your updated question: You get that exception because you are not closing the connection from the client side after you're done with the call. Try refactoring your code so calls to WCF look like this:
WCFProxy clientProxy = null;
try
{
clientProxy = new WCFProxy();
clientProxy.SomeCall();
clientProxy.Close();
}
catch (Exception)
{
if (clientProxy != null)
{
clientProxy.Abort();
}
throw;
}
and then see if it will cause problems.
i am getting the following error when i try access my webservice from the client application which is a windows based app
System.ServiceModel.Security.SecurityNegotiationException:
Secure channel cannot be opened
because security negotiation with the
remote endpoint has failed. This may
be due to absent or incorrectly
specified EndpointIdentity in the
EndpointAddress used to create the
channel. Please verify the
EndpointIdentity specified or implied
by the EndpointAddress correctly
identifies the remote endpoint. --->
System.ServiceModel.FaultException:
The request for security token has
invalid or malformed elements. at
System.ServiceModel.Security.SecurityUtils.ThrowIfNegotiationFault(Message
message, EndpointAddress target) at
System.ServiceModel.Security.IssuanceTokenProviderBase`1.ThrowIfFault(Message
message, EndpointAddress target) at
System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingMessageBody(Message
incomingMessage,
SspiNegotiationTokenProviderState
sspiState) --- End of inner
exception stack trace ---
Server stack trace: at
System.ServiceModel.Security.IssuanceTokenProviderBase1.DoNegotiation(TimeSpan
timeout) at
System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Security.TlsnegoTokenProvider.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Security.SecurityUtils.OpenCommunicationObject(ICommunicationObject
obj, TimeSpan timeout) at
System.ServiceModel.Security.SymmetricSecurityProtocol.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Channels.SecurityChannelFactory1.ClientSecurityChannel1.OnOpen(TimeSpan
timeout) at
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) at
System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperation(SecuritySessionOperation
operation, EndpointAddress target, Uri
via, SecurityToken currentToken,
TimeSpan timeout) at
System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetTokenCore(TimeSpan
timeout) at
System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan
timeout) at
System.ServiceModel.Security.SecuritySessionClientSettings1.ClientSecuritySessionChannel.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) at
System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan
timeout, CallOnceManager cascade)
at
System.ServiceModel.Channels.ServiceChannel.EnsureOpened(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)
i am also using asp membership provider....
i have been trying to get this working for the last couple hours but i'm getting nowhere..... the funny thing is that the app works on the local machine but not from a remote machine
thanks
{
<services>
<service name="AutoWatch.Entity.WcfService.SecurityService" behaviorConfiguration="ServiceBehavior">
<endpoint binding="wsHttpBinding" bindingConfiguration="ServiceBinding" bindingName="ServiceBinding" contract="AutoWatch.Entity.WcfService.ISecurityService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost..." />
</baseAddresses>
</host>
</service>
<service name="servicename" behaviorConfiguration="ServiceBehavior">
<endpoint binding="wsHttpBinding" bindingConfiguration="ServiceBinding" bindingName="ServiceBinding" contract="Service" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://localhost/.../" />
</baseAddresses>
</host>
</service>
</services>
<bindings>
<wsHttpBinding>
<binding name="ServiceBinding"></binding>
</wsHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- Configure role based authorization to use the Role Provider -->
<serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="SqlRoleProvider" />
<serviceCredentials>
<!-- Configure user name authentication to use the Membership Provider -->
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="SqlMembershipProvider" />
<!-- Configure the service certificate -->
<serviceCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" findValue="......co.za" />
</serviceCredentials>
<!-- 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>
}