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

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.

Related

WCF Rest Service broken after server restart

I made a WCF Rest Service and attached it to IIS 7 on my server and it worked great. Suddenly, we had a hard drive failure and the guys who're supposed to manage the backups didn't back up anything, so we lost all our stuff on the server.
So I go about setting everything back up, and I put all the stuff on IIS. We have another WCF Rest Service that does a lot of stuff the one I made does, including a couple of the same methods for authentication and such. But now it seems that mine won't work. Our website works and our other web service works, but not this one, and I've no idea why? I set them up the exact same and I don't think I changed anything when I did it initially.
The help reference pages work, but when calling the method, I get
"The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service."
I'm using the same methods as before, calling them with the same arguments, this happens for every method, regardless of GET or POST. I've used a REST extension thing in chrome to call it and the mobile app that I usually use to call it, as well as the browser and they all come up with the same error.
Here's the web.config file for it (I've tried adding a few things found on stackoverflow to get to the problem, but it's not done anything, really).
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation targetFramework="4.0" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel >
<behaviors>
<serviceBehaviors>
<behavior name="DataServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings >
<!-- pick whichever binding you want .... -->
<basicHttpBinding>
<!-- binding configuration with a name -->
<binding name="ExtendedMaxSize"
maxBufferSize="52428800" maxReceivedMessageSize="52428800" >
<readerQuotas maxDepth="52428800" maxStringContentLength="52428800"
maxArrayLength="52428800" maxBytesPerRead="52428800" maxNameTableCharCount="52428800" />
</binding>
</basicHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="52428800" maxBufferSize="52428800" maxBufferPoolSize="52428800" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
</configuration>
After turning tracing on, got this error from the viewer:
<E2ETraceEvent xmlns="http://schemas.microsoft.com/2004/06/E2ETraceEvent"><System
xmlns="http://schemas.microsoft.com/2004/06/windows/eventlog/system"><EventID>131076</EventID><Type>3</Type><SubType Name="Error">0</SubType><Level>2</Level><TimeCreated SystemTime="2014-03-27T12:15:47.5749853Z" /><Source Name="System.ServiceModel" /><Correlation ActivityID="{54672f7e-5a71-4dda-92a3-f07f7c94ccb9}" /><Execution ProcessName="w3wp" ProcessID="20820" ThreadID="9" /><Channel /><Computer>OHS-VMHOST-NEW</Computer></System><ApplicationData><TraceData><DataItem><TraceRecord Severity="Error" Channel="Operational" xmlns="http://schemas.microsoft.com/2004/10/E2ETraceEvent/TraceRecord"><TraceIdentifier>http://msdn.microsoft.com/en-GB/library/System.ServiceModel.Diagnostics.TraceHandledException.aspx</TraceIdentifier><Description>Handling an exception. Exception details: System.FormatException: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException)
at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult& result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult& result)
at System.Guid..ctor(String g)
at OHS.MobileAssessor.Services.MobileAssessorAPIService.GetProjectData(String token)
at SyncInvokeGetProjectData(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</Description><AppDomain>/LM/W3SVC/1/ROOT/mobileassessor-1-130403961472161807</AppDomain><Exception><ExceptionType>System.FormatException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</ExceptionType><Message>Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).</Message><StackTrace> at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException)
at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult&amp; result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult&amp; result)
at System.Guid..ctor(String g)
at OHS.MobileAssessor.Services.MobileAssessorAPIService.GetProjectData(String token)
at SyncInvokeGetProjectData(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><ExceptionString>System.FormatException: Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
at System.Guid.GuidResult.SetFailure(ParseFailureKind failure, String failureMessageID, Object failureMessageFormatArgument, String failureArgumentName, Exception innerException)
at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult&amp; result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult&amp; result)
at System.Guid..ctor(String g)
at OHS.MobileAssessor.Services.MobileAssessorAPIService.GetProjectData(String token)
at SyncInvokeGetProjectData(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</ExceptionString></Exception></TraceRecord></DataItem></TraceData></ApplicationData></E2ETraceEvent>
As requested, my GetProjectData method (And no, it isn't managing to write anything to my event log):
/// <summary>
///
/// </summary>
/// <param name="token"></param>
/// <returns></returns>
[WebGet(UriTemplate = "GetProjectData/{token}", ResponseFormat = WebMessageFormat.Json)]
public GetProjectContainerResult GetProjectData(string token)
{
WriteLog("Getting project data...");
GetProjectContainerResult result = new GetProjectContainerResult();
ProjectContainer container = new ProjectContainer();
MobileAssessorAuthenticationResults authResult = ValidateToken(new Guid(token));
if (authResult == MobileAssessorAuthenticationResults.Success)
{
container.jobs = getJobs(token);
container.buildings = getBuildings();
container.floors = getFloors();
container.locations = getLocations();
result.ReturnValue = container;
result.Result = MobileAssessorOperationResults.Success;
}
else
{
switch (authResult)
{
case MobileAssessorAuthenticationResults.Error:
result.Result = MobileAssessorOperationResults.Error;
result.ResultDescription = "An error occured.";
result.ReturnValue = new ProjectContainer();
break;
case MobileAssessorAuthenticationResults.Expired:
result.Result = MobileAssessorOperationResults.Failed;
result.ResultDescription = "The specified token has expired.";
result.ReturnValue = new ProjectContainer();
break;
case MobileAssessorAuthenticationResults.Invalid:
result.Result = MobileAssessorOperationResults.Failed;
result.ResultDescription = "The specified token is not valid.";
result.ReturnValue = new ProjectContainer();
break;
}
}
return result;
}
Looking at the stack trace from your log, I think you are having issues parsing a GUID in MobileAssessorAPIService.GetProjectData method
at System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult&amp; result)
at System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult&amp; result)
at System.Guid..ctor(String g)
at OHS.MobileAssessor.Services.MobileAssessorAPIService.GetProjectData(String token)
I would recommend that you put a break point in this method and attach a debugger to your REST service.
Based on the code you posted, the suspected line is
MobileAssessorAuthenticationResults authResult = ValidateToken(new Guid(token));
if you are not able to remotely debug this, I would recommend that you add logging just before this line to log the value of token. something like
logger.Log("paramater token = " + token);
Alternately, use wireshark to check the value of the token. once you extract the value of that guid, validate it online at http://guid.us/Test/GUID

WCF Web Service not working after IIS restart

I have a web service running on IIS 7.5
Whenever I restart the IIS or the AppPool of the website this web service is running I am getting the error message below. Then I found out that, if I change the complilation version (either from 4.5 to 4.0 or if it is 4.0 to 4.5) and save the web.config file then it starts working regularly. This is really weird. Can anybody help me on this please.
web.config:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
<connectionStrings>
<add name="NetDBEntities" connectionString="metadata=res://*/EFatura.csdl|res://*/EFatura.ssdl|res://*/EFatura.msl;provider=System.Data.SqlClient;provider connection string="data source=***********;initial catalog=*****;persist security info=True;user id=sa;password=***************;MultipleActiveResultSets=True;App=NSEfatLib"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.serviceModel>
<services>
<service name="NSEfatLib.NSEfatEntryPoint">
<endpoint address="Cari" binding="basicHttpBinding" bindingConfiguration=""
name="Cari" contract="NSEfatLib.ICari" />
<endpoint address="Stok" binding="basicHttpBinding" bindingConfiguration=""
name="Stok" contract="NSEfatLib.IStok" />
<endpoint address="FaturaIslemler" binding="basicHttpBinding"
bindingConfiguration="" name="FaturaIslemler" contract="NSEfatLib.IFaturaIslemler" />
<endpoint address="DefterIslemler" binding="basicHttpBinding"
bindingConfiguration="" name="DefterIslemler" contract="NSEfatLib.IDefterIslemler" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<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"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Error Message:
The type 'NSEfatLib.NSEfatEntryPoint', provided as the Service
attribute value in the ServiceHost directive, or provided in the
configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found. 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.InvalidOperationException: The type
'NSEfatLib.NSEfatEntryPoint', provided as the Service attribute value
in the ServiceHost directive, or provided in the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found.
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.
Stack Trace:
[InvalidOperationException: The type 'NSEfatLib.NSEfatEntryPoint',
provided as the Service attribute value in the ServiceHost directive,
or provided in the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found.]
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[] baseAddresses) +122516
System.ServiceModel.HostingManager.CreateService(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1451
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo
serviceActivationInfo, EventTraceActivity eventTraceActivity) +76
System.ServiceModel.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) +901
[ServiceActivationException: The service '/Service.svc' cannot be
activated due to an exception during compilation. The exception
message is: The type 'NSEfatLib.NSEfatEntryPoint', provided as the
Service attribute value in the ServiceHost directive, or provided in
the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found..] System.Runtime.AsyncResult.End(IAsyncResult result)
+650220 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult
result) +210733
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult
ar) +282
Event Log Entry:
System.ServiceModel.ServiceHostingEnvironment+HostingManager/62476613
System.ServiceModel.ServiceActivationException: The service
'/Service.svc' cannot be activated due to an exception during
compilation. The exception message is: The type
'NSEfatLib.NSEfatEntryPoint', provided as the Service attribute value
in the ServiceHost directive, or provided in the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found.. ---> System.InvalidOperationException: The type
'NSEfatLib.NSEfatEntryPoint', provided as the Service attribute value
in the ServiceHost directive, or provided in the configuration element
system.serviceModel/serviceHostingEnvironment/serviceActivations could
not be found. at
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String
constructorString, Uri[] baseAddresses) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.CreateService(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.ActivateService(ServiceActivationInfo
serviceActivationInfo, EventTraceActivity eventTraceActivity) at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) --- End
of inner exception stack trace --- at
System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath, EventTraceActivity eventTraceActivity) at
System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String
relativeVirtualPath, EventTraceActivity eventTraceActivity) w3wp
5028
Interestingly above error was fired when the web service was precompiled. I tried the service to run regularly (without precomopiling) and the issue is not appearing anymore.
I was using a library within the web service, so practically the web service itself did not have any code at all. Maybe that is the reason. Anyways, as there is no code, no precompilation is fine too.

"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

Win7 + VS 2010 + .NET4: Service using NetTcpBinding: net.tcp is not supported exception

I want to develop a very tiny service in WCF4 with callbacks to provide presence information (users, logins, logouts, etc), using NetTcpBinding.
My development machine is a Windows 7 64 Es with Visual Studio 2010, no IIS installed.
In order to create the services I've created a WCF Service Application project type and edited its web.config is:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="NewBinding0" portSharingEnabled="true">
<reliableSession enabled="true" />
<security mode="None" />
</binding>
</netTcpBinding>
<mexTcpBinding>
<binding name="NewBinding1" />
</mexTcpBinding>
</bindings>
<services>
<service name="JuguesServices.JuguesPresenceService">
<endpoint address="net.tcp://localhost:57920/JuguesServices/JuguesPresenceService"
binding="netTcpBinding" bindingConfiguration="NewBinding0" contract="JuguesServices.IJuguesPresenceService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Then I clicked "play" button, and a ASP.NET Development Server on port 57920 started, but this exception was thrown:
Server Error in '/' Application.
The protocol 'net.tcp' is not supported.
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.InvalidOperationException: The protocol 'net.tcp' is not supported.
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.
Stack Trace:
[InvalidOperationException: The protocol 'net.tcp' is not supported.]
System.ServiceModel.Activation.HostedTransportConfigurationManager.InternalGetConfiguration(String scheme) +98456
System.ServiceModel.Activation.HostedAspNetEnvironment.GetBaseUri(String transportScheme, Uri listenUri) +24
System.ServiceModel.Channels.TransportChannelListener.OnOpening() +12082260
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +274
System.ServiceModel.Channels.ReliableChannelListenerBase`1.OnOpen(TimeSpan timeout) +110
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +318
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +72
[InvalidOperationException: The ChannelDispatcher at 'net.tcp://localhost:57920/' with contract(s) '"IJuguesPresenceService"' is unable to open its IChannelListener.]
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan timeout) +118
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +318
System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan timeout) +111
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout) +318
System.ServiceModel.Channels.CommunicationObject.Open() +36
System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +184
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +615
[ServiceActivationException: The service '/JuguesPresenceService.svc' cannot be activated due to an exception during compilation. The exception message is: The ChannelDispatcher at 'net.tcp://localhost:57920/' with contract(s) '"IJuguesPresenceService"' is unable to open its IChannelListener..]
System.Runtime.AsyncResult.End(IAsyncResult result) +679246
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +190
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, String routeServiceVirtualPath, Boolean flowContext, Boolean ensureWFService) +234
System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +355
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +148
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
Is my config file incorrect?
Is it possible to debug a service using NetTcpBinding with the ASP.NET Development Server?
Is it necessary to use the NetTcpBinding to use CallBacks?
PS: I am trying to follow this example: http://www.codeproject.com/KB/WCF/WCFWPFChat.aspx
Edit:
The Contract:
/// <summary>
/// The service specification
/// </summary>
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IJuguesPresenceServiceCallback))]
interface IJuguesPresenceService
{
/// <summary>
/// Registers that an user is now logged in the system, and
/// notifyes it to its contacts.
/// </summary>
/// <param name="user_id">The user identificator who logs in.</param>
/// <returns>True if the login was successfull, false elsewhere.</returns>
[OperationContract(IsOneWay = false, IsInitiating = true, IsTerminating = false)]
bool UserLogin(string user_id);
/// <summary>
/// Registers that a user is no longer logged in the system, and
/// notifies it to its contact.
/// </summary>
[OperationContract(IsOneWay = true, IsInitiating = false, IsTerminating = true)]
void UserLogout();
/// <summary>
/// Returns the contact list of a logged in user.
/// </summary>
/// <returns>The list of contacts for the user.</returns>
/// <exception cref="InvalidOperationException">When tring to get the contacts without log in.</exception>
[OperationContract(IsOneWay = false, IsInitiating = false, IsTerminating = false)]
JuguesContact[] GetContacts();
}
The callback
/// <summary>
/// The events for the server-to-client communication.
/// </summary>
interface IJuguesPresenceServiceCallback
{
/// <summary>
/// Ocurrs when a contact logs in in the system.
/// </summary>
/// <param name="user_id">The identificator of the user who logged in.</param>
[OperationContract(IsOneWay = true)]
void UserLoggedIn(string user_id);
/// <summary>
/// Occurs when a contact logs out of the system.
/// </summary>
/// <param name="user_id">The identificator of the user who logged out.</param>
[OperationContract(IsOneWay = true)]
void UserLoggedOut(string user_id);
}
Your stack trace contains a reference to "HostedAspNetEnvironment", which hints that this is a web project to be hosted by IIS or the built-in development server. This will restrict you to HTTP/HTTPS. You will want to look into one of the following options:
Self-hosting - writing a standalone console or WinForms application that will construct a ServiceHost to host your WCF service.
Windows service - same as self-hosting, but running inside of a managed Windows service. This is advantageous as you can run the service on a server with nobody logged in, and take advantage of Windows automatic server restart functionality.
Windows Process Activation Service (WAS) - I don't have much experience with this, but it seems to be a stripped down version of IIS, without the restriction that services must use HTTP/HTTPS.
See an overview of your options here: http://msdn.microsoft.com/en-us/library/ms730158.aspx

CrossDomainError on IIS7 Silverlight 3 WCF app

* Readers Beware: massive code dump, not for the faint of heart... *
Hello,
I'm trying to figure out how to deploy a Silverlight 3 app to IIS7 with a WCF Service. I think i've got most of it figured out however I still get a cross domain error for some reason. I'm leaning toward thinking that the service is not finding the client access policy but I'm not sure how to confirm this. I get a very useless exception (simply says CrossDomainError). Inner Exception is nonexistant. Here are the steps I've taken to deploy the app. If anyone sees anything that doesn't add up can they please advise? I can't think of anything else to poke at right now...
In IIS manager I built a new site. I named it Silverlight, accepted a pool of the same name, and accepted all the rest of the defaults. I disabled the default site. I set the web root to be C:\WebApps
I placed all of the files from the release build of my Visual Studio Silverlight client project into the web root.
I place the following config files from the Silverlight client project in the web root: ServiceReferences.ClientConfig, Silverlight.js.
I placed the /bin directory from the release build of the Silverlight.Web project into the web root
I place the following files from the Silverlight.Web release build in the web root: crossdomain.xml, clientaccesspolicy.xml, Service1.svc, Service1.svc.cs, Web.config.
I renamed the TestPage.html file to index.html.
I realize that many of these are superfluous but I was running out of things to try so I started adding anything that looked like it might contain any useful metadata.
Here is the code to my various config files:
clientaccesspolicy.xml:
<?xml version="1.0" encoding="utf-8" ?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource include-subpaths="true" path="/"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
crossdomain.xml:
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
system.serviceModel configuration, excerpted from Web.config:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="SilverlightApplication2.Web.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="customBinding0">
<binaryMessageEncoding/>
<httpTransport/>
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<services>
<service behaviorConfiguration="SilverlightApplication2.Web.Service1Behavior" name="SilverlightApplication2.Web.Service1">
<endpoint address="http://win-xqawq222tag:2721/Service1.svc" binding="customBinding" bindingConfiguration="customBinding0" contract="SilverlightApplication2.Web.Service1"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
</system.serviceModel>
ServiceReferences.ClientConfig:
<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CustomBinding_Service1">
<binaryMessageEncoding />
<httpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="http://win-xqawq222tag:2721/Service1.svc" binding="customBinding"
bindingConfiguration="CustomBinding_Service1" contract="ServiceReference1.Service1"
name="CustomBinding_Service1" />
</client>
</system.serviceModel>
</configuration>
Service1.svc:
<%# ServiceHost Language="C#" Debug="true" Service="SilverlightApplication2.Web.Service1" CodeBehind="Service1.svc.cs" %>
Now for the implementation followed by the client code:
Service1.svc.cs:
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
namespace SilverlightApplication2.Web
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1
{
[OperationContract]
public DoWorkResult DoWork()
{
// Add your operation implementation here
int i = new Random().Next();
string s = "test string";
DoWorkResult r = new DoWorkResult() { String = s, Integer = i };
return r;
}
// Add more operations here and mark them with [OperationContract]
}
[DataContract]
public class DoWorkResult
{
[DataMember]
public string String { get; set; }
[DataMember]
public int Integer { get; set; }
}
}
MainPage.xaml.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication2
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
ServiceReference1.Service1Client proxy = new SilverlightApplication2.ServiceReference1.Service1Client();
proxy.DoWorkCompleted += new EventHandler<SilverlightApplication2.ServiceReference1.DoWorkCompletedEventArgs>(proxy_DoWorkCompleted);
proxy.OpenAsync();
proxy.DoWorkAsync();
proxy.CloseAsync();
}
void proxy_DoWorkCompleted(object sender, SilverlightApplication2.ServiceReference1.DoWorkCompletedEventArgs e)
{
if (e.Error == null)
{
String.Text = "Test String is: " + e.Result.String;
Integer.Text = "Random Int is: " + e.Result.Integer;
}
else
{
String.Text = e.Error.Message + e.Error.InnerException.Message + e.Error.StackTrace;
Integer.Text = e.Error.Message + e.Error.InnerException.Message + e.Error.StackTrace;
}
}
}
}
All of this works fine in VS 2008 on XP Pro. On IIS7 on Server2008 I am able to hit the default page, index.html, at http://localhost or at http://[myComputerName].
I am also able to hit the service at http://localhost/Service1.svc. I am not able to hit the service using http://[compNameHere]/Service1.svc. It complains with this error:
No protocol binding matches the given
address
'http://win-xqawq222tag:2721/Service1.svc'.
Protocol bindings are configured at
the Site level in IIS or WAS
configuration. 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.InvalidOperationException: No
protocol binding matches the given
address
'http://win-xqawq222tag:2721/Service1.svc'.
Protocol bindings are configured at
the Site level in IIS or WAS
configuration.
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.
Stack Trace:
[InvalidOperationException: No
protocol binding matches the given
address
'http://win-xqawq222tag:2721/Service1.svc'.
Protocol bindings are configured at
the Site level in IIS or WAS
configuration.]
System.ServiceModel.Channels.TransportChannelListener.OnOpening()
+11513378 System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +229
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan
timeout) +72
[InvalidOperationException: The
ChannelDispatcher at
'http://win-xqawq222tag:2721/Service1.svc'
with contract(s) '"Service1"' is
unable to open its IChannelListener.]
System.ServiceModel.Dispatcher.ChannelDispatcher.OnOpen(TimeSpan
timeout) +118
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +261
System.ServiceModel.ServiceHostBase.OnOpen(TimeSpan
timeout) +107
System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
timeout) +261
System.ServiceModel.HostingManager.ActivateService(String
normalizedVirtualPath) +121
System.ServiceModel.HostingManager.EnsureServiceAvailable(String
normalizedVirtualPath) +479
[ServiceActivationException: The
service '/Service1.svc' cannot be
activated due to an exception during
compilation. The exception message
is: The ChannelDispatcher at
'http://win-xqawq222tag:2721/Service1.svc'
with contract(s) '"Service1"' is
unable to open its IChannelListener..]
System.ServiceModel.AsyncResult.End(IAsyncResult
result) +11531006
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult
result) +194
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication
context, Boolean flowContext) +176
System.ServiceModel.Activation.HttpHandler.ProcessRequest(HttpContext
context) +23
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+181 System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+75
No protocol binding matches the given
address
'http://win-xqawq222tag:2721/Service1.svc'.
Protocol bindings are configured at
the Site level in IIS or WAS
configuration.
Further, I am able to hit the policy file at http://localhost/clientaccesspolicy.xml and http://[computerNameHere]/clientaccesspolicy.xml.
Is there something else I need to look at?
I freely admit I haven't exactely tried to reproduce you specific error, but I noticed something I too stubled over.
Colin Cole blogged that there was a subtle change in cap.xml format in regard to using SSL.
I didn't use SSL, but only when I changed
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
to
<allow-from http-request-headers="*">
<domain uri="http://*" />
<domain uri="https://*" /> <!-- if needed -->
</allow-from>
accessing the service worked.
I had to make the following change to the ServiceReferences.ClientConfig file and then publish again:
<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CustomBinding_Service1">
<binaryMessageEncoding />
<httpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="http://localhost/Service1.svc" binding="customBinding"
bindingConfiguration="CustomBinding_Service1" contract="ServiceReference1.Service1"
name="CustomBinding_Service1" />
<!--<endpoint address="http://localhost:2721/Service1.svc" binding="customBinding"
bindingConfiguration="CustomBinding_Service1" contract="ServiceReference1.Service1"
name="CustomBinding_Service1" />-->
</client>
</system.serviceModel>
</configuration>