How to make configuration from an xml file for WCF service - c#

I am new here. I want create a WCF WebService using Visual Studio and use it in Xamarin Forms application. This is my ultimate goal. Now I created WCF Service project and starts IIS service on my Mac machine(Windows 8 OS). But When I run the code already given in project to check whether things are alright or not, I am getting following error :
Failed to add a service. Service metadata may not be accessible. Make
sure your service is running and exposing metadata.
My Web.config file is as below :
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
</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>
Service.svc file :
<%# ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>
Service.cs file :
public class Service : IService
{
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;
}
}

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.

Unable to invoke method declared in WCF Service

I have created the WCF service and consumed that service into my client side application and I'm unable to invoke the method.
the following exception is occured:
{"The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs."}
I think there is the some issue with the binding. I had googled but didn't find any solution. Please guide me how can I fix this issue. Help will be appreciate.
Thanks
Code Snippet:
Service Web.Config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</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>
Index.aspx
private void process()
{
TestRef.EmployeeDC o = new TestRef.EmployeeDC();
o.userID = signInEmail;
o.companyID = signInPassword;
//ServiceReference.EmployeeDC p = new ServiceReference.EmployeeDC();
//Service Call
TestRef.TestServClient tsc = new TestRef.TestServClient();
tsc.callBusinessLayer(o); // here im getting the exception
Debug.Print(""+signInEmail);
}
Client Side Web.Config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_ITestServ" />
<binding name="BasicHttpBinding_ITestServ1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost/Publish/TestServ.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_ITestServ" contract="ServiceReference.ITestServ"
name="BasicHttpBinding_ITestServ" />
<endpoint address="http://localhost/Publish/TestServ.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_ITestServ1" contract="TestRef.ITestServ"
name="BasicHttpBinding_ITestServ1" />
</client>
</system.serviceModel>
</configuration>

WCF Webservice - Failed to invoke the service. The service is offline or inaccessible

We have developed the wcf service,when we are calling web service from WCF Test Client to fetch the data, In this case we are getting some exception while calling the WCF web service. I want to log error into html file.
My Code:-
try
{
int i = 1;
int j = 0;
int k = i / j;
}
catch (Exception ex)
{
ApplicationError.LogErrors(ex);
}
Web Config :-
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
</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>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<handlers>
<remove name="ISAPI-dll"/>
<add name="ISAPI-dll" path="*.dll" verb="*" modules="IsapiModule" scriptProcessor="C:\WINDOWS\System32\inetsrv\asp.dll" resourceType="File" requireAccess="None" allowPathInfo="true" preCondition="bitness64"/>
</handlers>
<directoryBrowse enabled="false"/>
</system.webServer>
Error :-
You can't log directly from WCF into HTML (or rather, you could but shouldn't).
What you could rather do is throw a FaultException with an appropriate message and have your ASP.NET page handle the Exception and render an HTML page with the appropriate Exception.Message (I prefer Exception.ToString() ) in it.
For more information have a look at this link: Fault Handling in WCF Services

WCF recieves a complex object as null

After getting input in another thread here on the forum [StackOverFlow][1]
[1]: Getting a nullreference when passing a complex object from KSOAP2 to WCF have i reached conclusion that my problem is with the WCF service itself. It seems that the service is not able to understand the object that it's receiving.
No matter what I do the object passed is always null.
I have even tried declaring the datamember explicit even though it should not be necessary in the current version of WCF.
Here's the class I'm trying to pass through the WCF:
namespace ModelLayer
{
[DataContract]
public class User
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Mac { get; set; }
public User()
{
}
}
}
My service interface:
[ServiceContract (Namespace = "http://nordahl.org/")]
public interface IWcfFoodAndAllergi
{
[OperationContract]
int InsertUser(User _user);
[OperationContract]
User GetUser(string _mac);
[OperationContract]
int InsertRecipe(Recipe _recipe);
[OperationContract]
List<Recipe> GetRecipeByAllergi(List<Allergies> _allergies);
[OperationContract]
List<Recipe> GetRecipeByType(string _type);
[OperationContract]
List<Recipe> GetRecipeByName(string _name);
}
}
And lastly the webconfig file itself:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="1048576"/>
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
<fileExtensions allowUnlisted="true">
<remove fileExtension=".cs"/>
<add fileExtension=".cs" allowed="true"/>
</fileExtensions>
</requestFiltering>
</security>
</system.webServer>
<system.serviceModel>
<services>
<service name="WcfFoodAndAllergi.WcfFoodAndAllergi">
<!-- Use a bindingNamespace to eliminate tempuri.org -->
<endpoint address=""
binding ="basicHttpBinding"
bindingNamespace="http://nordahl.org/"
contract="WcfFoodAndAllergi.IWcfFoodAndAllergi"
/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name ="">
<!-- 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>
I had a similar problem to yours when a complex object referenced another complex object in a T4 generated class. If you are using an include in an obtain method, or another method relating to Entity or objects linking complex objects to each other; you may get a circular reference error. I had a friend show me how to fix this with a custom class that sets up an attribute:
Complex Object won't return when using 'include' syntax in WCF with Entity Version 6

Configure WCF WebSite to support RESTful access from a browser

I have used VS2012 to create a new WCF website (Add->New Web Site->WCF Service).
'Out of the box' this gives me the following web.config file:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</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>
It also gives me an initial Service class as follows:
public class Service : IService
{
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;
}
}
I then F5 to start the project and it fires up a browser window listing the dir contents, including Service.svc.
I want to type in a URL to call the GetData method. What do I type into the browser address bar, and how to I configure and/or decorate the service so I can type a URL into the browser and see a JSON format string being returned?
Mark the Operation in your contract (IService interface) with following attribute - [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, UriTemplate="GetData/{id}")]
And then try invoking your service from browser by adding GetData/[any number]

Categories

Resources