Converting a PHP API to a C# implementation

by Damiaan Peeters 11. January 2010 13:32

I have this web service I want to use. The supplier only provides a PHP example to use the API. It is not a standard SOAP or REST service, but a custom Http POST based command.  This means that you that you either have to write

Because I had no Visual Studio installed, ready to be launched, i used the command line conversion. 

C:\Program Files\Microsoft Corporation\PHP to ASP.NET Migration Assistant>PHPConvert.exe "c:\source\PhpSource" /out "C:\source\AspDotNetVersion”

The port of the code was successful. Most of the code was converted to c#.  A lot of conversion warnings popped up, but most of them where not imposing any severe problems.

Code clean-up

A manual code clean-up is advised.  For example, this code comes clearly from an unmanaged environment:

  1. dpublic virtual void  useSecure(bool val)
  2.         {
  3.             if ((val == true) && (val.GetType() == true.GetType()))
  4.             {
  5.                 this.Secure = true;
  6.             }

Why should you check the type of “val” at runtime?  This is already done by the compiler.  A simple “ if (val== true) “  would be sufficient.  Or in this case even shorter:

  1. d        public virtual void useSecure(bool val)
  2.         {
  3.                 this.Secure = val;
  4.         }

Other things to clean up are links to magic-quotes, cURL and other specific PHP stuff.

Calling the API

Calling the API means in PHP that you do a socket write and read. For example, in PHP one would do:

$sock = fsockopen("ssl://".$this->ApiUrl["host"], 443, $errno, $errstr);

Because every effort is done to maintain the original architecture by the conversion tool.  The convertor tool added a PHP namespace containing extra support classes for duplicating the original (php) functionality. The previous line of code is thus converted to:

sock = PHP.NetworkSupport.OpenSocket("ssl://" + this.ApiUrl["host"], 443, errstr);

The OpenSocket function is a wrapper function with one line (with some additional simple error handling):

returnValue = (System.Net.HttpWebRequest)System.Net.WebRequest.Create((System.String)Target); // + ":" + System.Convert.ToInt32(Port));

Although this is neat, I like the native .Net HttpWebRequest and HttpWebResponse Classes.  So I took the code from my previous blog post: Http Post using C#, adapted it a bit and removed almost 80 lines of the converted code.

My problem with the wrapper functions created by the convertor tool, is that they use System.Object parameters and also return a System.Object.  So for readability and maintenance reasons, I started immediately converting this to some strongly typed code.


I was very pleased with this tool.  I saved literally hours typing, and it took me (only) a few hours of refactoring.   Refactoring meant:

  • removing unused functionality (magicQuotes, cURL, …)
  • removing unnecessary type checks using Relfection
  • removing calls to wrapper functions when I had decent managed .Net code available in my library

And just now I started thinking that it may have been faster implementing a custom WCF implementation. 

ConvertAll using lamba

by Damiaan Peeters 4. July 2009 17:41

When we are using generic lists, we always used a delegate when converting a List<int> to a List<string>.  This is very easy using the know ConvertAll method.
Normally, we should call it like this:

List<int> l1 = new List<int>(new int[] { 1,2,3 } );
List<string> l2 = l1.ConvertAll<int>(delegate(string s) { return Convert.ToInt32(s); });

Now that we are using .Net3.5 we can use also lambas, so your code changed now to this:

l2= l1.ConvertAll(s => return Convert.ToInt32(s) );

Pretty readable imho…

Tags: , ,


Implementing Finalize and Dispose to Clean Up Unmanaged Resources

by Damiaan Peeters 2. March 2008 12:04

I found some design patterns about implementing Dispose & Destructors in C#.

Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize on an object (destructor syntax in C# and C++). The garbage collector calls this method at some point after there are no longer any valid references to the object.

Implementing Finalize and Dispose to Clean Up Unmanaged Resources

Bart De Smet gone mad about Extension methods

by Damiaan Peeters 7. January 2008 16:56

Our beloved Bart De Smet has gone mad.  Complete insane.  He started to add some Extension Methods to do Exception handling. 

He writes the following on his blog:

What a joke you must think when reading this post's title. Isn't the functional paradigm all about side-effect free programming and the such? Well, it turns out you're absolutely right. So, why this post? I have to admit I had yet another crazy Sunday afternoon idea that I found worthwhile to open VS 2008 for and give it a short.  Exception Handling in functional style - B# .NET Blog

You read it well.  "Another crazy Sunday".  It appears that working at Microsoft has some side effects.

Apart from the crazy Sundays Bart, created to a few 5 star Webcasts about C# 3.0.

Connectionstring in another Project (DLL)

by Damiaan Peeters 1. January 2008 16:49

I always put my datalogic into a different project.  Like this i can reuse my DL in other projects with the same purpose or customer.  [more]

To change or get a connectionstring is normally impossible because the Settings class is declared as internal.  This means that the complete project is able to access this property, but other projects (dll's) are not allowed to access this property.

If you try to access this, you will see get an error like this:

'DamPee.MyProject.DL.Properties.Settings' is inaccessible due to its protection level   

If you open the Settings, you will see the Access Modifier.  Change this to Public.



Now you will be able to access the Settings (including the connectionstrings) in your other projects.

connection.ConnectionString = global::DamPee.MyProject.DL.Properties.Settings.Default.MyProjectConnectionString;

Certified Umbraco Master, Part of Umbraco Certified partner comm-it, .Net and Azure developer, seo lover. Magician in my spare time.

Month List