Convert C# and VB.NET
If, like me, you post pieces of code for others to view, I imagine you'll often do so in the language of your choice (and more than likely it will be C# or VB.NET). However, for some beginners it's often quite hard to grasp these examples if they are written in a language you are not familiar with.
I had this scenario when one of the visitors to my site wanted to see an example in C#, but I had written the article using VB.BET. It wasn't too hard for me to convert it, but it did mean that I had to write the example twice. I looked around for an automatic converter that would help me do this, and by far the best one I found was the one from Carlos Aguilar Mares. His Code Translator allows you to enter some in code in either C# or VB.NET and it will output the code in the opposite langauge. The beauty of how he coded the translator is that it is done via an "ashx" handler. After speaking to Carlos, I decided that I'd try to implement this automatically on my site my calling his handler directly (you can see an example of it in action here).
To call his handler, I simply had to make a httpWebRequest, pass in the "from" and "to" language, let his handler do it's magic and then read the response by using httpWebResponse. I've broken the way I do it down into a simple function just for demonstration purposes (my site uses a few Regular Expressions in case I have more than one example on the page) but in it's basic form, this is how it can be done:
<!DOCTYPE html PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
Partial Class Default1
Protected Sub Page_Load(ByVal
sender As Object,
ByVal e As
System.EventArgs) Handles Me.Load
CarlosAGConvertVBNETToCSharp("Dim s As
Public Function CarlosAGConvertVBNETToCSharp(ByVal Code As String) As String
strURL As String
strPostData As New
strResult As String
wbrqLogin As HttpWebRequest
wbrsLogin As HttpWebResponse
swLogin As StreamWriter
srLogin As StreamReader
' Set the URL to post to and the login info to post
strURL = "http://www.carlosag.net/Tools/CodeTranslator/Translate.ashx"
' Create the string to send to the web service
the web request
wbrqLogin.Method = "POST"
wbrqLogin.ContentType = "application/x-www-form-urlencoded"
wbrqLogin.CookieContainer = New CookieContainer
' Post the
swLogin = New
' Read the
wbrsLogin = wbrqLogin.GetResponse
srLogin = New
ex As Exception
"Sorry, an error occurred. You can try manually
converting your code by going to <a href=""http://www.carlosag.net/Tools/CodeTranslator/Default.aspx"">http://www.carlosag.net</a>."