Using Response.Redirect in try…catch block

Using Response.Redirect in a try catch block in C#.Net will throw an exception “Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.”.

To work around use the overloaded method Response.Redirect(String url, bool endResponse) and pass false to second argument. The detailed reason can be found at http://support.microsoft.com/kb/312629/EN-US/.

REST Web Services calls with C#

It’s really easy to call REST based web services from C#.Net. Let’s see how to do it. We’ll be calling Yahoo Web Services as an example here.

Make REST Calls With C#

The .NET Framework provides classes for performing HTTP requests. This HOWTO describes how to perform both GET and POST requests.

Overview

The System.Net namespace contains the HttpWebRequest and HttpWebResponse classes which fetch data from web servers and HTTP based web services. Often you will also want to add a reference to System.Web which will give you access to the HttpUtility class that provides methods to HTML and URL encode and decode text strings.

Yahoo! Web Services return XML data. While some web services can also return the data in other formats, such as JSON and Serialized PHP, it is easiest to utilize XML since the .NET Framework has extensive support for reading and manipulating data in this format.

Simple GET Requests

The following example retrieves a web page and prints out the source.

C# GET SAMPLE 1


using System;
using System.IO;
using System.Net;
using System.Text;
// Create the web request
HttpWebRequest request = WebRequest.Create(“http://developer.yahoo.com/”) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}

Simple POST Requests Some APIs require you to make POST requests. To accomplish this we change the request method and content type and then write the data into a stream that is sent with the request. C# POST SAMPLE 1

// We use the HttpUtility class from the System.Web namespace
using System.Web;
Uri address = new Uri("http://api.search.yahoo.com/ContentAnalysisService/V1/termExtraction");
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Create the data we want to send
string appId = "YahooDemo";
string context = "Italian sculptors and painters of the renaissance"
+ "favored the Virgin Mary for inspiration";
string query = "madonna";
StringBuilder data = new StringBuilder();
data.Append("appid=" + HttpUtility.UrlEncode(appId));
data.Append("&context=" + HttpUtility.UrlEncode(context));
data.Append("&query=" + HttpUtility.UrlEncode(query));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
    postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    // Get the response stream
    StreamReader reader = new StreamReader(response.GetResponseStream());
    // Console application output
    Console.WriteLine(reader.ReadToEnd());
}

HTTP Authenticated requests

The del.icio.us API requires you to make authenticated requests, passing your del.icio.us username and password using HTTP authentication. This is easily accomplished by adding an instance ofNetworkCredentials to the request.

C# HTTP AUTHENTICATION

// Create the web request
HttpWebRequest request
= WebRequest.Create("https://api.del.icio.us/v1/posts/recent") as HttpWebRequest;
// Add authentication to request
request.Credentials = new NetworkCredential("username", "password");
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    // Get the response stream
    StreamReader reader = new StreamReader(response.GetResponseStream());
    // Console application output
    Console.WriteLine(reader.ReadToEnd());
}

Error Handling

Yahoo! offers many REST based web services but they don’t all use the same error handling. Some web services return status code 200 (OK) and a detailed error message in the returned XML data while others return a standard HTTP status code to indicate an error. Please read the documentation for the web services you are using to see what type of error response you should expect. Remember that HTTP Authentication is different from the Yahoo!Browser-Based Authentication.

Calling HttpRequest.GetResponse() will raise an exception if the server does not return the status code 200 (OK), the request times out or there is a network error. Redirects are, however, handled automatically.

Here is a more full featured sample method that prints the contents of a web page and has basic error handling for HTTP error codes.

C# GET SAMPLE 2

public static void PrintSource(Uri address)
{
    HttpWebRequest request;
    HttpWebResponse response = null;
    StreamReader reader;
    StringBuilder sbSource;
    if (address == null) { throw new ArgumentNullException("address"); }
    try
    {
        // Create and initialize the web request
        request = WebRequest.Create(address) as HttpWebRequest;
        request.UserAgent = ".NET Sample";
        request.KeepAlive = false;
        // Set timeout to 15 seconds
        request.Timeout = 15 * 1000;
        // Get response
        response = request.GetResponse() as HttpWebResponse;
        if (request.HaveResponse == true && response != null)
        {
            // Get the response stream
            reader = new StreamReader(response.GetResponseStream());
            // Read it into a StringBuilder
            sbSource = new StringBuilder(reader.ReadToEnd());
            // Console application output
            Console.WriteLine(sbSource.ToString());
        }
    }
    catch (WebException wex)
    {
        // This exception will be raised if the server didn't return 200 - OK
        // Try to retrieve more information about the network error
        if (wex.Response != null)
        {
            using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
            {
                Console.WriteLine(
                "The server returned '{0}' with the status code {1} ({2:d}).",
                errorResponse.StatusDescription, errorResponse.StatusCode,
                errorResponse.StatusCode);
            }
        }
    }
    finally
    {
        if (response != null) { response.Close(); }
    }
}

Further reading

Related information on the web.

How to kill your time by hardcoding?

My colleague asked me to help him solve an issue he was facing. I sat with him and after spending more than half an hour I realized that someone has hardcoded the server name :@ while we were assuming that we have already moved to another server.

The main thing to realize here is that if we have spent few more minutes in making the server name configurable at first place then we could have saved hours that we spent later just to find out that server name was hard-coded. Not doing this results in frustration, waste of time, de-motivation, brings down the moral of the team, and finally kills productivity and you lose credibility.

Threads in Perl without using thread module

Threads are not good in Perl. If you want to know why, you can read PerlMonks article here. But C/C++ threads are good 🙂 How can you leverage the benefit of C/C++ threads in Perl? Well, if you have a C/C++ library which is multi-threaded then you can write a Perl wrapper on C/C++ library. For writing a wrapper you can use Inline::C or Inline::CPP module, that provides a very gentle and easy way to wrap up your C/C++ calls.

What happens is that if you call a C/C++ function which uses threads from a Perl script/process, it will make your Perl process multi-threaded. You can see this by using -m option of ps if you are on Linux platform.

I was working on a Perl based project and I used a multi-threaded C/C++ library. I was curious how will it work. I ran the Perl process and when I see the process in ps with -m option, it was showing two processes, actually one process and second was the thread. When I was using a single threaded library it used to show only a single process in ps. I also tested the functionality which was supposed to use the multiple threads and it worked as expected.

I think this is a better way to use threads in Perl if you really need threads, instead of using thread module of Perl. If you are not desperate, then try to stick with single threaded model of Perl, or use Perl wrapper over C/C++ multi-threaded library.

How to setup PHP development environment in Eclipse?

As I am currently working on Joomla (http://www.joomla.org/) a CMS built in PHP, I came across a very nice tutorial about how to setup your development environment if you want to work on Joomla. Although the tutorial is specific to Joomla, PHP, and Eclipse, but in general it is a very good tutorial and one can learn how to setup a development environment for any project irrespective of technology used. Especially novice programmers will learn a lot from it.

Author first explained how to install and configure XAMPP, then configure PHP and XDebug to debug the PHP applications. Then author explained how to install Eclipse, setup your workspace, configure it for debugging. Then author created a test project and ran it in debug mode. Then in the end author explained how to install and configure subclipse (Eclipse SVN plug-in) and how to import a project from SVN repository.

This is a very nice tutorial in general and specifically for those who work in Eclipse and PHP. Wanna read it? go ahead: http://docs.joomla.org/Setting_up_your_workstation_for_Joomla!_development

Breaking problem into code

Let us consider an example. If you have two boxes say BoxA and BoxB, and there are few balls of different colors, let’s say 5 balls (red, blue, green, yellow, and white) in BoxA, and you want to move one ball, say red ball from BoxA to BoxB. What will be the steps? If you can make a flow chart of it then its good, but if you find it difficult to make a flow chart of it then you need to do some hard work to become a programmer.

I asked this to someone and guess how he solved it. Here is his solution. Take out all balls from BoxA, then pick the red ball, put it in BoxB, and then put all remaining balls back in BoxA.

Fine! it worked. But why would you take out all balls if you can only take out red ball and move it to next box?

Let’s move this to programming side. In the above mentioned scenario we will have two database tables, boxes, and balls. boxes will have boxid as PK, name, and other details. Keep it simple so we don’t get lost in other details. balls table has ballid as PK, name, boxid as FK, and other details. boxes table has two records with 1 and BoxA as its boxid and name. balls table will have 5 records with id between 1 to 5 and red, blue, green, yellow, and white as their names, and all balls will have 1 in boxid field which is FK to boxes table.

Now if we adopt the first solution then it will run following queries (these are pseudo queries not actual SQL queries):

– select all balls where boxid=1 (so we can have a list of all balls before deleting them from database)
– delete from balls where boxid=1
– insert into balls values ballid=1, name=red ball, boxid=2
– insert into balls values
(ballid=2, name=blue ball, boxid=1)
(ballid=3, name=green ball, boxid=1)
(ballid=4, name=yellow ball, boxid=1)
(ballid=5, name=white ball, boxid=1)

Or even worse if we use multiple insert queries. It will run from 4 to 7 queries.

Now let’s see what happens if we just perform operation on the red ball and don’t touch other balls.

– update balls set boxid=2 where ballid=1; /* ball with id 1 is the red ball */

Wow, just one query and we’re done! We saved 3 to 6 queries. Imagine this scenario for a high traffic website or any other application, we can improve the performance with a big difference by just implementing correct logic to solve a problem.