Blue Theme Orange Theme Green Theme Red Theme
 
Click Here for 3 Month Free of ASP.NET Hosting!
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Web Services » Using Reflection to dynamically expose your Business Logic through a Webservice.

Using Reflection to dynamically expose your Business Logic through a Webservice.

Many people are using web services to communicate with their business logic. There are many advantages of this approach with some issues. This article will show you how you can avoid those issues, while still enjoying all the benefits of using web services.

Technologies: .NET 1.0/1.1, Web Services,Visual C# .NET
Total downloads :
Total page views :  15810
Rating :
 5/5
This article has been rated :  2 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
Become a Sponsor


Related EbooksTop Videos

Introduction:

Many people are using web services to communicate with their business logic. There are many advantages to this - Using this approach allows a wide range of flexibility in the architecture that would otherwise be very hard to come by. However, there are also a few disadvantages. One disadvantage is the amount of tedious work involved in keeping your web service methods in-sync with your business logic methods. This article will show you how you can avoid those issues, while still enjoying all the benefits of using web services.

The Reasoning:

I recently designed and built an application which used web services for business layer communication. The interface used a custom component to get data, and the custom component used the web services to communicate with the business layer. This allowed the interface to be deployed (almost) anywhere we wanted, and also gave us the ability to secure (via SSL) all communication. Our architecture was similar to this:

Interface <-> Communication Component <-> Web Service <-> Business Logic <-> Data Access Layer

Note that the Business Logic classes contained static methods to process data before being sent to the Data Access Layer, or returned to the Communication Component.

This was working great for about the first two weeks while we worked on the main system functionality. However, as time went on, we began adding more and more methods to the business logic that needed to be exposed via the web service. This was consuming a tremendous amount of time, as we had a one-to-one ratio of web services to business logic classes. Every time we added a new business logic class, we had to make a new web service, make the proxy class for the web service, keep the proxy class in-sync with the web service, and keep the web service in-sync with the business logic. It was quickly becoming more trouble than it was worth.

We had a hard deadline, and a very tight schedule. What we needed was a way to automate or simplify the maintenance associated with using web services. After tossing around some ideas (such as code generators - we already used one to generate classes from DB tables), I came up with the idea of using reflection to dynamically invoke methods in the business logic and return their results through the web service. After a 1/2 hour or so I had the first prototype, and about 2 hours later I had a component that I felt would work in a production environment.

The Setup:

Let's assume that you already have some classes developed. These classes can be thought of as "Data Transfer Objects" (DTOs). One of these classes is "CustomerData", which provides data on a particular customer. There are several ways you want to be able to access a Customer. You will either use the Customer's ID, or you will use an Order Number. You also have an "OrderData" class that you need to access. For the Order class you need to be able to either access a single order or every order for a given customer (ArrayList). The business logic classes will be called "Order" and "Customer" respectively.

Normally, for this type of situation, you would have 2 web services - One for returning CustomerData objects, and one for returning OrderData objects (you could pack them into one web service, but that gets crowded when dealing with a large number of classes). You would also have two methods in each of those web services. The web service methods would be called from your interface layer, and then they would call your business layer to get the data required. So for the normal situation, we've got two classes, two web services, and two methods in each web service.

For example:

Customer.LoadByCustomerID() <-> Customer Web Service <-> Customer Business Logic
Customer.LoadByOrderID() <-> Customer Web Service <-> Customer Business Logic
Order.LoadByOrderID() <-> Order Web Service <-> Order Business Logic
Order.LoadAllForCustomerID() <-> Order Web Service <-> Order Business Logic

Using reflection, you can have one web service, with two methods, handle each and every single call you would ever need to make to your business layer.

For Example:

Customer.LoadByCustomerID() <-> Generic Web Service <-> Customer Business Logic
Customer.LoadByOrderID() <-> Generic Web Service <-> Customer Business Logic
Order.LoadByOrderID() <-> Generic Web Service <-> Order Business Logic
Order.LoadAllForCustomerID() <-> Generic Web Service <-> Order Business Logic

The Code:

The following is the code for implementing a generic web service. I called this the "BusinessPipe" for my project.

[WebService(Namespace="http://tempuri/")]

[XmlInclude(typeof(CustomerData)),XmlInclude(typeof(OrderData))]

public class BusinessPipe : System.Web.Services.WebService

{

          private const string BUSINESS_ASSEMBLY = "My.Business.Assembly";

          #region Component Designer generated code

          //Required by the Web Services Designer

          private IContainer components = null;

          ///

/// Clean up any resources being used.

          ///

          protected override void Dispose( bool disposing )

          {

                    if(disposing && components != null)

                    {

                             components.Dispose();

                    }

                    base.Dispose(disposing); 

          }

          #endregion

 

          private Type AccessType(string typeName)

          {

                    Type type = null;

                    Assembly assembly = System.Reflection.Assembly.Load(BUSINESS_ASSEMBLY);

                   if(assembly == null)

                             throw new Exception("Could not find assembly in BusinessPipe! Assembly: " +

                                                         BUSINESS_ASSEMBLY);

                             type = assembly.GetType(BUSINESS_ASSEMBLY + "." + typeName);

                             if(type == null)

                                       throw new Exception("Could not find type!\nAssembly: " + BUSINESS_ASSEMBLY +

                                                                   "\nType: " + typeName);

                                        return type;

          }

          ///

          /// Executes a method on the Business Logic and returns whatever object that method returns.

          ///

          /// The class in the Business Logic to reference.

          /// The method that you want to execute in the class.

          /// The arguments to send to the method.

          /// The same object that the business logic method returns.

          [WebMethod]

          public object ExecuteMethod(string typeName, string method, params object[] arguments)

          {

                   object returnObject = null;

                   Type type = AccessType(typeName);

                   try

                   {

                             returnObject = type.InvokeMember(method,

                             BindingFlags.Default | BindingFlags.InvokeMethod,

                             null, null, arguments);

                   }

                   catch

                   {

                             //Do some custom exception handling here.

                             throw;

                   }

                   return returnObject;

          }

          ///

          /// Executes a method on the Business Logic and returns the same ArrayList that the method returns.

          ///

          /// The class in the Business Logic to reference.

          /// The method that you want to execute in the class.

          /// The arguments to send to the method.

          /// The same object that the business logic method returns.

          [WebMethod]

          public ArrayList ExecuteArrayMethod(string typeName, string method, params object[] arguments)

          {

                   ArrayList returnObject = null;

                   Type type = AccessType(typeName);

                   try

                   {

                             returnObject = type.InvokeMember(method,

                             BindingFlags.Default | BindingFlags.InvokeMethod,

                             null, null, arguments) as ArrayList;

                   }

                   catch

                   {

                             //Do some custom exception handling here.

                             throw;

                   }

                   return returnObject;

          }

}

Notes:

Notice how, at the top of the web service, I have included two XmlInclude statements. These two statements are required so that the framework knows how to serialize the OrderData and CustomerData objects. Also, the assembly which contains your business logic MUST be referenced from the web service. If it is not, your web service will have no idea how to get to the assembly. One last thing - notice that there are actually two public methods for this web service - ExecuteMethod() and ExecuteArrayMethod(). This is because the web service will not correctly serialize an ArrayList if the return type is not ArrayList.

Disadvantages:

There are a couple of disadvantages to this approach:

  1. You lose intellisense for the web service and it's method. This is a disadvantage if you're planning on having your web service be consumed by another party, or if you have developers who are unfamiliar with the business logic code.
  2. There is no built-in security to restrict the methods in your business logic that are accessible

While these are certainly issues, I feel that they can be addressed and corrected relatively easily:

  1. To allow intellisense, you could easily create 'proxy' classes that do nothing more than hand off requests/responses to/from the web service. However, this takes away one of the advantages of the dynamic web service, since you would then have to keep the proxy class in-sync with the business classes.
  2. To provide security, you could use custom attributes to define which business logic methods are visible, and which are not. This would be relatively easy to accomplish by using reflection to check the attributes before calling Type.Invoke().


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Zach Smith
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Consumer by Mike On May 1, 2006

Great article, I used your code in a Web Service and I am able to invoke the methods from a consumer.  However, I am having difficulty with the consumer side.  For example, I thought I could use this as a clever way to trick web services to deliver a datatable in the result set.  Unfortunately, I am getting an error:

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type System.Data.DataTable may not be used in this context. To use System.Data.DataTable as a parameter, return type, or member of a class or struct, the parameter, return type, or member must be declared as type System.Data.DataTable (it cannot be object). Objects of type System.Data.DataTable may not be used in un-typed collections, such as ArrayLists.
  at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType)
  at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType)
  at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write3_ExecuteMethodResponse(Object[] p)
  at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer1.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
  at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
  --- End of inner exception stack trace ---
  at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
  at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle)
  at System.Web.Services.Protocols.SoapServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)
  at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)
  at System.Web.Services.Protocols.WebServiceHandler.Invoke()
  --- End of inner exception stack trace ---

Any ideas on how I can make this work?  My goal is to be able to send the entire business object to the consumer so that it can use the data and the methods as well.  Thanks for your help in advance.

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved