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

http://www.asp.net/downloads/archived/migration-assistants/php-to-aspnet/

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.

Conclusion

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. 

Taggedmail profile

by Damiaan Peeters 4. January 2010 15:29

This is weird.  Yesterday my traffic on my side got some new traffic.  The website stats showed me (after a little bit of digging), the following figures.

image

Traffic with all the same keyword: “taggedmail profile”.  There were also some visits for the “tagged mail profile”, but much less.  The traffic initiated from different countries, but the majority came from Portugal.  I normally never get traffic from Portugal.    All traffic landed on this page: http://blog.dampee.be/?tag=/mail+profile.  It’s true, the tag “mail profile” is there.  But I doubt it was what they where searching.

I don’t know what it means.  I search Google, I searched Bing.  But couldn’t find any reasonable explanation. My guesses are:

  • spam bots searching for user profiles for email addresses. 
  • some company takeover of which i am not (yet) aware
  • someone interested in buying taggedmail.com (currently pointing to tagged.com)

After these ideas came up, I started searching TechMeme, Mashable and TechCrunch.  But none of them supplied me with some answers, expect for the CSE from Techcrunch: How do I get rid of tagged spam from taggedmail.com? Maybe some spam was send out from the domain taggedmail (.com, .net, …).  But what with the profile keyword?

If someone has any idea, I’ll read it in the comments.

Google Public DNS speed tested

by Damiaan Peeters 7. December 2009 12:53

A lot of blog posts, coming from Google have to do speed. It is all about a faster internet today.  And to help you, Google announced their public DNS services

I learned that not any statement made by major sources are true.  Before, configuring the DNS settings, I downloaded a free tool called Domain Name Server Benchmark, and started 2 times a benchmark rounds. These were launched from a corporate network up with an upstream connection to COLT. 

image

The Google public DNS servers (8.8.8.8 and 8.8.4.4) were not present in the fastest segment of the results produced by the 2 benchmarks I have launched.  The only advise, apart from any possible privacy concerns, is that you shouldn’t use (any) name server without first testing its speed.  There might be public facing DNS servers near you providing faster results.

Html Encoding and Decoding

by Damiaan Peeters 17. October 2009 16:27

If you want to be sure of reliable transmission over HTTP, it is advisable to HTMLEncode your text.  Another purpose to use HtmlEncoding, is to embed text in your XML files. 

You can use the HttpUtility class which i mentioned in this previous post: UrlEncode for a hyperlink without a HTTPContext

I used this time MSDN to find back the HtmlEncode method. You can find here: HttpUtility Members on MSDN

Tags:

Famous .Net websites found on the web (Part 2)

by Damiaan Peeters 1. September 2009 10:30

Ok, I admit.  I know my blogging rhythm is very low this year, it's about the opposite of my 'normal' day-to-day life rhythm. But I prepared in the past months this blog post…

From time to time I stumble upon famous web sites using .Net (part 1).  I would like to add some sites to the list.

Let me know if know any other big web sites using .Net technology, so I can complete the list.

TeamViewer – Desktop Sharing over the internet
image
Intel Download Center
image
Hardrock Café’s Memorablia  using Silverlight technology, Deepzoom.
image

Have you ever tried zooming really deep?  Look at this post: How to really show of with deepzoom

CRDC.Be - Official Belgium Database for Number Portability
image

Stanford Engineering – Sub site of university

image

Rabobank.be – online bank (and know sponsor of cycling)
image
DoubleClick – online advertising
image
International Telecommunication Union
image

Tags:

.Net

How to really show off Deepzoom technology

by Damiaan Peeters 31. August 2009 11:57

What is Deepzoom

Deepzoom is a product build on Silverlight technology.  It gives you the ability to smoothly zoom and pan on images.  The loading time is incredibly short because only parts of images are send over the network. This type of browsing can be compared with viewing imagery on google maps, live earth.

A nice example is the Memorablia of the HardRock café.  I searched for a guide on the internet, on how to get as deep as possible on the pictures.  This examples goes even a few levels deep.

If you search on the web for Deepzoom, you will find much more details and explanation.

Where to start

Go to http://memorabilia.hardrock.com/

and look for “Paul McCartney – The Beatles Letter from Paul and Beatles autographs”.  (Item number: 043311).

Finding this item, can be easily done by:

  • be clicking on “The Beatles” on the left side, or
  • use the search on the top right of the screen like this:
    image   or image

The item you are looking for is this one: 
 image

Go deeper

Have you already noticed the stamp on the left top of the envelop?  That is where you should go.  Use your mouse scroll wheel to enlarge this item.

As you will see this is not a normal stamp.  These are pictures of various buildings.  (Does anyone know which buildings these are?)

image

Zoom into the picture of the 3th row, 2nd column.  If I’am not mistaken, this is the Seattle hardrock Café.

image

If you thought this is cool, go to left below the middle of the image, you will see some white suites

image

image

Then zoom in on “The Beatles” Doll's image in the middle.

image

This last doll’s are available as a separate item  in Memorablilia: The Beatles “Bobb’n Head” dolls, and is available under Item number 051228.  The cool thing is, this contains some embedded video as shown below (click More Info – Video).

Do it yourself

You can make yourself Deepzoom content by using deepzoom composer.  Try it out, and let me know if you archived something spectacular.

UrlEncode without HttpContext

by Damiaan Peeters 25. August 2009 12:19

Yesterday I had to use the UrlEncode function.  UrlEncoding is used to converts all illegal characters in a URL to valid characters.  For example the space will be converted to %20.

Fortunately the .Net Framework supplies a UrlEncode method on its Server Class.  The server class resides in the HttpContext.  The problem is that you need a HttpContext Instance to call this class.

Using Reflector, I found out that the UrlEncode method on the Server Property uses the HttpUtility class.

image

So, instead of using this: HttpContext.Current.Server.UrlEncode(text)
you can also use: HttpUtility.UrlEncode(text)

The only thing to use this is to include the System.Web assembly in your project.

Managed Extensibility Framework Introduced By Bart

by Damiaan Peeters 19. August 2009 17:54

I have been thinking several years about how to implement Extensibility in a decent manner for one of my applications.  The problem is that as a sole freelance developer, implementing extensibility is not something you NEED.  It is more a ‘nice to have’.  At the end of 2008, I found the MEF (Managed Extensibility Framework).  But due to a lack of time and lack of articles about it, never started investigating into it.  I admit, I do not always jump on the newest beta technologies right away.

Unfortunately, when you search for some information on the MEF CodePlex website on how it exactly works, it doesn’t really encourage you to read further…  Try to dive in the first to links on the topic “Where to go next”

  • First there is:  Learn more about MEF .  Completely correct, but a 100% cryptic message for dummies.  Telling someone you have to start with a container or a catalog without explaining what a catalog or container is, is not very convincing.
  • Or take the programming guide, just a few steps to do very complex things.  My problem was not “how to”, but I wanted to understand what I was doing.  Adding references adding class or method attributes can be done by my little sister, but would she know what she has done?  I Guess not, I even bet she doesn’t understand these terms.

So, I watch out for months about articles covering the Managed Extensibility Framework (MEF).  Articles explaining the basics. Telling me what it exactly is, or what the basics are.  Some sort of “Hello World” for advanced programmers, but “MEF dummies”.

Earlier this week I found the article an article, written by a Belgian fellow, now working in Microsoft Redmond.
His blog posts tend to be very technical material for advanced LINQ adepts or Expression Tree lovers. This time he covered “MEF for Dummies”, just what I needed.  I’ve written before about the mouse-hating code-lover called Bart De Smet. (See a previous post “Bart De Smet gone mad about extension methods”.) 

Bart proved his excellent writing capabilities in his blog post written earlier this month. If you are interested in MEF, then read  A Whirlwind Tour through the Managed Extensibility Framework.  I highly recommend it.

Congratulations Bart, it was easy to read, even humorous. And most of all it was very understandable.  Thank you very much!

Tags: ,

.Net

Bing indexing obsolete page of Post.Be

by Damiaan Peeters 11. August 2009 12:27

De national Post service of Belgium, has changed it’s site and Bing managed to indexed the obsolete page…  Look at the URL: www.post.be/site/nl/obsolete.html.  I was curious and tried to find out why Bing gave me the wrong result.

bing search depost.be

Ok, i admit.  It was not the best search i have done.  Searching for post, would give the good result. 

Anyway, this is a screenshot of the web page:

"page unavailable" Post.be

See the text at the top?  It’s Dutch and French.  Translated into English it says: “This page is not available anymore, click a link below to visit our new site”.   I didn’t got it.  If the page does not exists anymore, was Bing wrong indexing it? 
No!  Bing got it right (sort of).  It was in fact the webmaster of Post.be who forgot something.

Explanation

The page you are entering is for a normal visitor a standard NOT FOUND page.  When visiting a page which doesn’t exists, the server should give a 404 status in its response.  The HTML can be customized like the screenshot above for an improved user experience.  But crawlers & indexers need the correct status.  In this case a 404 error.

When you investigate all requests send to the web server, every requests gets a 200 Status code: “Successful”.  I used Fiddler to verify the page request:

fiddler result of the URL

As anyone can find on the web, it tells the visitor that the request was successful.  Not a single 404 status code can be found in the second column.

A user centric solution

For a better user experience, it would have been nice of “De Post” to redirect me automatically to the new homepage.  The page I was visiting here was obviously an obsolete page.  This can be done in HTML using a Meta Refresh Tag.  Looking at the HTML source, no redirect is made.

HTML source of the web page

It would have been more user friendly, but not the best solution.

What about 301

A 404 would have been a good start.  Bing, Google and other search engines would not mention the result in their SERPs for long. I guess de webmaster of “De Post” must have had some reason not to use a 301.  A 301 is a status code telling the visitor (human or not) that the page has moved permanently to a new place.  Together with this status code the new URL is supplied.

What exactly happens when a 301 is send from the web server back to the visitor?

A human visitor

The browser (Internet Explorer, Firefox, …) of the visitor will notice the 301 status code and load the new page supplied with the 301 status code.  The end user might notice a new page is loaded because the shown URL in the browser will be updated.

A Bot / Spider

A spider or a bot will notice the 301 also, and will remove the old URL from their index and update it with the new URL.  Using a 301 has major advantages when migrating to a new site because you can retain all page rank from any incoming links.

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: , ,

C#

Who.I.am

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

Month List