Search Results

Search found 21 results on 1 pages for 'faultcontract'.

Page 1/1 | 1 

  • WCF : FaultContract(typeof(ExceptionDetail)) issue

    - by jitus
    I have put the attribute [FaultContract(typeof(ExceptionDetail))] for my operation contract. When I am trying to add the service th' a client app, I get this error - "Custom tool error: Failed to generate code for the service reference 'ServiceReference1'. Please check other error and warning messages for details." But when I comment out the FaultContract Attribute, I am able to add the wcf service reference th' my client app. Would appreciate if somebody can help me solve this mystery. Thanks

    Read the article

  • Using custom FaultContract object causes 'Add Service Reference' to fail

    - by SpoBo
    Hey, I just noticed something particular. I have an internal stock service which is published through basicHttpBinding, and a customBinding (http+binary) for which metadata is enabled. I also included a mex endpoint for http. We use Visual Studio 2008 & VB.NET Just recently we noticed that we were unable to succesfully add a service reference to this service in our other projects. All that it would generate was the first custom exception we included through a FaultContract (actually, there was only 1 type). if I'd add a simple web reference it would work correctly as well. Also, the WcfClient.exe had no problems either in loading the services. Just VS.NET add service reference wouldn't work. In the service this exception inherits from Exception and is marked as serializable. That's all you're supposed to do, no? Anyway, this had me baffled. If I remove the FaultContract for this custom exception everything works fine. I can add a service reference, no problem. But is there a way I can still have my custom exceptions? Is this a known problem? Thx!

    Read the article

  • WCF Webservices and FaultContract - Client's receiving SoapExc insted of FaultException<TDetails>

    - by Alessandro Di Lello
    Hi All, i'm developing a WCF Webservice and consuming it within a mvc2 application. My problem is that i'm using FaultContracts on my methods with a custom FaultDetail and i'm throwing manyally the faultexception but when the client receive the exception , it receives a normal SoapException instead of my FaultException that i throwed from the service side. Here is some code: Custom Fault Detail Class: [DataContract] public class MyFaultDetails { [DataMember] public string Message { get; set; } } Operation on service contract: [OperationContract] [FaultContract(typeof(MyFaultDetails))] void ThrowException(); Implementation: public void ThrowException() { var details = new MyFaultDetails { Message = "Exception Test" }; throw new FaultException<MyFaultDetails >(details , new FaultReason(details .Message), new FaultCode("MyFault")); } Client side: try { // Obv proxy init etc.. service.ThrowException(); } catch (FaultException<MyFaultDetails> ex) { // stuff } catch (Exception ex) { // stuff } What i expect is to catch the FaultException , instead that catch is skipped and the next catch is taken with an exception of type SoapException. Am i missing something ? i red a lot of threads about using faultcontracts within wcf and what i did seems to be good. I had a look at the wsdl and xsd generated and they look fine. here's a snippet regarding this method: <wsdl:operation name="ThrowException"> <wsdl:input wsaw:Action="http://tempuri.org/IAnyJobService/ThrowException" message="tns:IAnyJobService_ThrowException_InputMessage" /> <wsdl:output wsaw:Action="http://tempuri.org/IAnyJobService/ThrowExceptionResponse" message="tns:IAnyJobService_ThrowException_OutputMessage" /> <wsdl:fault wsaw:Action="http://tempuri.org/IAnyJobService/ThrowExceptionAnyJobServiceFaultExceptionFault" name="AnyJobServiceFaultExceptionFault" message="tns:IAnyJobService_ThrowException_AnyJobServiceFaultExceptionFault_FaultMessage" /> </wsdl:operation> <wsdl:operation name="ThrowException"> <soap:operation soapAction="http://tempuri.org/IAnyJobService/ThrowException" style="document" /> <wsdl:input> <soap:body use="literal" /> </wsdl:input> <wsdl:output> <soap:body use="literal" /> </wsdl:output> <wsdl:fault name="AnyJobServiceFaultExceptionFault"> <soap:fault use="literal" name="AnyJobServiceFaultExceptionFault" namespace="" /> </wsdl:fault> </wsdl:operation> Any help ? Thanks in advance Regards Alessandro

    Read the article

  • FaultException<T>() exception thrown by the service is not caught by the client catch(FaultException

    - by Ashish Gupta
    Ok, I know I am missing something here. I have the following operation contract: public double DivideByZero(int x, int y) { if (y == 0) { throw new FaultException<ArgumentException> (new ArgumentException("Just some dummy exception") ,new FaultReason("some very bogus reason"), new FaultCode("007")); } return x / y; } And following is taken from the client:- Console.WriteLine("Enter the x value"); string x = Console.ReadLine(); Console.WriteLine("Enter the Y value"); string y = Console.ReadLine(); try { double val = client.DivideByZero(Convert.ToInt32(x), Convert.ToInt32(y)); Console.WriteLine("The result is " + val.ToString()); } catch(FaultException<ArgumentException> exp) { Console.WriteLine("An ArgumentException was thrown by the service "+ exp.ToString()); } catch (Exception exp) { Console.WriteLine(exp.ToString()); } In the above case catch(FaultException exp) (the first catch block with ArgumentException in the client code) block does not get executed. However, when I remove ArgumentException to have catch(FaultException exp), the same catch block gets executed. I am not sure about this as I am throwing FaultException from my operation contract. Am I missing anything here. Appreciate your help, Ashish

    Read the article

  • What are the pros/cons to these 2 ways of defining parameters for a web service method

    - by Antony Scott
    I have an existing web service I need to expand, but it has not gone into production yet. So, I am free to change the contracts as I see fit. But I am not sure of the best way to define the methods. I am leaning towards Method 2 for no other reason than I cannot think of good names to give the parameters classes! Are there any major disadvantages to using Method 2 over Method 1? Method 1 [DataContract(Namespace = Constants.ServiceNamespace)] public class MyParameters { [DataMember(Order = 1, IsRequired = true)] public int CompanyID { get; set; } [DataMember(Order = 2, IsRequired = true)] public string Filter { get; set; } } [ServiceContract(Namespace = Constants.ServiceNamespace)] public interface IMyService { [OperationContract, FaultContract(MyServiceFault)] MyResult MyMethod(MyParameters params); } Method 2 public interface IMyService { [OperationContract, FaultContract(MyServiceFault)] MyResult MyMethod(int companyID, string filter); }

    Read the article

  • WCF JSON Service returns XML on Fault

    - by Anthony Johnston
    I am running a ServiceHost to test one of my services and all works fine until I throw a FaultException - bang I get XML not JSON my service contract - lovely /// <summary> /// <para>Get category by id</para> /// </summary> [OperationContract(AsyncPattern = true)] [FaultContract(typeof(CategoryNotFound))] [FaultContract(typeof(UnexpectedExceptionDetail))] IAsyncResult BeginCategoryById( CategoryByIdRequest request, AsyncCallback callback, object state); CategoryByIdResponse EndCategoryById(IAsyncResult result); Host Set-up - scrummy yum var host = new ServiceHost(serviceType, new Uri(serviceUrl)); host.AddServiceEndpoint( serviceContract, new WebHttpBinding(), "") .Behaviors.Add( new WebHttpBehavior { DefaultBodyStyle = WebMessageBodyStyle.Bare, DefaultOutgoingResponseFormat = WebMessageFormat.Json, FaultExceptionEnabled = true }); host.Open(); Here's the call - oo belly ache var request = WebRequest.Create(serviceUrl + "/" + serviceName); request.Method = "POST"; request.ContentType = "application/json; charset=utf-8"; request.ContentLength = 0; try { // receive response using (var response = request.GetResponse()) { var responseStream = response.GetResponseStream(); // convert back into referenced object for verification var deserialiser = new DataContractJsonSerializer(typeof (TResponseData)); return (TResponseData) deserialiser.ReadObject(responseStream); } } catch (WebException wex) { var response = wex.Response; using (var responseStream = response.GetResponseStream()) { // convert back into fault //var deserialiser = new DataContractJsonSerializer(typeof(FaultException<CategoryNotFound>)); //var fex = (FaultException<CategoryNotFound>)deserialiser.ReadObject(responseStream); var text = new StreamReader(responseStream).ReadToEnd(); var fex = new Exception(text, wex); Logger.Error(fex); throw fex; } } the text var contains the correct fault, but serialized as Xml What have I done wrong here?

    Read the article

  • WCF FaultContracts not working for Silverlight Client Proxy

    - by sarwara
    We have a Silverlight application client and a WCF Service hosted as Managed Window Service and exposing Service Contracts on BasicHttpBinding. We are sending FaultContract on the wire in case of exception is caught with the WCF Service Code. We are facing following problem as: A. If we have Synconized proxy call (in case of Window or Web Client), we are able to catch the Fault Contract. B. If we are using Silverlight Client which uses Asyncronized calls, we are unable to catch the Fault Contract. We need help on later problem (B.), Thanks in advance

    Read the article

  • Making WCF Output a single WSDL file for interop purposes.

    - by Glav
    By default, when WCF emits a WSDL definition for your services, it can often contain many links to others related schemas that need to be imported. For the most part, this is fine. WCF clients understand this type of schema without issue, and it conforms to the requisite standards as far as WSDL definitions go. However, some non Microsoft stacks will only work with a single WSDL file and require that all definitions for the service(s) (port types, messages, operation etc…) are contained within that single file. In other words, no external imports are supported. Some Java clients (to my working knowledge) have this limitation. This obviously presents a problem when trying to create services exposed for consumption and interop by these clients. Note: You can download the full source code for this sample from here To illustrate this point, lets say we have a simple service that looks like: Service Contract public interface IService1 { [OperationContract] [FaultContract(typeof(DataFault))] string GetData(DataModel1 model); [OperationContract] [FaultContract(typeof(DataFault))] string GetMoreData(DataModel2 model); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Service Implementation/Behaviour public class Service1 : IService1 { public string GetData(DataModel1 model) { return string.Format("Some Field was: {0} and another field was {1}", model.SomeField,model.AnotherField); } public string GetMoreData(DataModel2 model) { return string.Format("Name: {0}, age: {1}", model.Name, model.Age); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Configuration File <system.serviceModel> <services> <service name="SingleWSDL_WcfService.Service1" behaviorConfiguration="SingleWSDL_WcfService.Service1Behavior"> <!-- ...std/default data omitted for brevity..... --> <endpoint address ="" binding="wsHttpBinding" contract="SingleWSDL_WcfService.IService1" > ....... </services> <behaviors> <serviceBehaviors> <behavior name="SingleWSDL_WcfService.Service1Behavior"> ........ </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } When WCF is asked to produce a WSDL for this service, it will produce a file that looks something like this (note: some sections omitted for brevity): <?xml version="1.0" encoding="utf-8" ?> - <wsdl:definitions name="Service1" targetNamespace="http://tempuri.org/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" ...... namespace definitions omitted for brevity + &lt;wsp:Policy wsu:Id="WSHttpBinding_IService1_policy"> ... multiple policy items omitted for brevity </wsp:Policy> - <wsdl:types> - <xsd:schema targetNamespace="http://tempuri.org/Imports"> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd0" namespace="http://tempuri.org/" /> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd3" namespace="Http://SingleWSDL/Fault" /> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd1" namespace="http://schemas.microsoft.com/2003/10/Serialization/" /> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd2" namespace="http://SingleWSDL/Model1" /> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd4" namespace="http://SingleWSDL/Model2" /> </xsd:schema> </wsdl:types> + <wsdl:message name="IService1_GetData_InputMessage"> .... </wsdl:message> - <wsdl:operation name="GetData"> ..... </wsdl:operation> - <wsdl:service name="Service1"> ....... </wsdl:service> </wsdl:definitions> The above snippet from the WSDL shows the external links and references that are generated by WCF for a relatively simple service. Note the xsd:import statements that reference external XSD definitions which are also generated by WCF. In order to get WCF to produce a single WSDL file, we first need to follow some good practices when it comes to WCF service definitions. Step 1: Define a namespace for your service contract. [ServiceContract(Namespace="http://SingleWSDL/Service1")] public interface IService1 { ...... } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Normally you would not use a literal string and may instead define a constant to use in your own application for the namespace. When this is applied and we generate the WSDL, we get the following statement inserted into the document: <wsdl:import namespace="http://SingleWSDL/Service1" location="http://localhost:2370/HostingSite/Service-default.svc?wsdl=wsdl0" /> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } All the previous imports have gone. If we follow this link, we will see that the XSD imports are now in this external WSDL file. Not really any benefit for our purposes. Step 2: Define a namespace for your service behaviour [ServiceBehavior(Namespace = "http://SingleWSDL/Service1")] public class Service1 : IService1 { ...... } As you can see, the namespace of the service behaviour should be the same as the service contract interface to which it implements. Failure to do these tasks will cause WCF to emit its default http://tempuri.org namespace all over the place and cause WCF to still generate import statements. This is also true if the namespace of the contract and behaviour differ. If you define one and not the other, defaults kick in, and you’ll find extra imports generated. While each of the previous 2 steps wont cause any less import statements to be generated, you will notice that namespace definitions within the WSDL have identical, well defined names. Step 3: Define a binding namespace In the configuration file, modify the endpoint configuration line item to iunclude a bindingNamespace attribute which is the same as that defined on the service behaviour and service contract <endpoint address="" binding="wsHttpBinding" contract="SingleWSDL_WcfService.IService1" bindingNamespace="http://SingleWSDL/Service1"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } However, this does not completely solve the issue. What this will do is remove the WSDL import statements like this one: <wsdl:import namespace="http://SingleWSDL/Service1" location="http://localhost:2370/HostingSite/Service-default.svc?wsdl" /> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } from the generated WSDL. Finally…. the magic…. Step 4: Use a custom endpoint behaviour to read in external imports and include in the main WSDL output. In order to force WCF to output a single WSDL with all the required definitions, we need to define a custom WSDL Export extension that can be applied to any endpoints. This requires implementing the IWsdlExportExtension and IEndpointBehavior interfaces and then reading in any imported schemas, and adding that output to the main, flattened WSDL to be output. Sounds like fun right…..? Hmmm well maybe not. This step sounds a little hairy, but its actually quite easy thanks to some kind individuals who have already done this for us. As far as I know, there are 2 available implementations that we can easily use to perform the import and “WSDL flattening”.  WCFExtras which is on codeplex and FlatWsdl by Thinktecture. Both implementations actually do exactly the same thing with the imports and provide an endpoint behaviour, however FlatWsdl does a little more work for us by providing a ServiceHostFactory that we can use which automatically attaches the requisite behaviour to our endpoints for us. To use this in an IIS hosted service, we can modify the .SVC file to specify this ne factory to use like so: <%@ ServiceHost Language="C#" Debug="true" Service="SingleWSDL_WcfService.Service1" Factory="Thinktecture.ServiceModel.Extensions.Description.FlatWsdlServiceHostFactory" %> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Within a service application or another form of executable such as a console app, we can simply create an instance of the custom service host and open it as we normally would as shown here: FlatWsdlServiceHost host = new FlatWsdlServiceHost(typeof(Service1)); host.Open(); And we are done. WCF will now generate one single WSDL file that contains all he WSDL imports and data/XSD imports. You can download the full source code for this sample from here Hope this has helped you. Note: Please note that I have not extensively tested this in a number of different scenarios so no guarantees there.

    Read the article

  • Making WCF Output a single WSDL file for interop purposes.

    By default, when WCF emits a WSDL definition for your services, it can often contain many links to others related schemas that need to be imported. For the most part, this is fine. WCF clients understand this type of schema without issue, and it conforms to the requisite standards as far as WSDL definitions go. However, some non Microsoft stacks will only work with a single WSDL file and require that all definitions for the service(s) (port types, messages, operation etc) are contained within that single file. In other words, no external imports are supported. Some Java clients (to my working knowledge) have this limitation. This obviously presents a problem when trying to create services exposed for consumption and interop by these clients. Note: You can download the full source code for this sample from here To illustrate this point, lets say we have a simple service that looks like: Service Contract public interface IService1 { [OperationContract] [FaultContract(typeof(DataFault))] string GetData(DataModel1 model); [OperationContract] [FaultContract(typeof(DataFault))] string GetMoreData(DataModel2 model); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Service Implementation/Behaviour public class Service1 : IService1 { public string GetData(DataModel1 model) { return string.Format("Some Field was: {0} and another field was {1}", model.SomeField,model.AnotherField); } public string GetMoreData(DataModel2 model) { return string.Format("Name: {0}, age: {1}", model.Name, model.Age); } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Configuration File <system.serviceModel> <services> <service name="SingleWSDL_WcfService.Service1" behaviorConfiguration="SingleWSDL_WcfService.Service1Behavior"> <!-- ...std/default data omitted for brevity..... --> <endpoint address ="" binding="wsHttpBinding" contract="SingleWSDL_WcfService.IService1" > ....... </services> <behaviors> <serviceBehaviors> <behavior name="SingleWSDL_WcfService.Service1Behavior"> ........ </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } When WCF is asked to produce a WSDL for this service, it will produce a file that looks something like this (note: some sections omitted for brevity): <?xml version="1.0" encoding="utf-8" ?> - <wsdl:definitions name="Service1" targetNamespace="http://tempuri.org/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" ...... namespace definitions omitted for brevity + <wsp:Policy wsu:Id="WSHttpBinding_IService1_policy"> ... multiple policy items omitted for brevity </wsp:Policy> - <wsdl:types> - <xsd:schema targetNamespace="http://tempuri.org/Imports"> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd0" namespace="http://tempuri.org/" /> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd3" namespace="Http://SingleWSDL/Fault" /> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd1" namespace="http://schemas.microsoft.com/2003/10/Serialization/" /> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd2" namespace="http://SingleWSDL/Model1" /> <xsd:import schemaLocation="http://localhost:2370/HostingSite/Service-default.svc?xsd=xsd4" namespace="http://SingleWSDL/Model2" /> </xsd:schema> </wsdl:types> + <wsdl:message name="IService1_GetData_InputMessage"> .... </wsdl:message> - <wsdl:operation name="GetData"> ..... </wsdl:operation> - <wsdl:service name="Service1"> ....... </wsdl:service> </wsdl:definitions> The above snippet from the WSDL shows the external links and references that are generated by WCF for a relatively simple service. Note the xsd:import statements that reference external XSD definitions which are also generated by WCF. In order to get WCF to produce a single WSDL file, we first need to follow some good practices when it comes to WCF service definitions. Step 1: Define a namespace for your service contract. [ServiceContract(Namespace="http://SingleWSDL/Service1")] public interface IService1 { ...... } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Normally you would not use a literal string and may instead define a constant to use in your own application for the namespace. When this is applied and we generate the WSDL, we get the following statement inserted into the document: <wsdl:import namespace="http://SingleWSDL/Service1" location="http://localhost:2370/HostingSite/Service-default.svc?wsdl=wsdl0" /> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } All the previous imports have gone. If we follow this link, we will see that the XSD imports are now in this external WSDL file. Not really any benefit for our purposes. Step 2: Define a namespace for your service behaviour [ServiceBehavior(Namespace = "http://SingleWSDL/Service1")] public class Service1 : IService1 { ...... } As you can see, the namespace of the service behaviour should be the same as the service contract interface to which it implements. Failure to do these tasks will cause WCF to emit its default http://tempuri.org namespace all over the place and cause WCF to still generate import statements. This is also true if the namespace of the contract and behaviour differ. If you define one and not the other, defaults kick in, and youll find extra imports generated. While each of the previous 2 steps wont cause any less import statements to be generated, you will notice that namespace definitions within the WSDL have identical, well defined names. Step 3: Define a binding namespace In the configuration file, modify the endpoint configuration line item to iunclude a bindingNamespace attribute which is the same as that defined on the service behaviour and service contract <endpoint address="" binding="wsHttpBinding" contract="SingleWSDL_WcfService.IService1" bindingNamespace="http://SingleWSDL/Service1"> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } However, this does not completely solve the issue. What this will do is remove the WSDL import statements like this one: <wsdl:import namespace="http://SingleWSDL/Service1" location="http://localhost:2370/HostingSite/Service-default.svc?wsdl" /> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } from the generated WSDL. Finally. the magic. Step 4: Use a custom endpoint behaviour to read in external imports and include in the main WSDL output. In order to force WCF to output a single WSDL with all the required definitions, we need to define a custom WSDL Export extension that can be applied to any endpoints. This requires implementing the IWsdlExportExtension and IEndpointBehavior interfaces and then reading in any imported schemas, and adding that output to the main, flattened WSDL to be output. Sounds like fun right..? Hmmm well maybe not. This step sounds a little hairy, but its actually quite easy thanks to some kind individuals who have already done this for us. As far as I know, there are 2 available implementations that we can easily use to perform the import and WSDL flattening.  WCFExtras which is on codeplex and FlatWsdl by Thinktecture. Both implementations actually do exactly the same thing with the imports and provide an endpoint behaviour, however FlatWsdl does a little more work for us by providing a ServiceHostFactory that we can use which automatically attaches the requisite behaviour to our endpoints for us. To use this in an IIS hosted service, we can modify the .SVC file to specify this ne factory to use like so: <%@ ServiceHost Language="C#" Debug="true" Service="SingleWSDL_WcfService.Service1" Factory="Thinktecture.ServiceModel.Extensions.Description.FlatWsdlServiceHostFactory" %> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Within a service application or another form of executable such as a console app, we can simply create an instance of the custom service host and open it as we normally would as shown here: FlatWsdlServiceHost host = new FlatWsdlServiceHost(typeof(Service1)); host.Open(); And we are done. WCF will now generate one single WSDL file that contains all he WSDL imports and data/XSD imports. You can download the full source code for this sample from here Hope this has helped you. Note: Please note that I have not extensively tested this in a number of different scenarios so no guarantees there.Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • "The creator of this fault did not specify a Reason" Exception

    - by Michael Kniskern
    I have the following code in WCF service to throw a custom fault based on certain situations. I am getting a "The creator of this fault did not specify a Reason" exception. What am I doing wrong? //source code if(!DidNotPass) { InvalidRoutingCodeFault fault = new InvalidRoutingCodeFault("Invalid Routing Code - No Approval Started"); throw new FaultException<InvalidRoutingCodeFault>(fault); } //operation contract [OperationContract] [FaultContract(typeof(InvalidRoutingCodeFault))] bool MyMethod(); //data contract [DataContract(Namespace="http://myuri.org/Simple")] public class InvalidRoutingCodeFault { private string m_ErrorMessage = string.Empty; public InvalidRoutingCodeFault(string message) { this.m_ErrorMessage = message; } [DataMember] public string ErrorMessage { get { return this.m_ErrorMessage; } set { this.m_ErrorMessage = value; } } }

    Read the article

  • Catches communication exception instead of custom fault exception - WCF

    - by Ismail S
    On Server I'm throwing the exception like this. catch(SqlException exception) { if (exception.Message.Contains("Custom error from stored proc")) { //Exception to be thrown when authentication fails. throw new FaultException<MyServiceFault>(new MyServiceFault { MessageText = exception.Message }); } } And on client end I'm catching the exception catch(FaultException<MyServiceFault> faultException) { } Here is my MyServiceFault [DataContract] public class MyServiceFault { [DataMember] public string MessageText { get; set; } [DataMember] public Guid Id { get; set; } } The problem is that on client, it doesn't go to MyServiceFault catch block instead it goes to communication exception catch block and throws this error System.ServiceModel.CommunicationException: The underlying connection was closed: The connection was closed unexpectedly. ---> System.Net.WebException I've also decorated my service method [FaultContract(typeof(MyServiceFault))] in the interface which is implemented by my service. In my web.config servicebehaviour tag consist <serviceDebug includeExceptionDetailInFaults="true" /> Any idea where I'm going wrong

    Read the article

  • WCF ValidationFault

    - by RandomNoob
    I'm using Validation Application Block - Enterprise Library to validate parameters sent to my WCF Service operations. For instance, a certain operation requires the parameter to either be a 1 or 6, like so: [OperationContract(Name="GetEmployeesByRegion")] [FaultContract(typeof(ValidationFault))] List<Employees> GetEmployeesByRegion([DomainValidator(1,6)]int regionId); This works just fine i.e the validation fault occurs however, when the service is invoked by the client, a generic System.ServiceModel.FaultException is thrown. An the message indicates: "The creator of this fault did not specify a reason." Now, I could check the parameters myself before the service cal and throw a custom fault but that seems to defeat the purpose of attribute based validation of parameters using the Validation Application Block. Is there anyway to customize the error returned by the validation Fault? It is also possible I'm doing something completely wrong. I just want the caller to know that he/she should have passed in a 1 or 6 in the exception message. Is this possible?

    Read the article

  • How do I catch generic fault exceptions in Fitnesse?

    - by Dan Ryan
    Previously within my Fitnesse fixture I was specifying an expected WCF exception using: exception[FaultException] Since then I have converted the WCF service to return a strongly typed FaultContract. I am now getting the following failure message: exception[FaultException`1: "A file with the name DMS Documents/testFileWord.doc already exists. It was last modified by SHAREPOINT\system on 09 Mar 2010 15:36:14 -0000."] This is not unexpected but how do I check for strongly typed fault exceptions? Please note I cannot include the fault message as part of the check as it contains a date which changes (I check this separately).

    Read the article

  • WCF "The server did not provide a meaningful reply"

    - by Nelson
    I am out of ideas here, so I'm hoping someone can help. Here is what I've got: A WCF service that only has a basicHttpBinding endpoint. There is only a service interface, all other [DataMember], [FaultContract] are concrete types. When I run it straight from Visual Studio (using WCF Test Client or my custom app) everything works (I send a request and get a response). This usually takes a second or two. I published it to an IIS 6 server. I can successfully open http://server/WebService/WebService.svc?WSDL I can successfully open http://server/WebService/WebService.svc/mex (same output as above) The WCF Test Client and my custom app can successfully add the service reference Whenever I try to call a service method it waits for about 15 seconds and I get the dreaded "no meaningful reply" error. I ran Fiddler and I got a 202 result, which would seem like a success. It's not returning more than 65536 bytes It's returning an array, but it is small I tried remote debugging, but can't get that to work, probably due to a firewall (but port 80 is open, I can get the WSDL) I enabled system.diagnostics, nothing. I have an IErrorHandler which normally logs things, nothing. Here's the endpoint config: <endpoint address="" binding="basicHttpBinding" contract="Enterprise.IMyService" bindingNamespace="http://ourdomain.com/MyService/"> <identity> <dns value="localhost" /> </identity> </endpoint> Anything else I can try? It's probably a simple setting somewhere, but I can't figure it out.

    Read the article

  • IncludeExceptionDetailInFaults not behaving as thought

    - by pdiddy
    I have this simple test project just to test the IncludeExceptionDetailInFaults behavior. public class Service1 : IService1 { public string GetData(int value) { throw new InvalidCastException("test"); return string.Format("You entered: {0}", value); } } [ServiceContract] public interface IService1 { [OperationContract] string GetData(int value); } In the app.config of the service i have it set to true <serviceDebug includeExceptionDetailInFaults="True" /> On the client side: try { using (var proxy = new ServiceReference1.Service1Client()) Console.WriteLine(proxy.GetData(5)); } catch (Exception ex) { Console.WriteLine(ex.Message); } This is what I thought the behavior was: Setting to includeExceptionDetailInFaults=true would propagate the exception detail to the client. But I'm always getting the CommunicationObjectFaultException. I did try having the FaultContract(typeof(InvalidCastException)) on the contract but same behavior, only getting the CommunicationObjectFaultException. The only way to make it work was to throw new FaultException(new InvalidCastException("test")); But I thought with IncludeExceptionDetailInFaults=true the above was done automatically. Am I missing something?

    Read the article

  • How to specify allowed exceptions in WCF's configuration file?

    - by tucaz
    Hello! I´m building a set of WCF services for internal use through all our applications. For exception handling I created a default fault class so I can return treated message to the caller if its the case or a generic one when I have no clue what happened. Fault contract: [DataContract(Name = "DefaultFault", Namespace = "http://fnac.com.br/api/2010/03")] public class DefaultFault { public DefaultFault(DefaultFaultItem[] items) { if (items == null || items.Length== 0) { throw new ArgumentNullException("items"); } StringBuilder sbItems = new StringBuilder(); for (int i = 0; i Specifying that my method can throw this exception so the consuming client will be aware of it: [OperationContract(Name = "PlaceOrder")] [FaultContract(typeof(DefaultFault))] [WebInvoke(UriTemplate = "/orders", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, Method = "POST")] string PlaceOrder(Order newOrder); Most of time we will use just .NET to .NET communication with usual binds and everything works fine since we are talking the same language. However, as you can see in the service contract declaration I have a WebInvoke attribute (and a webHttp binding) in order to be able to also talk JSON since one of our apps will be built for iPhone and this guy will talk JSON. My problem is that whenever I throw a FaultException and have includeExceptionDetails="false" in the config file the calling client will get a generic HTTP error instead of my custom message. I understand that this is the correct behavior when includeExceptionDetails is turned off, but I think I saw some configuration a long time ago to allow some exceptions/faults to pass through the service boundaries. Is there such thing like this? If not, what do u suggest for my case? Thanks a LOT!

    Read the article

  • Enterprise Library Logging / Exception handling and Postsharp

    - by subodhnpushpak
    One of my colleagues came-up with a unique situation where it was required to create log files based on the input file which is uploaded. For example if A.xml is uploaded, the corresponding log file should be A_log.txt. I am a strong believer that Logging / EH / caching are cross-cutting architecture aspects and should be least invasive to the business-logic written in enterprise application. I have been using Enterprise Library for logging / EH (i use to work with Avanade, so i have affection towards the library!! :D ). I have been also using excellent library called PostSharp for cross cutting aspect. Here i present a solution with and without PostSharp all in a unit test. Please see full source code at end of the this blog post. But first, we need to tweak the enterprise library so that the log files are created at runtime based on input given. Below is Custom trace listner which writes log into a given file extracted out of Logentry extendedProperties property. using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; using Microsoft.Practices.EnterpriseLibrary.Logging; using System.IO; using System.Text; using System; using System.Diagnostics;   namespace Subodh.Framework.Logging { [ConfigurationElementType(typeof(CustomTraceListenerData))] public class LogToFileTraceListener : CustomTraceListener {   private static object syncRoot = new object();   public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) {   if ((data is LogEntry) & this.Formatter != null) { WriteOutToLog(this.Formatter.Format((LogEntry)data), (LogEntry)data); } else { WriteOutToLog(data.ToString(), (LogEntry)data); } }   public override void Write(string message) { Debug.Print(message.ToString()); }   public override void WriteLine(string message) { Debug.Print(message.ToString()); }   private void WriteOutToLog(string BodyText, LogEntry logentry) { try { //Get the filelocation from the extended properties if (logentry.ExtendedProperties.ContainsKey("filelocation")) { string fullPath = Path.GetFullPath(logentry.ExtendedProperties["filelocation"].ToString());   //Create the directory where the log file is written to if it does not exist. DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(fullPath));   if (directoryInfo.Exists == false) { directoryInfo.Create(); }   //Lock the file to prevent another process from using this file //as data is being written to it.   lock (syncRoot) { using (FileStream fs = new FileStream(fullPath, FileMode.Append, FileAccess.Write, FileShare.Write, 4096, true)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { Log(BodyText, sw); sw.Close(); } fs.Close(); } } } } catch (Exception ex) { throw new LoggingException(ex.Message, ex); } }   /// <summary> /// Write message to named file /// </summary> public static void Log(string logMessage, TextWriter w) { w.WriteLine("{0}", logMessage); } } }   The above can be “plugged into” the code using below configuration <loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="Trace" logWarningsWhenNoCategoriesMatch="true"> <listeners> <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Subodh.Framework.Logging.LogToFileTraceListener, Subodh.Framework.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Subodh Custom Trace Listener" initializeData="" formatter="Text Formatter" /> </listeners> Similarly we can use PostSharp to expose the above as cross cutting aspects as below using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using PostSharp.Laos; using System.Diagnostics; using GC.FrameworkServices.ExceptionHandler; using Subodh.Framework.Logging;   namespace Subodh.Framework.ExceptionHandling { [Serializable] public sealed class LogExceptionAttribute : OnExceptionAspect { private string prefix; private MethodFormatStrings formatStrings;   // This field is not serialized. It is used only at compile time. [NonSerialized] private readonly Type exceptionType; private string fileName;   /// <summary> /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute /// that logs every exception flowing out of the methods to which /// the custom attribute is applied. /// </summary> public LogExceptionAttribute() { }   /// <summary> /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute /// that logs every exception derived from a given <see cref="Type"/> /// flowing out of the methods to which /// the custom attribute is applied. /// </summary> /// <param name="exceptionType"></param> public LogExceptionAttribute( Type exceptionType ) { this.exceptionType = exceptionType; }   public LogExceptionAttribute(Type exceptionType, string fileName) { this.exceptionType = exceptionType; this.fileName = fileName; }   /// <summary> /// Gets or sets the prefix string, printed before every trace message. /// </summary> /// <value> /// For instance <c>[Exception]</c>. /// </value> public string Prefix { get { return this.prefix; } set { this.prefix = value; } }   /// <summary> /// Initializes the current object. Called at compile time by PostSharp. /// </summary> /// <param name="method">Method to which the current instance is /// associated.</param> public override void CompileTimeInitialize( MethodBase method ) { // We just initialize our fields. They will be serialized at compile-time // and deserialized at runtime. this.formatStrings = Formatter.GetMethodFormatStrings( method ); this.prefix = Formatter.NormalizePrefix( this.prefix ); }   public override Type GetExceptionType( MethodBase method ) { return this.exceptionType; }   /// <summary> /// Method executed when an exception occurs in the methods to which the current /// custom attribute has been applied. We just write a record to the tracing /// subsystem. /// </summary> /// <param name="context">Event arguments specifying which method /// is being called and with which parameters.</param> public override void OnException( MethodExecutionEventArgs context ) { string message = String.Format("{0}Exception {1} {{{2}}} in {{{3}}}. \r\n\r\nStack Trace {4}", this.prefix, context.Exception.GetType().Name, context.Exception.Message, this.formatStrings.Format(context.Instance, context.Method, context.GetReadOnlyArgumentArray()), context.Exception.StackTrace); if(!string.IsNullOrEmpty(fileName)) { ApplicationLogger.LogException(message, fileName); } else { ApplicationLogger.LogException(message, Source.UtilityService); } } } } To use the above below is the unit test [TestMethod] [ExpectedException(typeof(NotImplementedException))] public void TestMethod1() { MethodThrowingExceptionForLog(); try { MethodThrowingExceptionForLogWithPostSharp(); } catch (NotImplementedException ex) { throw ex; } }   private void MethodThrowingExceptionForLog() { try { throw new NotImplementedException(); } catch (NotImplementedException ex) { // create file and then write log ApplicationLogger.TraceMessage("this is a trace message which will be logged in Test1MyFile", @"D:\EL\Test1Myfile.txt"); ApplicationLogger.TraceMessage("this is a trace message which will be logged in YetAnotherTest1Myfile", @"D:\EL\YetAnotherTest1Myfile.txt"); } }   // Automatically log details using attributes // Log exception using attributes .... A La WCF [FaultContract(typeof(FaultMessage))] style] [Log(@"D:\EL\Test1MyfileLogPostsharp.txt")] [LogException(typeof(NotImplementedException), @"D:\EL\Test1MyfileExceptionPostsharp.txt")] private void MethodThrowingExceptionForLogWithPostSharp() { throw new NotImplementedException(); } The good thing about the approach is that all the logging and EH is done at centralized location controlled by PostSharp. Of Course, if some other library has to be used instead of EL, it can easily be plugged in. Also, the coder ARE ONLY involved in writing business code in methods, which makes code cleaner. Here is the full source code. The third party assemblies provided are from EL and PostSharp and i presume you will find these useful. Do let me know your thoughts / ideas on the same. Technorati Tags: PostSharp,Enterprize library,C#,Logging,Exception handling

    Read the article

  • IErrorHandler doesn't seem to be handling my errors in WCF .. any ideas?

    - by John Nicholas
    Have been readign around on IErrorHandler and want to go the config route. so, I have read the following in an attempt to implement it. MSDN Keyvan Nayyeri blog about the type defintion Rory Primrose Blog I have got it to compile and from the various errors i have fixed it seems like WCF is actually loading the error handler. My problem is that the exception that i am throwing to handle in the error handler doesn;t get the exception passed to it. My service implementation simply calls a method on another class that throws ArgumentOutOfRangeException - however this exception never gets handled by the handler. My web.config <system.serviceModel> <bindings> <basicHttpBinding> <binding name="basic"> <security mode="None" /> </binding> </basicHttpBinding> </bindings> <extensions> <behaviorExtensions> <add name="customHttpBehavior" type="ErrorHandlerTest.ErrorHandlerElement, ErrorHandlerTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </behaviorExtensions> </extensions> <behaviors> <serviceBehaviors> <behavior name="exceptionHandlerBehaviour"> <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"/> <customHttpBehavior /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="exceptionHandlerBehaviour" name="ErrorHandlerTest.Service1"> <endpoint binding="basicHttpBinding" bindingConfiguration="basic" contract="ErrorHandlerTest.IService1" /> </service> </services> Service Contract [ServiceContract] public interface IService1 { [OperationContract] [FaultContract(typeof(GeneralInternalFault))] string GetData(int value); } The ErrorHandler class public class ErrorHandler : IErrorHandler , IServiceBehavior { public bool HandleError(Exception error) { Console.WriteLine("caught exception {0}:",error.Message ); return true; } public void ProvideFault(Exception error, MessageVersion version, ref Message fault) { if (fault!=null ) { if (error is ArgumentOutOfRangeException ) { var fe = new FaultException<GeneralInternalFault>(new GeneralInternalFault("general internal fault.")); MessageFault mf = fe.CreateMessageFault(); fault = Message.CreateMessage(version, mf, fe.Action); } else { var fe = new FaultException<GeneralInternalFault>(new GeneralInternalFault(" the other general internal fault.")); MessageFault mf = fe.CreateMessageFault(); fault = Message.CreateMessage(version, mf, fe.Action); } } } public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) { } public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { IErrorHandler errorHandler = new ErrorHandler(); foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers) { ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher; if (channelDispatcher != null) { channelDispatcher.ErrorHandlers.Add(errorHandler); } } } public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { } } And the Behaviour Extension Element public class ErrorHandlerElement : BehaviorExtensionElement { protected override object CreateBehavior() { return new ErrorHandler(); } public override Type BehaviorType { get { return typeof(ErrorHandler); } } }

    Read the article

  • Web service client receiving generic FaultException rather than FaultException<T>

    - by Junto
    I am connecting to a Java Axis2 web service using a .NET web service client. The client itself targets the .NET 3.5 framework. The application that wraps the client DLL is 2.0. I'm not sure if that has any bearing. I have been given the WSDL and XSDs by email. From those I have built my proxy class using svcutil. Although I am able to successfully send messages, I am unable to pick up the correct faults when something goes wrong. In the example below, errors are always being picked up by the generic FaultException. catch (FaultException<InvoiceErrorType> fex) { OnLog(enLogLevel.ERROR, fex.Detail.ErrorDescription); } catch (FaultException gfex) { OnLog(enLogLevel.ERROR, gfex.Message); } The proxy client appears to have the appropriate attributes for the FaultContract: // CODEGEN: Generating message contract since the operation SendInvoiceProvider_Prod is neither RPC nor document wrapped. [OperationContractAttribute(Action = "https://private/SendInvoiceProvider", ReplyAction = "*")] [FaultContractAttribute(typeof(InvoiceErrorType), Action = "https://private/SendInvoiceProvider", Name = "InvoiceError", Namespace = "urn:company:schema:entities:base")] [XmlSerializerFormatAttribute(SupportFaults = true)] [ServiceKnownTypeAttribute(typeof(ItemDetail))] [ServiceKnownTypeAttribute(typeof(Supplier))] OutboundComponent.SendInvoiceProviderResponse SendInvoiceProvider_Prod(OutboundComponent.SendInvoiceProvider_Request request); I have enabled tracing and I can see the content of the fault coming back, but .NET is not recognizing it as an InvoiceError. The SOAP fault in full is: <soapenv:Fault> <faultcode xmlns="">soapenv:Client</faultcode> <faultstring xmlns="">Message found to be invalid</faultstring> <faultactor xmlns="">urn:SendInvoiceProvider</faultactor> <detail xmlns=""> <InvoiceError xmlns="urn:company:schema:entities:common:invoiceerror:v01"> <ErrorID>100040</ErrorID> <ErrorType>UNEXPECTED</ErrorType> <ErrorDescription>&lt;![CDATA[&lt;error xmlns="urn:company:schema:errordetail:v01"&gt;&lt;errorCode&gt;1000&lt;/errorCode&gt;&lt;highestSeverity&gt;8&lt;/highestSeverity&gt;&lt;errorDetails count="1"&gt;&lt;errorDetail&gt;&lt;errorType&gt;1&lt;/errorType&gt;&lt;errorSeverity&gt;8&lt;/errorSeverity&gt;&lt;errorDescription&gt;cvc-complex-type.2.4.a: Invalid content was found starting with element 'CompanyName'. One of '{"urn:company:schema:sendinvoice:rq:v01":RoleType}' is expected.&lt;/errorDescription&gt;&lt;errorNamespace&gt;urn:company:schema:sendinvoice:rq:v01&lt;/errorNamespace&gt;&lt;errorNode&gt;CompanyName&lt;/errorNode&gt;&lt;errorLine&gt;1&lt;/errorLine&gt;&lt;errorColumn&gt;2556&lt;/errorColumn&gt;&lt;errorXPath/&gt;&lt;errorSource/&gt;&lt;/errorDetail&gt;&lt;/errorDetails&gt;&lt;/error&gt;]]&gt;</ErrorDescription> <TimeStamp>2010-05-04T21:12:10Z</TimeStamp> </InvoiceError> </detail> </soapenv:Fault> I have noticed the namespace defined on the error: <InvoiceError xmlns="urn:company:schema:entities:common:invoiceerror:v01"> This is nowhere to be seen in the generated proxy class, nor in the WSDLs. The interface WSDL defines the error schema namespace as such: <xs:import namespace="urn:company:schema:entities:base" schemaLocation="InvoiceError.xsd"/> Could this be the reason why the .NET client is not able to parse the typed Fault Exception correctly? I have no control over the web service itself. I see no reason why .NET can't talk to a Java Axis2 web service. This user had a similar issue, but the reason for his problem cannot be the same as mine, since I can see the fault detail in the trace: http://stackoverflow.com/questions/864800/does-wcf-faultexceptiont-support-interop-with-a-java-web-service-fault Any help would be gratefully received.

    Read the article

  • Strange exception when connecting to a WCF service via a proxy server

    - by Slauma
    The exception "This operation is not supported for a relative URI." occurs in the following situation: I have a WCF service: [ServiceContract(ProtectionLevel=ProtectionLevel.None)] public interface IMyService { [OperationContract] [FaultContract(typeof(MyFault))] List<MyDto> MyOperation(int param); // other operations } public class MyService : IMyService { public List<MyDto> MyOperation(int param) { // Do the business stuff and return a list of MyDto } // other implementations } MyFault and MyDto are two very simple classes marked with [DataContract] attribute and each only having three [DataMember] of type string, int and int?. This service is hosted in IIS 7.0 on a Win 2008 Server along with an ASP.NET application. I am using an SVC file MyService.svc which is located directly in the root of the web site. The service configuration in web.config is the following: <system.serviceModel> <services> <service name="MyServiceLib.MyService"> <endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpBindingConfig" contract="MyServiceLib.IMyService" /> </service> </services> <bindings> <wsHttpBinding> <binding name="wsHttpBindingConfig"> <security mode="None"> <transport clientCredentialType="None" /> </security> </binding> </wsHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="false"/> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> This seems to work so far as I can enter the address http://www.domain.com/MyService.svc in a browser and get the "This is a Windows Communication Foundation Service"-Welcome page. One of the clients consuming the service is a console application: MyServiceClient aChannel = new MyServiceClient("WSHttpBinding_IMyService"); List<MyDto> aMyDtoList = aChannel.MyOperation(1); It has the following configuration: <system.serviceModel> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IMyService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="true" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="false" proxyAddress="10.20.30.40:8080" allowCookies="false"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /> <security mode="None"> <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" /> <message clientCredentialType="Windows" negotiateServiceCredential="true" /> </security> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="http://www.domain.com/MyService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IMyService" contract="MyService.IMyService" name="WSHttpBinding_IMyService" /> </client> </system.serviceModel> When I run this application at a production server at a customer site calling aChannel.MyOperation(1) throws the following exception: This operation is not supported for a relative URI. When I run this client application on my development PC with exactly the same config, with the exception that I remove proxyAddress="10.20.30.40:8080" from the bindings the operation works without problems. Now I really don't know what specifying a proxy server address might have to do with absolute or relative URIs. The use of the proxy server or not is the only difference I can see when running the client on the production or on the development machine. Does someone have an idea what this exception might mean in this context and how possibly to solve the problem? Thank you in advance for help!

    Read the article

  • migrating webclient to WCF; WCF client serializes parametername of method

    - by Wouter
    I'm struggling with migrating from webservice/webclient architecture to WCF architecture. The object are very complex, with lots of nested xsd's and different namespaces. Proxy classes are generated by adding a Web Reference to an original wsdl with 30+ webmethods and using xsd.exe for generating the missing SOAPFault objects. My pilot WCF Service consists of only 1 webmethod which matches the exact syntax of one of the original methods: 1 object as parameter, returning 1 other object as result value. I greated a WCF Interface using those proxy classes, using attributes: XMLSerializerFormat and ServiceContract on the interface, OperationContract on one method from original wsdl specifying Action, ReplyAction, all with the proper namespaces. I create incoming client messages using SoapUI; I generated a project from the original WSDL files (causing the SoapUI project to have 30+ methods) and created one new Request at the one implemented WebMethod, changed the url to my wcf webservice and send the message. Because of the specified (Reply-)Action in the OperationContractAttribute, the message is actually received and properly deserialized into an object. To get this far (40 hours of googling), a lot of frustration led me to using a custom endpoint in which the WCF 'wrapped tags' are removed, the namespaces for nested types are corrected, and the generated wsdl get's flattened (for better compatibility with other tools then MS VisualStudio). Interface code is this: [XmlSerializerFormat(Use = OperationFormatUse.Literal, Style = OperationFormatStyle.Document, SupportFaults = true)] [ServiceContract(Namespace = Constants.NamespaceStufZKN)] public interface IOntvangAsynchroon { [OperationContract(Action = Constants.NamespaceStufZKN + "/zakLk01", ReplyAction = Constants.NamespaceStufZKN + "/zakLk01", Name = "zakLk01")] [FaultContract(typeof(Fo03Bericht), Namespace = Constants.NamespaceStuf)] Bv03Bericht zakLk01([XmlElement("zakLk01", Namespace = Constants.NamespaceStufZKN)] ZAKLk01 zakLk011); When I use a Webclient in code to send a message, everything works. My problem is, when I use a WCF client. I use ChannelFactory< IOntvangAsynchroon to send a message. But the generated xml looks different: it includes the parametername of the method! It took me a lot of time to figure this one out, but here's what happens: Correct xml (stripped soap envelope): <soap:Body> <zakLk01 xmlns="http://www.egem.nl/StUF/sector/zkn/0310"> <stuurgegevens> <berichtcode xmlns="http://www.egem.nl/StUF/StUF0301">Bv01</berichtcode> <zender xmlns="http://www.egem.nl/StUF/StUF0301"> <applicatie>ONBEKEND</applicatie> </zender> </stuurgegevens> <parameters> </parameters> </zakLk01> </soap:Body> Bad xml: <soap:Body> <zakLk01 xmlns="http://www.egem.nl/StUF/sector/zkn/0310"> <zakLk011> <stuurgegevens> <berichtcode xmlns="http://www.egem.nl/StUF/StUF0301">Bv01</berichtcode> <zender xmlns="http://www.egem.nl/StUF/StUF0301"> <applicatie>ONBEKEND</applicatie> </zender> </stuurgegevens> <parameters> </parameters> </zakLk011> </zakLk01> </soap:Body> Notice the 'zakLk011' element? It is the name of the parameter of the method in my interface! So NOW it is zakLk011, but it when my parameter name was 'zakLk01', the xml seemed to contain some magical duplicate of the tag above, but without namespace. Of course, you can imagine me going crazy over what was happening before finding out it was the parametername! I know have actually created a WCF Service, at which I cannot send messages using a WCF Client anymore. For clarity: The method does get invoked using the WCF Client on my webservice, but the parameter object is empty. Because I'm using a custom endpoint to log the incoming xml, I can see the message is received fine, but just with the wrong syntax! WCF client code: ZAKLk01 stufbericht = MessageFactory.CreateZAKLk01(); ChannelFactory<IOntvangAsynchroon> factory = new ChannelFactory<IOntvangAsynchroon>(new BasicHttpBinding(), new EndpointAddress("http://localhost:8193/Roxit/Link/zkn0310")); factory.Endpoint.Behaviors.Add(new LinkEndpointBehavior()); IOntvangAsynchroon client = factory.CreateChannel(); client.zakLk01(stufbericht); I am not using a generated client, i just reference the webservice like i am lot's of times. Can anyone please help me? I can't google anything on this...

    Read the article

1