wcf linq to sql error - wcf

I am getting an error returning a linq query over http to an ASP.Net application
I have the following wcf service running in IIS
public class ProductService : IProductService
{
NorthwindEntities context = new NorthwindEntities();
public List<Customer> GetCustomers()
{
return context.Customers.Select(c => c).ToList();
}
}
Web Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
</system.web>
<system.serviceModel>
<services>
<service name="WCF_Entity.ProductService">
<endpoint address="" binding="wsHttpBinding" contract="WCF_Entity.IProductService" />
</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="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<connectionStrings>
<add name="NorthwindEntities" connectionString="metadata=res://*/Northwind.csdl|res://*/Northwind.ssdl|res://*/Northwind.msl;provider=System.Data.SqlClient;provider connection string="Data Source=SHLOMOKATZ-PC;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
I created a ASP.Net application to use the service
myService.ProductServiceClient objService = new ProductServiceClient();
var customers = objService.GetCustomers();
on debuging, I get the following error
An existing connection was forcibly closed by the remote host
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
Source Error:
Line 2454:
Line 2455: public ASPWFC.myService.Customer[] GetCustomers() {
Line 2456: return base.Channel.GetCustomers();
Line 2457: }
Line 2458: }
Source File: D:\My Documents\Visual Studio 2010\Projects\wcf\WCF_Entity\ASPWFC\Service References\myService\Reference.cs Line: 2456
Stack Trace:
[SocketException (0x2746): An existing connection was forcibly closed by the remote host]
System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) +6132200
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +134
[IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.]
System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) +300
System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) +26
System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead) +265
[WebException: The underlying connection was closed: An unexpected error occurred on a receive.]
System.Net.HttpWebRequest.GetResponse() +6038435
System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +103
[CommunicationException: An error occurred while receiving the HTTP response to http://localhost/WCF_Entity_SVC/ProductService.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9464367
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345
ASPWFC.myService.IProductService.GetCustomers() +0
ASPWFC.myService.ProductServiceClient.GetCustomers() in D:\My Documents\Visual Studio 2010\Projects\wcf\WCF_Entity\ASPWFC\Service References\myService\Reference.cs:2456
ASPWFC._Default.Page_Load(Object sender, EventArgs e) in D:\My Documents\Visual Studio 2010\Projects\wcf\WCF_Entity\ASPWFC\Default.aspx.cs:36
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +37
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +95
System.Web.UI.Control.OnLoad(EventArgs e) +145
System.Web.UI.Control.LoadRecursive() +134
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3412
changing the buffer length, etc... Didn't solve the issue. The database is the sample NorthWind database
I am able to browse to the service
It seems that Aliostad is correct as I recreated the service without using IIs and used ASP to consume the service, and get the below error. So it is a problem invoking the svc from the app, I can still run the service directly via http
The underlying connection was closed: The connection was closed unexpectedly.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The underlying connection was closed: The connection was closed unexpectedly.
Source Error:
Line 2337:
Line 2338: public NorthwindApp.myService.Customer[] getCustomers() {
Line 2339: return base.Channel.getCustomers();
Line 2340: }
Line 2341: }
Source File: d:\my documents\visual studio 2010\Projects\wcf\NorthwindServices\NorthwindApp\Service References\myService\Reference.cs Line: 2339
Stack Trace:
[WebException: The underlying connection was closed: The connection was closed unexpectedly.]
System.Net.HttpWebRequest.GetResponse() +6038435
System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +51
[CommunicationException: The underlying connection was closed: The connection was closed unexpectedly.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +9464367
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +345
NorthwindApp.myService.INorthwindService.getCustomers() +0
NorthwindApp.myService.NorthwindServiceClient.getCustomers() in d:\my documents\visual studio 2010\Projects\wcf\NorthwindServices\NorthwindApp\Service References\myService\Reference.cs:2339
NorthwindApp._Default.Page_Load(Object sender, EventArgs e) in d:\my documents\visual studio 2010\Projects\wcf\NorthwindServices\NorthwindApp\Default.aspx.cs:18
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +46
System.Web.UI.Control.OnLoad(EventArgs e) +83
System.Web.UI.Control.LoadRecursive() +120
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3954

I found an article that says that with entity framework 4 there is a problem to serialize entities in wcf with lazy loading enabled
I added the following code to the service and everything works
context.ContextOptions.LazyLoadingEnabled = false;
link to article http://geekswithblogs.net/danemorgridge/archive/2010/05/04/entity-framework-4-wcf-amp-lazy-loading-tip.aspx

How many records are being returned? There are a couple of things in play here:
From a WCF Perspective:
MaxBufferSize: Gets or sets the maximum size of the buffer to use. For buffered messages this value is the same as MaxReceivedMessageSize. For streamed messages, this value is the maximum size of the SOAP headers, which must be read in buffered mode. For a non-streamed message, if the message size is greater than this property, then the message is dropped.
If not specified, this defaults to 65536.
This is only 0.0625 megabytes!
MaxReceivedMessageSize: Gets and sets the maximum allowable message size that can be received.
Default here is also 65536 bytes.
MaxStringContentLength: Gets and sets the maximum string length returned by the reader.
Your service is probably returning a value greater in size than the defaults.
So, you could try modifying your service behavior to include these attributes with higher limits, say 6 MB or so to see if it resolves your issue.
Also - remember there is maxRequestLength limit which is enforced by IIS which trumps any WCF setting, the default is 4096 KB, so you may have to tweak that if you alter the above properties.

Related

WCF customUserNamePasswordValidatorType error - Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies

I have created a simply WCF web service and require WCF Security with username/password added to the service and have read through the following MS documentation https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-a-custom-user-name-and-password-validator to try and do so.
However, I am getting the error below when I run the project and go to http://localhost:50533/Service.svc:
Server Error in '/' Application.
Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'CustomUserNameValidator' could not be loaded.
=== Pre-bind state information ===
LOG: DisplayName = CustomUserNameValidator
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: CustomUserNameValidator | Domain ID: 6
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/
LOG: Initial PrivatePath = C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\web.config
LOG: Using host configuration file: C:\Users\xxxx\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.EXE.
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +71
System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) +41
System.Type.GetType(String typeName, Boolean throwOnError) +35
System.ServiceModel.Configuration.UserNameServiceElement.ApplyConfiguration(UserNamePasswordServiceCredential userName) +356
System.ServiceModel.Configuration.ServiceCredentialsElement.ApplyConfiguration(ServiceCredentials behavior) +128
System.ServiceModel.Configuration.ServiceCredentialsElement.CreateBehavior() +165
System.ServiceModel.Description.ConfigLoader.LoadBehaviors(ServiceModelExtensionCollectionElement`1 behaviorElement, KeyedByTypeCollection`1 behaviors, Boolean commonBehaviors) +204
System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress, Boolean skipHost) +13502205
System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection) +74
System.ServiceModel.ServiceHostBase.ApplyConfiguration() +188
System.ServiceModel.ServiceHost.ApplyConfiguration() +65
System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses) +188
System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses) +49
System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses) +153
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(Type serviceType, Uri[] baseAddresses) +34
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +538
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1489
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +53
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +666
[ServiceActivationException: The service '/Service.svc' cannot be activated due to an exception during compilation. The exception message is: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified..]
System.Runtime.AsyncResult.End(IAsyncResult result) +513025
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +182
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +12
System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +161
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +128
I have noticed this error only appears due to adding the following into my Web.Config file
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
I've modified the value in customUserNamePasswordValidatorType numerous times to try and fix it but the error still comes up or a similar one.
See below for the full Web.Config file.
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
<pages>
<namespaces>
<add namespace="System.Runtime.Serialization"/>
<add namespace="System.ServiceModel"/>
<add namespace="System.ServiceModel.Web"/>
</namespaces>
</pages>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Binding1">
<security mode="Transport">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="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"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</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>
The Code is simply the default WCF Service code you get out of the box when creating a new WCF Service project in Visual Studio and I've just added a new CustomUserNameValidator class.
If you want to see this class, here is the code for it:
Imports System.IdentityModel.Selectors
Public Class CustomUserNameValidator
Inherits UserNamePasswordValidator
Public Overrides Sub Validate(ByVal userName As String, ByVal password As String)
If userName Is Nothing OrElse password Is Nothing Then
Throw New ArgumentNullException()
End If
If Not (userName = "user" AndAlso password = "pass123") Then
Throw New FaultException("Unknown Username or Incorrect Password")
End If
End Sub
End Class
Also, this is all that shows in Properties for the file.
If you can please help with the error, that would be very much appreciated.
You must to be sure that the “Build Action” on the “CustomUserNameValidator.vb” Properties is set to “Compile”.
It seems to be set on “Content” based on what you are describing.
The image shows how you can do that or take a look here:
https://learn.microsoft.com/en-us/visualstudio/ide/build-actions?view=vs-2022
The reason I was getting the problem above was because I needed to set this in the web.config
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomUserNameValidator, App_Code" />
</serviceCredentials>
When I went to the following path on my machine, the only dll was App_Code.tjgywzog.dll so figured the assembly is just App_Code and then it just has to use the class name CustomUserNameValidator since my code is not using namespaces.

how to access EF navigation properties via WCF SOAP service?

I am struggling with this WCF error for some time now without any luck. Basically I am tying to fetch an Entity Poco with Navigation Properties and connected objects via WCF Services. My EF v6 code successfully get the poco with all the related entities from the DB
Poco debug view
but as i try to access this Entity via WCF service, i see the following error -
An error occurred while receiving the HTTP response to http://localhost:8734/Design_Time_Addresses/BusinessLogicServicesLayer/userServices/. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory1.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 IuserServicesQuery.getCompleteUserSnapshot(String emailAddress)
at IuserServicesQueryClient.getCompleteUserSnapshot(String emailAddress)
Inner Exception:
The underlying connection was closed: An unexpected error occurred on a receive.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
Inner Exception:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
Inner Exception:
An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
my AppConfig file looks like this -
<endpoint address="" behaviorConfiguration="MyBehavior" binding="basicHttpBinding"
bindingConfiguration="IncreasedTimeout" name="BasicHttpEndpoint"
contract="BusinessLogicServicesLayer.IuserServicesQuery" listenUriMode="Explicit">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
&&
<bindings>
<basicHttpBinding>
<binding name="IncreasedTimeout"
openTimeout="12:00:00"
receiveTimeout="12:00:00" closeTimeout="12:00:00"
sendTimeout="12:00:00">
</binding>
</basicHttpBinding>
</bindings>
.
.
<behaviors>
<endpointBehaviors>
<behavior name="MyBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483646" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
can someone please help out or point me to a correct direction
This is because when data is returned, serialization fails, causing the WCF service to stop automatically.
Solution:
We can serialize the proxy class into the entities we need before returning the data.
Here is a demo,The student class contains the navigation properties of other entities:
public Student Getstu()
{
CodeFirstDBContext codeFirstDBContext = new CodeFirstDBContext();
Student student =codeFirstDBContext.Student.Find(1);
var serializer = new DataContractSerializer(typeof(Student), new DataContractSerializerSettings()
{
DataContractResolver = new ProxyDataContractResolver()
});
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, student);
stream.Seek(0, SeekOrigin.Begin);
var stu = (Student)serializer.ReadObject(stream);
return stu;
}
}
This is the method that the client will call.
ServiceReference1.ServiceClient serviceClient = new ServiceReference1.ServiceClient();
var stu = serviceClient.Getstu();
Client-side will call successfully.
UPDATE Disabling Loading loading also solves this problem:
public class CodeFirstDBContext : DbContext
{
public CodeFirstDBContext() : base("name=DBConn")
{
this.Configuration.ProxyCreationEnabled = false;
this.Configuration.LazyLoadingEnabled = false;
Database.SetInitializer(new CreateDatabaseIfNotExists<CodeFirstDBContext>());
}
}

"No destination configuration registered" - WCF/SAP integration using SAP nCo3 (SAP .NET Connectior 3.0)

When I try to call a WCF service I developed I get this error message: "Method or operation is not implemented".
Let me explain the scenario I'm facing and them I'll give you more details, the code and etc:
I'm developing a WCf service in .NET framework 4.0 in a Windows 8/Visual Studio 2012 machine.
The WCF service will be accessed from a mobile application developed in .NET compact framework 2.0 (Dev environment: a Virtual Machine running Windows XP service pack 3, Visual Studio 2008, Windows Mobile 6.1 Professional Emulator).
The WCF service is using the SAP .NET Conector (SAPnCO) version 3.0.
When I run the service using VS integrated IIS or IIS8, everything goes fine: I can test the service, access it from a test console application and can access it from Windows Mobile Emulator.
However, we where about to start some preliminar tests with the final users and we still didn`t have a proper server to deploy the WCF application, so I had to make a contingency server using Windows XP and IIS express 7.5 (I was not able to make it work on IIS 5.1).
I know that IIS Express is for local access only, but I followed this tutorial to open ti to the LAN: TUTORIAL.
Doing so I can acess the service signature via browser and see the WSDL file.
Everytime i try to acess the service I get the error message "Method or operation is not implemented". I`ve been looking for some similar problem over the internet for the past 4 hours without success.
Here`s what I managed to do so far:
Host a default WCF sample service on IIS Express 7.5 and use the service remotely: ok;
Reduce the scope of the original service to the minimal only: still get the same error;
So, I still don't know what can be causing this or how to solve it. I kindly request for your help, please!
Here`s my code:
WEB.CONFIG
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="SAP.Middleware.Connector">
<sectionGroup name="ClientSettings">
<section name="DestinationConfiguration" type="SAP.Middleware.Connector.RfcDestinationConfiguration, sapnco"/>
</sectionGroup>
</sectionGroup>
</configSections>
<SAP.Middleware.Connector>
<ClientSettings>
<DestinationConfiguration>
<destinations>
<add NAME="QA" USER="XX" PASSWD="XX" CLIENT="XX" LANG="XX" ASHOST="XX" SYSNR="XX" MAX_POOL_SIZE="XX" IDLE_TIMEOUT="XX"/>
</destinations>
</DestinationConfiguration>
</ClientSettings>
</SAP.Middleware.Connector>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<appSettings/>
<system.web>
<compilation targetFramework="4.0" debug="true"/>
<httpRuntime/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="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>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</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>
SERVICE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using SAP.Middleware.Connector;
namespace WCFCriarOT
{
public class Service1 : IService1
{
public string CriarOT(int areaSelecionada, int nlenr, string codMaterial, int qtdMAterial)
{
try
{
string vltyp = "", vlpla = "";
switch (areaSelecionada)
{
case 1:
vltyp = "902";
vlpla = "GR-ZONE";
break;
case 3:
vltyp = "901";
vlpla = "GFI-ZONE";
break;
case 4:
vltyp = "904";
vlpla = "DEVOLUCAO";
break;
default:
break;
}
RfcDestination SapRfcDestination = RfcDestinationManager.GetDestination("QA");
RfcRepository SapRfcRepository = SapRfcDestination.Repository;
IRfcFunction FCriarOT = SapRfcRepository.CreateFunction("ZWM001");
FCriarOT.SetValue("I_LGNUM", "WM1");
FCriarOT.SetValue("I_BWLVS", "999");
FCriarOT.SetValue("I_MATNR", codMaterial);
FCriarOT.SetValue("I_WERKS", "120");
FCriarOT.SetValue("I_LGORT", "0001");
FCriarOT.SetValue("I_ANFME", qtdMAterial);
FCriarOT.SetValue("I_SQUIT", "");
FCriarOT.SetValue("I_VLTYP", vltyp);
FCriarOT.SetValue("I_VLPLA", vlpla);
FCriarOT.SetValue("I_VLENR", "");
FCriarOT.SetValue("I_NLTYP", "");
FCriarOT.SetValue("I_NLPLA", "");
FCriarOT.SetValue("I_NLENR", nlenr.ToString().PadLeft(20, '0'));
FCriarOT.SetValue("I_BNAME", "PAGOTR"); // receber os dados do login posteriormente
FCriarOT.Invoke(SapRfcDestination);
if (Convert.ToInt32(FCriarOT.GetValue("E_RETURN")) == 1)
{
IRfcTable RfcReturn = FCriarOT.GetTable("T_MSG");
RfcReturn.CurrentIndex = 0;
return "1";
}
else
{
return "0";
}
}
catch (Exception ex)
{
throw new NotImplementedException();
}
}
}
SERVICE SIGNATURE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WCFCriarOT
{
[ServiceContract]
public interface IService1
{
// Contrato para a operação "Criar OT"
[OperationContract]
string CriarOT(int areaSelecionada, int nlenr, string codMaterial, int qtdMAterial);
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
}
Exception
System.ServiceModel.FaultException`1 was unhandled
HResult=-2146233087
Message=O método ou a operação não está implementada.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
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 testeDoTeste1.ServiceReference1.IService1.CriarOT(Int32 areaSelecionada, Int32 nlenr, String codMaterial, Int32 qtdMAterial)
at testeDoTeste1.ServiceReference1.Service1Client.CriarOT(Int32 areaSelecionada, Int32 nlenr, String codMaterial, Int32 qtdMAterial) in c:\Users\Documents\Visual Studio 2012\Projects\testeDoTeste1\testeDoTeste1\Service References\ServiceReference1\Reference.cs:line 119
at testeDoTeste1.Program.Main(String[] args) in c:\Users\Documents\Visual Studio 2012\Projects\testeDoTeste1\testeDoTeste1\Program.cs:line 16
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
If I have failed in provide all necessary information, please, let me know: I will provide anything I can. I really need and apretiate all your help! Tks a lot!
--------------
UPDATE 1
Since the WEB.CONFIG file is the only piece of the service that is edited to make the WCF service work with IIS Express I think this can (evetually) be the source of trouble. I`m posting the original WEB.CONFIG file, without the edits hoping that this can help someone spot the problem!
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="SAP.Middleware.Connector">
<sectionGroup name="ClientSettings">
<section name="DestinationConfiguration" type="SAP.Middleware.Connector.RfcDestinationConfiguration, sapnco"/>
</sectionGroup>
</sectionGroup>
</configSections>
<SAP.Middleware.Connector>
<ClientSettings>
<DestinationConfiguration>
<destinations>
<add NAME="QA" USER="XX" PASSWD="XX" CLIENT="XX" LANG="XX" ASHOST="XX" SYSNR="XX" MAX_POOL_SIZE="XX" IDLE_TIMEOUT="XX"/>
</destinations>
</DestinationConfiguration>
</ClientSettings>
</SAP.Middleware.Connector>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<appSettings/>
<system.web>
<compilation targetFramework="4.0" debug="true"/>
<httpRuntime/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="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>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</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>
--------------
UPDATE 2
Found a new error, but it`s still fuzzy to me: "{"Cannot get destination QA -- no destination configuration registered"}". This destination works fine in dev, so why it is not working on IIS Express?
Anyways, here`s the complete exception:
System.ServiceModel.FaultException`1 was unhandled
HResult=-2146233087
Message=Cannot get destination QA -- no destination configuration registered
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
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 testeDoTeste1.ServiceReference1.IService1.CriarOT(Int32 areaSelecionada, Int32 nlenr, String codMaterial, Int32 qtdMAterial)
at testeDoTeste1.ServiceReference1.Service1Client.CriarOT(Int32 areaSelecionada, Int32 nlenr, String codMaterial, Int32 qtdMAterial) in c:\Users\Documents\Visual Studio 2012\Projects\testeDoTeste1\testeDoTeste1\Service References\ServiceReference1\Reference.cs:line 119
at testeDoTeste1.Program.Main(String[] args) in c:\Users\Documents\Visual Studio 2012\Projects\testeDoTeste1\testeDoTeste1\Program.cs:line 16
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
--------------
I have found, this exception occurs if sapnco assembly is not loaded. Try to set referenced SAP assemblies to Copy local: True.
It is not ideal solution, but it has worked for me well.
I resolved it by moving the configSections' section to the top of the app.config. Maybe the 'configSections' must be the first child section of configuration.
See here too:
Parameter 'sectionGroupName' is invalid

System.ServiceModel.CommunicationException - On Large Message Size

I'm getting this exception on the client application, not sure how to get past this.
I encounter this exception when the data returned(A list of prices) exceeds 15MB, but works for message size less that 15MB.
Error Message:
An error occurred while receiving the HTTP response to "http://localhost:8782/CMDService". This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.
Trace O/P for client from TraceViewer:
<ApplicationData>
<TraceData>
<DataItem>
<TraceRecord xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord" Severity="Error">
<TraceIdentifier>http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx</TraceIdentifier>
<Description>Throwing an exception.</Description>
<AppDomain>CMD.Web.Test.exe</AppDomain>
<Exception>
<ExceptionType>System.ServiceModel.CommunicationException, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>An error occurred while receiving the HTTP response to "http://localhost:8782/CMDService". This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.</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 CMD.Client.Interface.ICMDService.GetData(String region, DateTime QuoteDate)
at CMD.Web.Test.Program.TestGetData()
at CMD.Web.Test.Program.Main(String[] args)
</StackTrace>
<ExceptionString>System.ServiceModel.CommunicationException: An error occurred while receiving the HTTP response to "http://localhost:8782/CMDService". This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details. System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
--- End of inner exception stack trace ---
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=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>The underlying connection was closed: An unexpected error occurred on a receive.</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: An unexpected error occurred on a receive. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)</ExceptionString>
<InnerException>
<ExceptionType>System.IO.IOException, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.</Message>
<StackTrace>
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)
</StackTrace>
<ExceptionString>System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead)</ExceptionString>
<InnerException>
<ExceptionType>System.Net.Sockets.SocketException, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType>
<Message>An existing connection was forcibly closed by the remote host</Message>
<StackTrace>
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
</StackTrace>
<ExceptionString>System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)</ExceptionString>
<NativeErrorCode>2746</NativeErrorCode>
</InnerException>
</InnerException>
</InnerException>
</Exception>
</TraceRecord>
</DataItem>
</TraceData>
</ApplicationData>
Tracing on the service did not report any exceptions
Config on both service and client are identical
<basicHttpBinding>
<binding name="CMDServiceBinding"
receiveTimeout="00:10:00"
closeTimeout="00:10:00"
openTimeout="00:10:00"
sendTimeout="00:10:00"
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
<behaviors>
<serviceBehaviors>
<behavior name="UBS.Firc.Broil.CMD.QuotesServiceBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
</behaviors>
Any help would be much appreciated. Thanks
Briefly in behaviors you have serviceBehavior and endpointBehavior. You should write something like this:
<behaviors>
<endpointBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="10000000"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
Hoping that helps !
Hope It may help you...
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IVtmWebResolution" maxBufferSize="2147483647" receiveTimeout="00:10:00" sendTimeout="00:10:00"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
Happy Coding
If your service was hosted by ASP.NET, you might have to increase ASP.NET's max upload size:
<system.web>
<httpRuntime maxRequestLength="2147483647" />
</system.web>

WCF Net.TCP service throwing obscure errors

I am trying to enable an additional net.tcp endpoint (which uses Username authentication) for an existing WCF service. The service is hosted in IIS7.
Executing a client against the service returns an error that the socket connection was aborted. Enabling tracing against the service reveals the following exception is thrown:
System.ArgumentOutOfRangeException
The value of this argument must be positive.
Parameter name: maxAccepts
Actual value was 0.
I'm confused, because as best I can tell port sharing should be disabled by the configuration (see below), but it's still calling through the port sharing code (again, as best I can tell). In any case, I can't find any way to specify this maxAccepts value; Google doesn't know anything about it, and the maxPendingAccepts value doesn't seem to do it. How do I resolve the error?
The service's config file contains the following for the net.tcp endpoint:
<bindings>
<customBinding>
<binding name="netTcp">
<security authenticationMode="UserNameOverTransport" />
<windowsStreamSecurity />
<tcpTransport portSharingEnabled="false" listenBacklog="10" maxPendingAccepts="10" maxPendingConnections="10" />
</binding>
</customBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="netTcp">
<serviceDebug includeExceptionDetailInFaults="false" />
<serviceMetadata/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Asi.Soa.ServiceModelEx.NullUserNamePasswordValidator, Asi.Soa.ServiceModelEx" />
<clientCertificate>
<authentication certificateValidationMode="None"/>
</clientCertificate>
</serviceCredentials>
<serviceAuthorization principalPermissionMode="Custom">
<authorizationPolicies>
<add policyType="Asi.Soa.ServiceModelEx.ClaimsAuthorizationPolicy, Asi.Soa.ServiceModelEx" />
</authorizationPolicies>
</serviceAuthorization>
</behavior>
</serviceBehaviors>
</behaviors>
The full exception stack trace is:
System.ServiceModel.Channels.ConnectionAcceptor..ctor(IConnectionListener listener, Int32 maxAccepts, Int32 maxPendingConnections, ConnectionAvailableCallback callback, ErrorCallback errorCallback)
System.ServiceModel.Channels.ConnectionDemuxer..ctor(IConnectionListener listener, Int32 maxAccepts, Int32 maxPendingConnections, TimeSpan channelInitializationTimeout, TimeSpan idleTimeout, Int32 maxPooledConnections, TransportSettingsCallback transportSettingsCallback, SingletonPreambleDemuxCallback singletonPreambleCallback, ServerSessionPreambleDemuxCallback serverSessionPreambleCallback, ErrorCallback errorCallback)
System.ServiceModel.Channels.SharedTcpTransportManager.CreateConnectionDemuxer()
System.ServiceModel.Channels.SharedTcpTransportManager.OnDuplicatedVia(Uri via, Int32& connectionBufferSize)
System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.HandleOnVia(DuplicateContext duplicateContext)
System.ServiceModel.Channels.SharedConnectionListener.SharedListenerProxy.System.ServiceModel.Activation.IConnectionDuplicator.BeginDuplicate(DuplicateContext duplicateContext, AsyncCallback callback, Object state)
AsyncInvokeBeginBeginDuplicate(Object , Object[] , AsyncCallback , Object )
System.ServiceModel.Dispatcher.AsyncMethodInvoker.InvokeBegin(Object instance, Object[] inputs, AsyncCallback callback, Object state)
System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc)
System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.Dispatch(MessageRpc& rpc, Boolean isOperationContextSet)
System.ServiceModel.Dispatcher.ChannelHandler.DispatchAndReleasePump(RequestContext request, Boolean cleanThread, OperationContext currentOperationContext)
System.ServiceModel.Dispatcher.ChannelHandler.HandleRequest(RequestContext request, OperationContext currentOperationContext)
System.ServiceModel.Dispatcher.ChannelHandler.AsyncMessagePump(IAsyncResult result)
System.ServiceModel.Dispatcher.ChannelHandler.OnAsyncReceiveComplete(IAsyncResult result)
System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
System.ServiceModel.Channels.FramingDuplexSessionChannel.TryReceiveAsyncResult.OnReceive(IAsyncResult result)
System.ServiceModel.Diagnostics.Utility.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
System.ServiceModel.Channels.SynchronizedMessageSource.ReceiveAsyncResult.OnReceiveComplete(Object state)
System.ServiceModel.Channels.SessionConnectionReader.OnAsyncReadComplete(Object state)
System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
System.ServiceModel.Channels.TracingConnection.WaitCallback(Object state)
System.ServiceModel.Channels.PipeConnection.OnAsyncReadComplete(Boolean haveResult, Int32 error, Int32 numBytes)
System.ServiceModel.Channels.OverlappedContext.CompleteCallback(UInt32 error, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
System.ServiceModel.Diagnostics.Utility.IOCompletionThunk.UnhandledExceptionFrame(UInt32 error, UInt32 bytesRead, NativeOverlapped* nativeOverlapped)
System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
Edit: I have installed the non-HTTP WCF activation components, run ServiceModelReg.exe, added net.tcp and net.pipe to the list of enabled protocols in IIS Manager, etc. No joy.
I've also written a quick Windows Service to host the service (not the ideal long-term solution for us), and the Net TCP connection works fine there, so it doesn't appear to be anything in my configuration or code, which means something isn't right in/with IIS. Does the app pool for the application have to be running in Integrated mode? I tried it both ways, it didn't seem to make a difference, but our app currently is installed in Classic mode.
As best I can determine, the problem is simply that .NET does not like hosting two services in the same IIS application when one is a Soap11 endpoint and one is a NetTcp endpoint. Removing the Soap11 endpoint allows the NetTcp endpoint to work without error.
We've moved to a model where we are using a Windows Service to host the NetTcp endpoint and left the Soap11 endpoint in IIS.
If anyone figures out how to host both a NetTcp and Soap11 service in the same application in IIS, I'd love to hear about it.
Net.tcp does not work on IIS7 out-of-the-box, there are a number of things that need to be activated.
See: http://labs.episerver.com/en/Blogs/Paul-Smith/Dates/2008/6/Hosting-non-HTTP-based-WCF-applications-in-IIS7/