Archive for the ‘.Net’ Category

Breaking encapsulation with C# 2.0 partial classes (moved posting)

March 23, 2010

For good or bad partial classes in C# 2.0 allows breaking of encapsulation as this example will show.

In a consulting job I recently ran into an interesting case involving a webservice with several different service methods f1, f2, fn (sample names, not actual names) all taking the same string argument and all returning a string. The user would select an operation name after which my code had to call the named operation on a web service using a standard parameter. Trivial really, if one would do accept bad code like this below, but I don’t:

 String operationName = …
 String arg = …
 Webserviceproxy webserviceproxy = …
 // Warning: Badly coupled code begins here (need to update each time we  add/rename/delete operations).
 switch (operationName) {
 case “f1″: return webserviceproxy.f1(arg); break;
 case “f2″: return webserviceproxy.f2(arg); break;
 }

What is really needed is a method to invoke a webservice method by name, while still using the generated .NET proxy to do the hard soap/http stuff (no time to reinvent a better wheel here). Reflection is one way to do this, but let’s try another type-safe method for this posting, because the technique shown here is quite powerful for all sorts of related problems:

Let’s look at an extract of the generated proxy:

public partial class Webserviceproxy :  System.Web.Services.Protocols.SoapHttpClientProtocol
 {
  …
  public string f1(string arg) {
   object[] results = this.Invoke(”f1″, new object[] {arg});
   return ((string)(results[0]));
  }
  …
 }

and at the inherited SoapHttpClientProtocol:

 public  class SoapHttpClientProtocol : HttpWebClientProtocol {
 
  protected object[]  Invoke(string methodName, object[] parameters) {
 
  }
 
  }

It seems the method “invoke” would fulfil our needs if it was only public (which it isn’t). So what do we do? Certainly we do not want to modify the generated file (and lose our changes each time it is regenerated).

The good news is that Generatedwebserviceproxy is a partial class so we can extend it with the following code. We will place the code in a file safely outside the generated proxy class file:

public partial class Webserviceproxy :  System.Web.Services.Protocols.SoapHttpClientProtocol
 {
  ///
  /// Dynamic operation that allows us to call an operation by name.
  ///
  public string InvokeAny(String operationName, string arg)
  {
   object[] results = this.Invoke(operationName, new object[] {arg});
   return ((string)(results[0]));
  }
 }

The compiler will merge the two class definitions effectively adding a new public InvokeAny method to the generated class. And now we can call our web service calls dynamicly from using InvokeAny:

 String operationName = …
 String arg = …
 Webserviceproxy webserviceproxy = …
 return webserviceproxy.InvokeAny(operationName, arg);

Clearly, easy to do and with better overall code than a “switch” – even though it is not without drawbacks as it breaks encapsulation of the generated proxy.

Post scriptum:
Used the same partial classes trick today to add a common custom interface to two differently generated proxies. I now officially miss this feature in Java (yes, AspectJ can do the thing but it is not a official part of the language).

Recent update and notice:

This post an almost identical copy from my old blog at “http://www.mortench.net/blog” which I will shortly retire for good.

Asp.net MVC framework

October 12, 2007

And so it happened… Microsoft acknowledged that not all developers like the whole event driven/viewstate model.

Other web frameworks like the MVC model has been used for years on other platforms, alternatives like MonoRails have existed on the .net platform with a small loyal crowd of developers.

But now…. (my guess is because the whole buzz about Ruby on Rails and its MVC model) Microsoft launches their own MVC framework:

http://codebetter.com/blogs/jeffr…mvc-framework-at-alt-net-conf.aspx

At last… I can’t wait to try it out and to see how adoption goes.

Shooting yourself in the leg with a bazooka

July 13, 2007

The colorful title reflects that this posting is about common mistakes done by good but relatively inexperienced software developers. Big mistakes that a developer actually need quite some skills to make. Mistakes that we unfortunately see all too often and we would rather not see much of again (hopefully this blog entry can aid a bit towards that goal):

  1. Overly complicated design – Instead of a simple design for a simple project some developers insist on using a impracticable mix of all the newest, fanciest abstractions, design patterns, techniques and advanced language constructs that can possibly be combined in one software solution. All design elements have benefits and drawbacks. Great (experienced) developers know when a particular benefit of an abstraction, pattern, technique or feature outweighs the drawbacks. There is no silver bullet. No design element works well in all situations (just as no rules that you learned in “programming school” are in fact absolute). Developers that get way too eager ends up with one big unmaintainable design mess with the combined drawbacks of all decisions but few if any real benefits remaining…. Remember, a simple design is a beautiful design!
  2. Writing too much code – Writing lengthily code with a high maintenance cost by hand when writing such code can be avoided. Much code can be avoided by choosing a more suitable design/architecture, using standard framework/library features (xml serialization is a common example), using techniques such as dynamic reflection or specialized code generation and aspect oriented tools (be careful though).
  3. Reinventing the wheel – Some developers think they can write their own code much faster than learning to understand the underlying framework and available libraries. This might in some cases even be true, but when considering overall quality and maintainability (which developers seldom do) reinventing the wheel is almost always a bad idea.
  4. Incorrect use of advanced concepts such as multithreading – Some developers use multithreading without the discipline and deep understanding that writing correct, safe multi-threaded code requires. Multithreading can improve the user experience immensely. It is also the answer to scalability nowadays. However, before even considering to use multithreading in your design, make sure to know the theory and features in your environment well. A vague recollection of mutexes and semaphores from school is not good enough. You should also realize that by deciding to use multithreading, you generally need to upgrade on testing, documentation, reviews and quality insurance.

Design a site like this with WordPress.com
Get started