dotnetspider.com
Login Login    Register      

TutorialsForumCareer DevelopmentResourcesReviewsJobsInterviewCommunitiesProjectsTraining

Subscribe to Subscribers
Talk to Webmaster
Tony John

Facebook
Google+
Twitter
LinkedIn
Online MembersAmruta
Minu
Rakesh Chaubey
Tarun
Shine S
More...
Join our online Google+ community for Bloggers, Content Writers and Webmasters




Resources » .NET programming » WCF/Webservices

In this we see How ta handle exception in WCF using FaultContract


Posted Date:     Category: WCF/Webservices    
Author: Member Level: Gold    Points: 20


In this we see how WCF handles the error using the SOAP Fault contract. We will see an application that will show the steps to how to create an application that handles the exception using Fault Contract.From this you also get some idea about the ServiceContract and Operation Contract.



 


In all managed applications, we handle the error using Exception Handling mechenism. In WCF applications, we does this by using SOAP FaultContract. SOAP faults are message types that are included in the metadata for a service operation and, therefore, create a fault contract that clients can use to make their operation more interactive. In addition, because SOAP faults are expressed to clients in XML form, they are highly interoperable.

Understanding WCF FaultContract
1. Create an empty solution named "WCF_ExceptionHandling".

2. Add a new project named "WCFService1" of type "WCF Service Library" in the solution.

3. Delete the file named "IService1.cs".

4. Delete all the code in the file named "Service1.cs".

5. Add the following code in the file named "Service1.cs".

[ServiceContract]
public interface IService1
{
[OperationContract]
string SomeMethod(int x);
}
public class CService1 : IService1
{
public string SomeMethod(int x)
{
if (x == 0)
{
throw new DivideByZeroException("CANNOT BE ZERO");
}
else if (x == 1)
{
throw new ArgumentException("CANNOT BE 1");
}
return "Method executed successfully with value: " +x.ToString();
}
}
public class WCFService1_HOST
{
static void Main()
{
ServiceHost h = new ServiceHost(typeof(CService1));
h.Open();
Console.WriteLine("Host started");
Console.ReadKey();
h.Close();
}
}


6. Delete all the markup inside the tag in the file named "App.config" .

7. Add the following markup inside .

< system.serviceModel>
<services>
<service name="WCFService1.CService1" behaviorConfiguration="PublishMetaData">
<host>
<baseAddresses>
<add baseAddress="http://localhost:9999/WCFService1"/>
</baseAddresses>
</host>
<endpoint address=""
binding="basicHttpBinding"
contract="WCFService1.IService1"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="PublishMetaData">
<serviceMetadata httpGetEnabled="true" httpGetUrl="METADATA"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>


8. Change the output type of the above project to "Console Application".

9. Build the solution.

10. Add a new "Windows Forms Application" named "WCFService1_CLIENT" in the current solution.

11. Create the following UI

12. Start the host by pressing Ctrl + f5.

13. Add a Service Reference in the client application using the following URL
http://localhost:9999/WCFService1/METADATA?wsdl

14. Name the proxy as "MyProxy".

15. Add the following code inside the class of the form shown above

MyProxy.Service1Client proxy = new
WCFService1_CLIENT.MyProxy.Service1Client();


16. Add the following code in the Click event of the button

try
{
int x = int.Parse(textBox1.Text);
MessageBox.Show(proxy.SomeMethod(x));
}
catch (Exception ex)
{
MessageBox.Show("Exception type: "
+ ex.GetType().FullName + "\n" + ex.Message);
}


17. Configure the solution for multiple startup projects as follows
WCFService1 Start without debugging
WCFService1_CLIENT Start without debugging

18. Start without debugging. Enter 0 and 1 respectively in the textbox and click the button.
Observe the exception in each case.

19. Add the following markup inside the tag in the "App.config" file.


20. Start without debugging. Enter 0 and 1 respectively in the textbox and click the button.
Observe the exception in each case.

21. Remove the markup added in step 19 above.

22. In the "SomeMethod()" method in "Service1.cs" file, inside each condition, replace the existing code with the following code respectively.

DivideByZeroException ex = new DivideByZeroException("CANNOT BE ZERO");
throw new FaultException(ex,ex.Message);
ArgumentException ex = new ArgumentException("CANNOT BE 1");
throw new FaultException(ex,ex.Message);


23. Start without debugging. Enter 0 and 1 respectively in the textbox and click the button.
Observe the exception in each case.

24. Add the following attributes below [OperationContract] in the interface in "Service1.cs" file.

[FaultContract(typeof(DivideByZeroException))]
[FaultContract(typeof(ArgumentException))]
[FaultContract(typeof(MyException))]


25. Add another condition below the last condition inside the "SomeMethod()" method in "Service1.cs" file.

else if (x == 2)
{
IndexOutOfRangeException ex =
new IndexOutOfRangeException("CANNOT BE 2");
}


26. In the Click event of the button, replace the existing catch block with the following.

catch (System.ServiceModel.FaultException ex)
{
MessageBox.Show("Exception type: "
+ ex.GetType().FullName + "\n" + ex.Message);
}
catch (System.ServiceModel.FaultException ex)
{
MessageBox.Show("Exception type: "
+ ex.GetType().FullName + "\n" + ex.Message);
}
catch (System.ServiceModel.FaultException ex)
{
MessageBox.Show("Exception type: "
+ ex.GetType().FullName + "\n" + ex.Message);
}


27. Start without debugging. Enter 0, 1 and 2 respectively in the textbox and click the button. Observe the exception in each case.

28. Add the following class in the file "Service1.cs"

[DataContract]
public class MyException
{
string error;
string datetime;
public MyException(string error,string datetime)
{
this.error = error;
this.datetime = datetime;
}
public string TheError
{
get { return this.error; }
set { this.error = value; }
}
[DataMember]
public string ErrorTime
{
get { return this.datetime; }
set { this.datetime = value; }
}
}

29. Add another condition below the last condition inside the "SomeMethod()" method in "Service1.cs" file.

else if (x == 3)
{
MyException ex =
new MyException("Custom Exception Message",DateTime.Now.ToString());
throw new FaultException(ex, ex.TheError);
}


30. Add the following catch block before the last catch block in the Click event of the button.

catch (System.ServiceModel.FaultException ex)
{
MessageBox.Show("Exception type: " + ex.GetType().FullName + "\n" +
ex.Message +"\nGenerated at: " + ex.Detail.ErrorTime);
}

31. Start without debugging. Enter 0, 1, 2 and 3 respectively in the textbox and click the button. Observe the exception in each case.





Did you like this resource? Share it with your friends and show your love!


Responses to "In this we see How ta handle exception in WCF using FaultContract"
Author: Siva Prasad    07 Jul 2012Member Level: Gold   Points : 0
8. Change the output type of the above project to "Console Application".

You said Above point, How to change the type of the project?



Author: Siva Prasad    07 Jul 2012Member Level: Gold   Points : 0
19. Add the following markup inside the tag in the "App.config" file.

Where is the markup below...Not available.



Author: Siva Prasad    07 Jul 2012Member Level: Gold   Points : 2
No need to be add this many catch blocks.One catch block is enough.

catch (System.ServiceModel.FaultException ex)
{
MessageBox.Show("Exception type: "
+ ex.GetType().FullName + "\n" + ex.Message);
}
catch (System.ServiceModel.FaultException ex)
{
MessageBox.Show("Exception type: "
+ ex.GetType().FullName + "\n" + ex.Message);
}
catch (System.ServiceModel.FaultException ex)
{
MessageBox.Show("Exception type: "
+ ex.GetType().FullName + "\n" + ex.Message);
}



Author: Siva Prasad    07 Jul 2012Member Level: Gold   Points : 0
Thanks for this article. Really nice one.


Author: Deep Gautam    07 Oct 2012Member Level: Gold   Points : 0
http://www.youtube.com/watch?v=DCnRZpoRiAY


Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Next Resource: IEnumerable Return types in WCF
    Previous Resource: Difference between Bindings in WCF
    Return to Resources
    Post New Resource
    Category: WCF/Webservices


    Post resources and earn money!
     
    More Resources
    Popular Tags   Tag posting guidelines   Search Tags  
    Error Handling in WCF  .  



    Follow us on Twitter: https://twitter.com/dotnetspider

    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Email subscription
  • .NET Jobs
  • .NET Articles
  • .NET Forums
  • Articles Rss Feeds
    Forum Rss Feeds


    About Us    Contact Us    Copyright    Privacy Policy    Terms Of Use    Revenue Sharing sites   Advertise   Talk to Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
    2005 - 2012 All Rights Reserved.
    .NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
    Articles, tutorials and all other content offered here is for educational purpose only.
    We are not associated with Microsoft or its partners.