WCF Exception : ServiceHost only supports class service types -- when run from windows service - wcf

i am new in wcf. i am facing this error ServiceHost only supports class service types.
here i will say i am doing & running my win service & wcf together.
i added windows service project and also add few reference like System.ServiceModel for wcf in win service project. when i am trying to run wcf service from win service then i am getting error called ServiceHost only supports class service types
i search & got many answer like
ServiceHost host = new ServiceHost(
typeof(subservice.ISubService), new Uri("someuri"));
If this is your usage, change it to use the implemented service class type of ISubService
ServiceHost host = new ServiceHost(
typeof(subservice.SubService), new Uri("someuri"));
If configuring the service in .svc then:
<%#ServiceHost Service="subservice.SubService"%>
Also in you config file, change service name to the service instead of the service contract as:
<services>
<service name="subservice.SubService">
...
other search result also said very similar things to get rid of this problem.
i have no svc file for my wcf service. i have just one file where i have contract and service classes. i also have config file.
here i am giving the brief of my service code
namespace SageDataImportWCF
{
[ServiceContract]
public interface ISagePart
{
[OperationContract]
string SageInsertionProcess(string SQLConnectionString, string CountryCode);
// TODO: Add your service operations here
}
public class SagePartInsertion : ISagePart
{
public string SageInsertionProcess(string SQLConnectionString, string CountryCode)
{
}
}
}
here i am giving the code by which i am trying to run from win service
namespace SageDataImportWCF
{
public partial class SageDateInsertionService : ServiceBase
{
#region Local Variables
ServiceHost serviceHost;
#endregion
#region Constructor
public SageDateInsertionService()
{
InitializeComponent();
serviceHost = null;
ServiceName = "Sage DataInsertion Service";
}
#endregion
protected override void OnStart(string[] args)
{
string strAdrHTTP = "http://192.168.6.2:11000/SagePartInsertion";
if (serviceHost != null)
{
serviceHost.Close();
}
serviceHost = new ServiceHost(typeof(SageDataImportWCF.SagePartInsertion));
serviceHost.AddServiceEndpoint(typeof(SageDataImportWCF.ISagePart), new BasicHttpBinding(), strAdrHTTP);
ServiceMetadataBehavior behaviour = new ServiceMetadataBehavior();
behaviour.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(behaviour);
serviceHost.Open();
}
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
}
here is my config entry for wcf service
<configuration>
<system.serviceModel>
<services>
<service name="SageDataImportWCF.SagePartInsertion" behaviorConfiguration="SageBehavior">
<endpoint address="http://localhost:9001/SagePartInsertion" contract="SageDataImportWCF.ISagePart" binding="basicHttpBinding"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="SageBehavior">
<!-- 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>
</configuration>
here i have pasted all the relevant code and i like to request some one please have a look at my code and tell me why i am getting the error message like ServiceHost only supports class service types when try to run it from windows service. did i miss anything in code ?
should i have a separate project for wcf class library and another separate project for windows service because i have one project there i have files for wcf & windows service both.
so looking for suggestion like what i need to rectify in code as a result win service can start the wcf service. please help.

Check the definition of the service in the Markup:
Right click on the SagePartInsertion.svc file and select "View Markup".
Make sure the service is the implementation of the interface, like this:
<%# ServiceHost Language="C#" Debug="true" Service="SageDataImportWCF.SagePartInsertion" CodeBehind="SagePartInsertion.svc.cs" %>
In the past it failed because I was referencing the interface.

Related

Not getting the expected results from WCF REST Service (Newbie)

I'm new to WCF Web Services. I'm trying to test my simple hello world web service.
For now, I'm doing self hosting. I'm at the point where I've started the host application, opened my browser and typed in the address to my resource. I've also run Fiddler and created a Request by using the Composer. In both cases, I get the "You have created a service." page that has a link to my .wsdl.
I was expecting to see the "Hello World" text in my Response or a web page that has "...Hello world".
What am I missing? or am I just misunderstanding the process?
App.Config
<?xml version="1.0"?>
<configuration>
<system.serviceModel>
<services>
<service name="My.Core.Services.GreetingService" behaviorConfiguration="MyServiceTypeBehaviors">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/greeting"/>
</baseAddresses>
</host>
<endpoint name="GreetingService" binding="webHttpBinding" contract="My.Core.Services.IGreetingService"/>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MyServiceTypeBehaviors" >
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>
Host code
using System;
using System.ServiceModel;
using My.Core.Services;
namespace My.Service.Host
{
class Program
{
static void Main(string[] args)
{
using (var host = new ServiceHost(typeof(GreetingService)))
{
host.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
host.Close();
}
}
}
}
Hello World Contract and Service
using System.ServiceModel;
using System.ServiceModel.Web;
namespace My.Core.Services
{
[ServiceContract]
public interface IGreetingService
{
[OperationContract]
[WebGet(UriTemplate = "/")]
string GetGreeting();
}
}
using System.Collections.Generic;
namespace My.Core.Services
{
public class GreetingService : IGreetingService
{
public string GetGreeting()
{
return "Greeting...Hello World";
}
}
}
If I understand you correctly, you can see your wsdl link at the following url
http://localhost:8080/greeting
In order to now call your endpoint, you need to add it to the url like this
http://localhost:8080/greeting/GetGreeting/
I'm not entirely sure why you have the UriTemplate thing in there though other than my guessing that you probably just copy pasted it from an example. Unless you have specific query string parameters that you want defined, you don't really need it and it kind of tends to complicate things so I'd recommend taking it out. That means your Interface would look something like this...
[ServiceContract]
public interface IGreetingService
{
[OperationContract]
[WebGet]
string GetGreeting();
}
...and you can then lose the final "/" on the url.
I figure out the problem. When I use the url: "http://localhost:8080/greeting" the server sends the temp page. When I add the backslash "/" on the end of the url it execute my service.
so, "http://localhost:8080/greeting/" works and sends me the "...Hello World" back.

Edit System.Servicemodel values programmatically?

When using WCF, there is a section in the web.config as below.
<system.serviceModel>
<services>
<service name="abc">
<endpoint /> <---this
</service>
</services>
</system.serviceModel>
Is it possible to edit the area I've marked programmatically?
I can see there is a sytem.serviceModel namespace, but other than that I'm a bit lost.
If you want to change these parameters at runtime you can override ServiceHost.OnOpening()
E.g. to change port:
protected override void OnOpening()
{
foreach (ServiceEndpoint endpoint in Description.Endpoints)
{
string uriString = string.Format("{0}://{1}:{2}{3}",
endpoint.Address.Uri.Scheme,
endpoint.Address.Uri.Host,
endpoint.Address.Uri.Port + _basePort,
endpoint.Address.Uri.LocalPath);
endpoint.Address = new EndpointAddress(uriString);
}
base.OnOpening();
}
To complement Mike Mozhaev's answer, since your service is hosted in IIS you'll need a ServiceHostFactory to get a reference to the service host (or to use your own host). There's some information about it at http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/14/wcf-extensibility-servicehostfactory.aspx.

WCF, MVC2, obtaining access to auto generated WSDL and working through default endpoint not found issues

I’m trying to run a very basic web service on the same IIS7 website that runs a MVC2 application. This is presenting a couple of different issues, and I believe it has to do with my system.serviceModel, but obviously I don’t know for sure (or I would fix it).
On the server side I can run my service just fine, the help operation works like a charm. I can execute the default WCF operation GetData and supply a value through the FireFox address bar.
http://localhost/services/service1/getdata?value=3 (example)
The first problem I’m having is that when I navigate to the base service URI it will display the message below. While this isn’t the end of the world because I can still execute code by manipulating the address; I do expect something else to be displayed. I expect the standard new web service message explaining that by appending “?wsdl” to the address you will receive the auto generated WSDL. I cannot access my auto generated WSDL.
“Endpoint not found. Please see the
service help page for constructing
valid requests to the service.”
Problem number two is in regard to client applications connecting to my web service. I created a console application in separate Visual Studio solution and added a web service reference to Service1. In the Visual Studio tool I can see and use the two methods that exist in my service, but when I run the code I get the following exception.
InvalidOperationException Could not
find default endpoint element that
references contract
'ServiceReference1.IService1' in the
ServiceModel client configuration
section. This might be because no
configuration file was found for your
application, or because no endpoint
element matching this contract could
be found in the client element.
Before I post my code (I’m sure readers are tired of reading about my struggles) I do want to mention that I’ve been able to run a WCF Service Library and Console application in the same solution flawlessly. There seems to be very few resources explaining WCF, WCF configuration, and working with MVC. I’ve read through several articles and either they were out-of-date or they were so simplistic they were nearly useless (e.g. click button receive web service named “Service1”).
To summarize; why am I not able to access the auto generated WSDL and how can I successfully connect my client and use the web service? Now the best part; the code.
Global.asax
//Services section
routes.Add(new ServiceRoute("services/service1", new WebServiceHostFactory(), typeof(Service1)));
Web.Config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="DefaultEndpoint" helpEnabled="true" automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
<mexEndpoint />
</standardEndpoints>
<services>
<service name="Project.Services.Service1" behaviorConfiguration="MetadataBehavior">
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint endpointConfiguration="DefaultEndpoint" kind="webHttpEndpoint" binding="webHttpBinding" contract="Project.Services.IService1" />
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MetadataBehavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="false" /> <!-- httpGetEnabled="true" does not solve the problem either -->
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
IService1
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET")]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
Service1
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
}
Client Program
class Program
{
static void Main(string[] args) {
Service1Client client = new Service1Client();
client.GetData(2);
}
}
Thanks for the help! The problem was inside of my Global.asax.cs.
Original:
routes.Add(new ServiceRoute("services/service1", new WebServiceHostFactory(), typeof(Service1)));
New:
routes.Add(new ServiceRoute("services/service1", new ServiceHostFactory(), typeof(Service1)));
The difference was chaing the host factory from "WebServiceHostFactory" to "ServiceHostFactory".
The second part of my question regarding client connections is because configuration settings are not being generated. I have to manually type them for each client. Yikes!
To avoid manually typing client configuration I had to change my endpoint
Original
<endpoint endpointConfiguration="DefaultEndpoint" kind="webHttpEndpoint" binding="webHttpBinding" contract="Project.Services.IService1" />
New
<endpoint binding="wsHttpBinding" contract="Project.Services.IService1" />
After making this change the service and client are working flawlessly.
A quick answer to one of your questions:
To summarize; why am I not able to
access the auto generated WSDL
<serviceMetadata httpGetEnabled="false" />
...needs to be
<serviceMetadata httpGetEnabled="true" />
...in order to be able to retrieve the WSDL over http. You have to tell WCF to generate service metadata, and you've told it not to.

Easy way to startup NHibernate in a WCF project

I'd like to use an NHibernate startup module for my WCF project like the one I use for my ASP.NET MVC projects. Jeffery Palermo outlines the startup module that I use in his post ASP.NET MVC HttpModule Registration. Essentially the code boils down to adding a startup module in the web.config that looks like this:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="StartupModule" type="Infrastructure.NHibernateModule, Infrastructure, Version=1.0.0.0, Culture=neutral" />
</modules>
</system.webServer>
This is not working when I try to run the service with the WCF Test Client or directly against the endpoint with SoapUI. What are my options for a simple startup mechanism for NHibernate in a WCF project?
You can resolve the issue by using a Message Inspector. On your NHibernateModule implement IDispatchMessageInspector. This will allow you to open your NHibernate session as each request is received and close it right before your reply is sent out.
Palermo's demo indicates that you will have extended IHttpModule. If that is the case, you will add two methods for the IDispatchMessageInspector interface:
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
context_BeginRequest(null, null);
return null;
}
and
public void BeforeSendReply(ref Message reply, object correlationState)
{
context_EndRequest(null, null);
}
This will implement the new interface using your old code. You will also need to implement the IServiceBehavior interface. This will allow you to use the module on a behavior extension in your web.config. The IServiceBehavior requires three methods, only one will actually do anything:
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher cd in serviceHostBase.ChannelDispatchers)
{
foreach (EndpointDispatcher ed in cd.Endpoints)
{
ed.DispatchRuntime.MessageInspectors.Add(this);
}
}
}
This will add your new inspector to each of the endpoints.
You will then have to add a BehaviorExtensionElement. This BehaviorExtensionElement should return the type and a new instance of your NHibernateModule. This will allow you to create a new behavior that returns the NHibernateModule in your web.config.
public class NHibernateWcfBehaviorExtension : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof(NHibernateModule); }
}
protected override object CreateBehavior()
{
return new NHibernateModule();
}
}
Now you have all the pieces in order, you can use them in your web.config. To apply them to all services your web.config should look like the following.
<system.serviceModel>
<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"/>
<NHibernateSessionStarter />
</behavior>
</serviceBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="NHibernateSessionStarter" type="Infrastructure.NHibernateWcfBehaviorExtension, Infrastructure, Version=1.0.0.0, Culture=neutral" />
</behaviorExtensions>
</extensions>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

BadImageFormatException IIS hosted WCF service Win7 x86, VS2010b2

My system is Windows 7 Ultimate 32 bit. Running Visual Studio 2010 beta 2 targeting .Net 4.
I have a project containing service contracts.
A project containing the services.
And an ASP.NET Web Application that is hosting the services in IIS.
I've written my own Clients using the ChannelFactory().CreateChannel()...
Whenever I run my application that uses the ServiceClient and calls a method on the service, I get this error:
An attempt was made to load a program with an incorrect format.
(Exception from HRESULT: 0x8007000B)
I've tried to add a service reference in VS, so that the service client is auto-generated and that doesn't change anything.
Then I tried to create a new WCF Service Application from the Web category in VS2010, adding a service reference and calling the standard GetData method That works fine, so it is for sure my service or the hosting of the service that goes wrong...
UPDATE
I noticed that this error was only present when using wsHttpBindings. basicHttpBindings works fine.
This is how I instantiate the service:
private IAdminService _AdminService;
public AdminServiceClient()
{
_AdminService = new ChannelFactory<IAdminService>(String.Empty)
.CreateChannel();
}
Client config settings:
<system.serviceModel>
<client>
<endpoint address="http://AdminServices/svcs/AdminService.svc"
binding="wsHttpBinding"
contract="MyApp.Admin.Model.ServiceContracts.IAdminService" />
</client>
</system.serviceModel>
My service looks like this:
public class AdminService : IAdminService
{
public User GetUserByEmail(string email)
{
throw new NotImplementedException();
}
public void CreateUser(string fullname, string email,
string encryptedPassword,
string encryptedPasswordQuestion,
string encryptedPasswordAnswer)
{
throw new NotImplementedException();
}
public IEnumerable<Application> GetApplications()
{
IEnumerable<Application> apps = new List<Application>();
// Call data access layer method to retrieve Applications
return apps;
}
public IEnumerable<ApplicationInstance> GetApplicationInstances(
long? applicationId)
{
throw new NotImplementedException();
}
public Dictionary<string, string> GetApplicationsAndInstances()
{
Dictionary<string, string> appsAndInstances =
new Dictionary<string, string>();
appsAndInstances.Add("Dummy 1", "1");
appsAndInstances.Add("Dummy 2", "2");
return appsAndInstances;
}
}
My AdminService.svc file looks like this:
<%# ServiceHost Service="MyApp.Admin.Services.AdminService" %>
My Service Host config looks like this:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true"
targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="MyApp.Admin.Services.AdminService">
<endpoint address=""
binding="wsHttpBinding"
contract="MyApp.Admin.Model.ServiceContracts.IAdminService" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
I've also tried to create a new Console App, and add a service reference to http://AdminServices/svcs/AdminService.svc - that doesn't work either.
I've added AdminServices to my hosts file, and I can browse http://AdminServices/svcs/AdminService.svc and see the service information...
The most obvious cause would be that you are loading a 64 bits DLL into a 32 bits process or visa versa. However given that you are running everything on a a 32 bits development box I assume this isn't the case.
The other option is a .NET bug using a generic constraint like this:
public class SpecificClass: BaseClass: where T : class { }
If you remove the where T : class it should work just fine.