How can I Create this configuration programmatically? - c#

I have an WCF and I'm needing to create this configuration dinamically because my
app.config never changes in client machines.
Any body help?
<behaviors>
<endpointBehaviors>
<!-- REST -->
<behavior name="restBehavior">
<webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Wrapped"/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="defaultBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<client>
<endpoint name="json" address="http://localhost:8080/json"
binding="webHttpBinding"
bindingConfiguration="webBinding"
behaviorConfiguration="restBehavior"
contract="ServiceReference.ServiceClientContract" />
</client>

Most WCF elements in the config file have a corresponding class or property that can be set in code (which is presumably what you meant by "dynamically"?) For example, 'endpointBehaviors' can be accessed through the Behaviors property of the ServiceEndpoint class:
Uri baseAddress = new Uri("http://localhost:8001/Simple");
ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress);
ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(
typeof(ICalculator),
new WSHttpBinding(),
"CalculatorServiceObject");
endpoint.Behaviors.Add(new MyEndpointBehavior());
Console.WriteLine("List all behaviors:");
foreach (IEndpointBehavior behavior in endpoint.Behaviors)
{
Console.WriteLine("Behavior: {0}", behavior.ToString());
}
http://msdn.microsoft.com/en-us/library/system.servicemodel.description.serviceendpoint.behaviors.aspx
Searching any of the elements your are interested in configuring in MSDN should be enough to get you started.

Related

WCF REST Endpoint

I am developing a WCF and I want it to be called by both ways SOAP/REST.
Now I am able to get response by SOAP but unable to call the same WCF by JSON request.
IService1.cs
[OperationContract]
[FaultContract(typeof(CustomException))]
[WebInvoke(Method = "POST", UriTemplate = "/Validateuser",
RequestFormat = WebMessageFormat.Xml | WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Xml | WebMessageFormat.Json)]
ResponsetoCustomer Validateuser(ValidateCustomerInput validate);
Web.config
<system.serviceModel>
<services>
<service name="TractorMitraIntegration.IService1" behaviorConfiguration="ServBehave">
<!--Endpoint for SOAP-->
<endpoint
address="soapService"
binding="basicHttpBinding"
contract="TractorMitraIntegration.IService1"/>
<!--Endpoint for REST-->
<endpoint
address="XMLService"
binding="webHttpBinding"
behaviorConfiguration="restPoxBehavior"
contract="TractorMitraIntegration.IService1"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServBehave">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
<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"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<!--Behavior for the REST endpoint for Help enability-->
<behavior name="restPoxBehavior">
<webHttp helpEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
Below error I am facing,
Cannot process the message because the content type 'application/json' was not the expected type 'text/xml; charset=utf-8'
Please help!
You probably need defaultOutgoingResponseFormat="Json":
<behavior name="restPoxBehavior">
<webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json" />
</behavior>
You cannot support both soap and rest for the same endpoint.
See this REST / SOAP endpoints for a WCF service for how to.

WCF service inside a Web application is not working through RESTCLIENT?

I have added a RESTful WCF service inside a Web application(Righclicked solution and added WCF service) and while running it is exposing the url as svcutil.exe http://localhost:62783/Service1.svc?wsdl but i have tried calling that service UriTemplate from a RESTCLIENT like http://localhost:62783/AuthenticateUser it is throwing an error like
HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
But if i create a seperate RESTful WCF service and calling from a RESTCLIENT is working fine.Here is my code
[OperationContract]
string AuthenticateUser1();
and
[WebInvoke(UriTemplate = "/AuthenticateUser", Method = "GET", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
public string AuthenticateUser1()
{
return string.Format("Token {0}", new Guid().ToString());
}
and config
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Any suggestion??
Based on your posted config, you have a default endpoint for SOAP of basicHttpBinding, which is (by default) mapped to the http scheme. I've done very little with REST, but I believe you will need to add an endpoint using webHttpBinding to do REST, and most likely the URL will need to be http://localhost:62783/Service1.svc/AuthenticateUser (note the inclusion of the service file), though I'm not 100% sure on that one.
To add a REST endpoint, do something like this in your service's config file:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
<!-- Added for REST -->
<endpointBehaviors>
<behavior name="REST">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<!-- REST endpoint -->
<endpoint address="" binding="webHttpBinding"
contract="<contract name with namespace>"
behaviorConfiguration="REST">
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
Again, REST is not my strong point, but this should hopefully get you pointed in the right direction at least.

WCF multiple services same contract in same Config

Im trying to host to different service implementations of the same contract:
The reason is that need a dummy implementation for out-of-the-house testing.
Im trying to host both in the same WindowsService:
private ServiceHost _host;
private ServiceHost _dummy;
protected override void OnStart(string[] args)
{
_host = new ServiceHost(typeof(Service));
_host.Open();
//trying to avoid the app.config beeing used - because its already been hoste by _host
_dummy = new ServiceHost(typeof(TestDummyService));
_dummy.Description.Endpoints.Clear();
_dummy.AddServiceEndpoint(typeof(IService),
new WebHttpBinding(),
#"<link>/Dummy.svc/");
_dummy.ChannelDispatchers.Clear();
_dummy.Open();
}
This is the config file:
<system.serviceModel>
<services>
<service name="namespace.Service">
<host>
<baseAddresses>
<add baseAddress="<link>/Service.svc"/>
</baseAddresses>
</host>
<endpoint address=""
binding="webHttpBinding"
contract="namespace.IService"
behaviorConfiguration="web" />
<endpoint address="/mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors >
<behavior>
<serviceMetadata httpGetEnabled="true"
httpGetUrl="<link>/Service.svc/About" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name ="web">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
The ChannelDispatcher at /Service.svc/About with Contracts ‘IHttpGetHelpPageAndMetadataContract’ is unable to open.
any help is appreciated.
Update 1
My goal is to have 2 different implementations of the same contract (IService) hosted in one WindowsService.
I would also like to configure both of them in the config file.
Well i would like to know what's the business scenario. All I guess is, the client should not know the implementation, its just the URL of the service would indicate (or route) to the implementation.
Kindly clarify.
Refer to this existing post and let
me know if it makes sense.
The above post is hinting the implementation, refer to this post for deployment details.
so i found out, that even thow the testdummy service was added programatic, it still got the service metadatabehavior.
My solution was to not make the dehavior default - given it at name:
app.config:
<service name="namespace.Service" behaviorConfiguration="someName">
//.. later:
<behavior name="someName">
<serviceMetadata httpGetEnabled="true"
httpGetUrl="<link>/Service.svc/About" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
The rest of the code, statyed the same
Can't you add another endpoint and fill in the adress with a distinct name:
<endpoint address="/SecondService"
binding="webHttpBinding2"
contract="namespace.IService"
/>
Url becomes /Service.svc/SecondService

WCF anything in the endPointBehavior cancels the metaData exposure?

This is my web.config file:
<bindings>
<basicHttpBinding>
<binding
name="ExtremeBinding"
maxBufferSize="12354000"
maxReceivedMessageSize="12354000" />
</basicHttpBinding>
</bindings>
<services>
<service name="WcfService3.Service1" behaviorConfiguration="myServiceBehaviour">
<endpoint
address=""
binding="basicHttpBinding"
bindingConfiguration="ExtremeBinding"
contract="WcfService3.IService1"
behaviorConfiguration="epBehavior"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="epBehavior">
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="myServiceBehaviour">
<!-- 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" />
If I keep it like this, and run the WCF Test Client, everything works fine.
But if I add anything to the endPoint Behavior, for example:
<behavior name="epBehavior">
<callbackDebug includeExceptionDetailInFaults="true"/>
</behavior>
the WCF Test Client fails with the Error:
Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.
It seems as though it doesn't matter what I put within the . For example:
<behavior name="epBehavior">
<webHttp/>
</behavior>
It's clear to me that I missing something fundamental, but I can't figure what it is.
Thank you very much.
I don't know the exact reason why this happens, but I think you can fix this by adding a serviceMetadata behavior:
<behaviors>
<serviceBehaviors>
<behavior name="NewBehavior">
<serviceMetadata httpsGetEnabled="true"
httpsGetUrl="https://myComputerName/myEndpoint" />
</behavior>
</serviceBehaviors>
</behaviors>
This is from:
http://msdn.microsoft.com/en-us/library/ms731317.aspx

provided URI scheme'http' is invalid; expected 'https'

I have a RESTful Web Service hosted in IIS 6.0, I am able to Browse the Service in browser. When i am trying to access the same service via Client console App, it is giving me the following error:
"provided URI scheme'http' is invalid; expected 'https', Parameter name: Via"
My WebService web.config has this settings:
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="TestAPI">
<endpoint address="" behaviorConfiguration="RESTFriendly" binding="webHttpBinding" contract="ITestAPI" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="RESTFriendly">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
My Client App has App.config from where i am getting the address :
<appSettings>
<add key="WEBSERVICE" value="URL"/>
in the Main method :
WebChannelFactory<ITestAPI> cf = new WebChannelFactory<IAPI>(baseAddress);
WebHttpBinding wb =cf.Endpoint.Binding as WebHttpBinding;
wb.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
wb.Security.Mode = WebHttpSecurityMode.Transport;
cf.Credentials.UserName.UserName = "usermane";
cf.Credentials.UserName.Password = "password";
ITestAPI channel = cf.CreateChannel();
string msg = channel.TestMethod();
When it tries to call TestMethod, it gives me this error.
You're setting the security to transport mode, which is HTTPS, with this line:
wb.Security.Mode = WebHttpSecurityMode.Transport;
Is the value of baseAddress an HTTP or HTTPS address?

Categories

Resources