Error connecting Java App to WCF web service - c#

I've written a simple Java Console Application in Eclipse that references a WCF web service written in C#. Hosting the WCF service locally on my PC, I'm unable to connect to the service using the java client.
The steps I've taken to create the WCF Service are as follows
Create a 'Service1.svc' with the following endpoint:
string IService1.Hello(string sName)
{
return "Hello " + sName + "!" ;
}
The web config for the service is as follows:
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding" />
</basicHttpBinding>
</bindings>
<client>
<endpoint binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding"
contract="WcfService1.IService1" name="BasicHttpEndpoint" />
</client>
<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"/>
I modified the properties so the service will always use port 8888.
I've tested the service using a C# console application.
To Create the Java client, I did the following:
Download and install Glassfish 3.0.1 (Application server) which come bundled with Metro (Web Server)
Use the 'wsimport' tool in the 'bin'directory of my jdk to generate the service reference code for the java client app. The .bat file that I ran to create the service reference
Copy the code from step 2. above into a new Java Application in Eclipse.
Create a new Java class in my console app which calls the web service as follows
`
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import org.tempuri.Service1;
import org.tempuri.IService1;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
try {
Service1 service = new Service1(new URL("http://localhost:8888/Service1.svc?wsdl"), new QName("http://tempuri.org", "Service1"));
IService1 port = service.getBasicHttpBindingIService1();
((BindingProvider)port).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8888/Service1.svc");
String sFileName = port.hello("Cal");
System.out.println(sFileName);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.printStackTrace();
}
}
}
`
The error I'm getting when I attempt to run my application is as follows:
Exception in thread "main" javax.xml.ws.WebServiceException: {http://tempuri.org}Service1 is not a valid service. Valid services are: {http://tempuri.org/}Service1
at com.sun.xml.ws.client.WSServiceDelegate.(WSServiceDelegate.java:237)
at com.sun.xml.ws.client.WSServiceDelegate.(WSServiceDelegate.java:182)
at com.sun.xml.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:106)
at javax.xml.ws.Service.(Unknown Source)
at org.tempuri.Service1.(Service1.java:42)
at Main.main(Main.java:17)
Any assistance with this is appreciated. Thanks.

change:
new QName("http://tempuri.org", "Service1")
to:
new QName("http://tempuri.org/", "Service1")
notice the extra "/" after org.

Related

Server Error in '/' Application. The resource cannot be found. (404) when deploying WCF service to Azure App Service

I am creating a WCF service to store some data in a Xamarin.Forms application I am making. I have deployed this service to an Azure App Service. I am getting the following error when navigating to the URL:
Server Error in '/' Application.
The resource cannot be found.
Description: 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.
Requested URL: /EventWCFService.svc
Code-behind of the WCF service:
public class EventWCFService : IEventWCFService
{
private static IEventService _eventService = new EventService(new EventRepository());
public void AddEvent(Event #event)
{
try
{
if (String.IsNullOrWhiteSpace(#event.EventTitle) || #event == null)
{
throw new FaultException("Event name is required");
}
_eventService.AddEvent(#event);
}
catch (Exception exception)
{
throw new FaultException($"Whoops... Something has gone wrong {exception.Message}");
}
}
public IList<Event> GetAllEvents()
{
return _eventService.GetAllEvents();
}
}
My WCF project also contains repositories and services:
IEventWCFService:
[ServiceContract]
public interface IEventWCFService
{
[OperationContract]
IList<Event> GetAllEvents();
[OperationContract]
void AddEvent(Event #event);
}
Web.Config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8"/>
</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="false"/>
</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>
Things I've tried:
First of all I tried to go to the properties and create a virtual directory - that did not work or solve the problem.
I tried to set the 'Specific page' to blank - it still did not solve the problem.
I tried to create a new app service - and I still got the problem.
I am quite new to WCF - so apologies if this may be a rookie mistake. I am a following a Pluralsight course and I was getting along quite well until the Azure deployment part.
I solved this problem by creating and deploying a new Azure App Service directly from the Azure portal rather than from Visual Studio itself. Then - I deployed the WCF service directly from the existing app service that I had just created.

host service in console application

Dears,
I host WCF sevice in console application but when explore it in browser using the following url
http://localhost:8000/GettingStarted/CalculatorService i get error
"Service Unavailable
HTTP - Error 503. The service is unavailable."
the following is console application code which host the service
class Program
{
static void Main(string[] args)
{
// Step1: Create URI to serve as the base address
Uri baseAddress = new Uri("http://localhost:8000/GettingStarted");
// Step2: Create service host instance
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);
try
{
// Step 3: Add service endpoint
selfHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "CalculatorService");
// Enable Metadata exchange
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
// Starts the service
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (CommunicationException ex)
{
Console.WriteLine("An exception occurred: {0}", ex.Message);
selfHost.Abort();
}
}
}
and this is app.config in service
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service name="GettingStartedLib.CalculatorService">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8000/GettingStarted/CalculatorService" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint address="" binding="wsHttpBinding" contract="GettingStartedLib.ICalculator">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- 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>
<!-- 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>
</behaviors>
</system.serviceModel>
</configuration>
so what is the problem ?
If you want to access the web service description language(wsdl) over http, you should type the http metadata address in the browser address bar instead of service endpoint address.
http://localhost:8000/GettingStarted
you could specify the address in the HttpGetUrl property, whose value is service base address by default.
smb.HttpGetUrl = new Uri("http://localhost:9000");
Feel free to let me know if there is anything I can help with.

WCF config file 413-request-entity-too-large

i have read multiple similar threads but still don't know what to do.
I've created simple WCF service which is getting some xml data (in strings)
Everything was working fine until project was running on windows 7.
Now, when i try to send data from client to WCF service i get exception
413-request-entity-too-large
i've tried to add these two parameters to my web.config on WCF service
maxBufferSize="2147483647"
maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
Can someone please look at my config and try to help me ?
WCF service code:
public class Service1 : IService1
{
public static Konfiguracja config;
public static DBqueries queries;
public void WczytajKonfiguracje()
{
config = new Konfiguracja();
queries = new DBqueries();
}
public bool? DodajInfoSprzet(int idKlienta, string haslo, int id_zgloszenia, string HardwareInfoXML, string SoftInfoXML)
{
...and some code
}
}
and here is my wcf web.config file:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ProjektSerwisConnectionString" connectionString="Data Source=.\sql12;Initial Catalog=ProjektSerwis;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1"/>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647" />
</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="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0" />
</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>
(i've edited it by visual studio context menu on file web.config)
WCF service has been running by
namespace SelfService
{
class Program
{
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:55555/WcfStart/");
ServiceHost selfHost = new ServiceHost(typeof(Service1), baseAddress);
try {
selfHost.AddServiceEndpoint(typeof(IService1), new WSHttpBinding(), "WmiService");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
selfHost.Open();
while(true)
{
Console.WriteLine("Usługa działa");
Console.WriteLine("Wpisz quit aby zakończyć działanie");
string command = string.Empty;
command=Console.ReadLine();
if (String.Equals(command.ToLower(), "quit".ToLower()))
break;
}
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
}
}
}
and client has just references to web service and connect it by :
Service1Client scl = new Service1Client();
bool? ok = false;
try
{
ok = scl.DodajInfoSprzet(IdKlienta, haslo, IdZgloszenia, HardwareInfoXML, SoftInfoXml);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
i konw that i have pasted a lot of code, but i have no idea what to do with my web.config file
the data which is being sending is not big, it is less than 1 MB
Did you just put this configuration in the web.config?
Since you're hosting your WCF as a console application you have to make the configuration in the App.config of the hosting application.

How to make my CustomUserNamePasswordValidator work

I have been trying to get this working for hours now and have not had any luck. I am trying to create a WCF web service that has validation. I want the consumer of the service to be required to do:
ServiceReference1.XServiceClient client = new ServiceReference1.XServiceClient();
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
before he can call any of the service methods. I found out that I have to create a CustomUserNamePasswordValidator so I created class library project in the solution to contain the Custom Validator class. I just wanted to verify that it works.
namespace XServices
{
public class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string username, string password)
{
if (!(username == "test" && password == "password"))
{
throw new FaultException("Invalid username or password!");
}
}
}
}
Then I tried to make the necessary changes to my web.config file in the WCF project to support it. Unfortunately, this is where I had my first trouble.
Here is my web.config file as it is now.
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<!-- connection strings ommitted for security reasons -->
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off"/>
</system.web>
<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"/>
</behavior>
<behavior name="CustomValidator">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomUserNameValidator.XServices.CustomUserNameValidator, CustomUserNameValidator"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="Binding1">
<security mode="Message">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
The MSDN docs are very unclear on how the customUserNamePasswordValidatorType works. The example https://msdn.microsoft.com/en-us/library/aa702565(v=vs.110).aspx completely glosses over it so I have no idea if I even did it correctly. And worse, it does not throw an error if what you put for that parameter is incorrect. It just silently ignores it. Long story short, the Validate method of my custom validator is not being called. I can't figure out why and I haven't found anything that has worked after hours of google searching. Please help.
In your service config, you forgot to associate the serviceBehavior with your service. Therefore your service don't know anything about your custom validator.
The following section is missing:
<services>
<service behaviorConfiguration="CustomValidator" name="ServiceName...">
<endpoint name="EndpointName..." bindingConfiguration="Binding1" address="..." binding="wsHttpBinding" contract="..." />
</service>
</services>

i am running wcf service not working on iis

I am working on wcf first time so created just sinple wcf ,problem is when i run service from visual studio its working fine but when i deploy it on iis it giving HTTTP 500 Error
my web config file is as below
<?xml version="1.0"?>
<configuration>
<appSettings/>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
<pages controlRenderingCompatibilityVersion="4.0"/>
</system.web>
<system.serviceModel>
<services>
<service name="WcfService2.Service1" behaviorConfiguration="servicebehavior">
<endpoint address="" binding="webHttpBinding" contract="WcfService2.IService1" behaviorConfiguration="web"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="servicebehavior">
<!-- 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 name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" 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>
and svc file is as below
namespace WcfService2
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IService1
{
public string JSONData(string id)
{
return "you requested prduct" + id ;
}
public void DoWork()
{
}
}
}
and interface is as below
namespace WcfService2
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/json/{id}")]
string JSONData(string id);
void DoWork();
}
}
https://stackoverflow.com/a/11460220/2211593
my iis server was not having feature of HTTP activation enabled so after lot of googling i found this solution. very useful for me i spent almost half of day to find the solution of this small issue

Categories

Resources