Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
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.

Page Views : 19379
Downloads : 0
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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().

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
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 | Modify 
good thought .. but not practically good one by Vinod On May 7, 2010

The design looks unique and tries to show the use of reflection. But I am not convinced about one aspect. You are oepning gates for users of your webservice to pass class and method names of business logic to provide the service they require. Are we not compromising to a large extent by asking the client application to provide the class and method details to be invoked. I may be wrong. Please explain.

Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.