Consuming URL Shortening Services – X.co

هذه المقالة متوفرة أيضا باللغة العربية، اقرأها هنا.

Read more about URL shortening services here.

Source- Elsheimy.Samples.ShortenSvcs.zip

Contents

Contents of this article:

  • Contents
  • Overview
  • Introduction
  • API
  • WCF Services
    • Squeeze Service
    • Reporting Service
  • RESTful Services
    • Squeeze Service
    • Reporting Service
  • Source Code
  • What’s next

Overview

This is another article of our URL shortening services series. This article is talking about X.co shortening service provided by Go Daddy. If you don’t know how to access this service from your .NET application, then it’s the time to.

We’ll have a complete discussion of the WCF services offered by X.co. Then, we’ll consider the RESTful interfaces provided.

Introduction

Today we are going to talk about one of the most popular URL shortening services on the web now; it’s the new X.co provided by Go Daddy, the dominating domain names and web hosting service provider.

While X.co is considered very new since it has released just few months ago, it gained support from users worldwide very quickly, and now it’s one of the most popular shortening services exist in the web. Although the interface provided to users doesn’t offer great functionality, the API interface it provides really deserves respect since it’s one of the most easiest yet powerful APIs (for shortening services) exist on the web now.

API

The most noticeable thing about X.co API is that unlike other APIs it’s based on ASP.NET and WCF (WOW!) Moreover, the WCF service provides you a RESTful interface. Thus, you end up with two interfaces, one is based on WCF, and other is a REST web service.

You might not be familiar with WCF or other new technologies related to versions higher than .NET 2.0, don’t worry it’s just a matter of names! You use WCF services the same way as with ordinary Web Services.

In this writing, we’ll first talk about WCF/Web service interfaces provided to you by X.co. After that, we’ll have a look at how RESTful interfaces fit in the picture.

Before we begin our discussion, you’ll need to grab your API key that’s required by all functions for authentication. To get your API key, first create a free account at http://www.godaddy.com if you don’t have one yet. Figure 1 shows the registration page.

Figure 1 - Go Daddy Registration Page

After you complete the registration process, go to http://x.co, login with your username and password, and go to Settings to get your API key. See figure 2.

Figure 2 - X.co API Key

Notice that this is a secret key and you should keep it away from intruder eyes. This key will be used in all of your work with X.co API.

WCF Services

WCF or Web services, not a big deal, let’s just call it WCF. Our service X.co provides you two WCF services that you can access:

The Squeeze service supports only one function that can be used to shorten (squeeze) long URLs. In fact, the Squeeze service provides other functions too, however, they are either deprecated or for the internal use of Go Daddy. The other service, the Reporting service, supports functions related to reports and analytics of short URLs (like clicks and referrer sites.)

Whatever service you like to use, you must reference it to your projects. To add a reference to a web service to your project, you can use one of two ways. The first and better way is to use Visual Studio. Right-click the Web References node under your project node in Solution Explorer and select Add Web Reference to launch the Add Web Reference dialog (see figure 3.)

Figure 3 - Solution Explorer - Add Web Reference

Figure 3 - Solution Explorer - Add Web Reference

The Add Web Reference dialog is now on the top of the IDE, the dialog might appear different in .NET 2.0 than higher versions (see figure 4 and figure 5.) Whatever, write the address of the service that you need to add, click Go so can Visual Studio read service description, write a good name in the Reference Name field that would be the namespace that groups service objects, and finally click Add Reference. Notice that we have used the name xcoapi for the Squeeze service, and xcoapirpt for the Reporting service.

Figure 4 - Add Web Reference Dialog in .NET 3.0+

Figure 4 - Add Web Reference Dialog in .NET 3.0+

Figure 5 - Add Web Reference Dialog in .NET 2.0

Figure 5 - Add Web Reference Dialog in .NET 2.0

Another approach to get the required source files for the service is to use the svcutil.exe tool that’s used internally by Visual Studio. This is a command tool that generates source files for web and WCF services. You can use this tool as follows:

svcutil.exe http://api.x.co/Squeeze.svc?wsdl /language=C#
svcutil.exe http://api.x.co/Squeeze.svc?wsdl /language=VB

Notice that we have included the address of the discovery (description) WSDL data of the services so that the tool can read it. Remember to select your language in the command.

Squeeze Service

The first function we have today and the only function of the Squeeze service (http://api.x.co/Squeeze.svc) is the Shorten() function that’s used to shorten long URL files. This function simply accepts 2 arguments:

  • url:
    The long URL to be shortened.
  • apiKey:
    The API key used to authenticate the call.

There’re other functions existing in the Squeeze service but they are either deprecated or reserved for internal use by Go Daddy.

After you ensure that a reference of the service is added to your project (check the previous section) you can start writing your code. The following function accepts the long URL and returned the shortened one that’s -at the time of this writing- is no more than 16 characters (e.g. http://x.co/8Gg8):

// C#
string Shorten(string url, string apiKey)
{
    using (xcoapi.Squeeze sq = new xcoapi.Squeeze())
    {
        return sq.Shorten(url, apiKey);
    }
}

Notice that web services consumes lots of system resources and you should release them as soon as you finish you work with them, that’s why we have used the C# using statement.

Reporting Service

The other service we have is the Reporting service (http://api.x.co/Reporting.svc) that offers you great deal of analytics and reporting functionalities that can be sorted in 3 areas:

  • Click count (the number of uses of the short URL)
  • Referrer sites (for the short URL)
  • Uses by locations (city, region, and country.)

This service supports 5 functions:

  • GetTotalMapClick():
    Returns total clicks (uses) of a short URLs.
  • GetMapClicksByDates():
    Returns clicks of a short URL made within a given time period grouped by days.
  • GetMapClicksByHour():
    Returns clicks of a short URL made today grouped by hours.
  • GetMapReferrersByDates():
    Returns referrer links made to the short URL within a given time period grouped by days.
  • GetMapLocationsByDates():
    Returns clicks of a short URL made within a given time period grouped by geographic location.

Those five functions are very similar in many ways. First, they all accept two required parameters:

In addition, the last four functions work the same way. They all return arrays of objects. GetMapClicksByHour() for instance returns the number of clicks made today grouped by hours each hour is represented by an object that contain the hour number besides the clicks made in that hour, and all objects are grouped inside one array.

The other functions GetMapClicksByDates(), GetMapReferrersByDates(), and GetMapLocationsByDates() work the same way and accept the same parameters except that they accept four additional parameters represent the begin and the end dates of the time period and whether the date parameters were set or leaved empty.

How can the four parameters help? You can define both and set the two flags to indicate that we need a specific time period. You can also set one of them and set its flag to indicate that you need to start from a specific day and get analytics till now. Notice that you can’t leave both empty.

The following code returns the total number of clicks for a specific short URL:

// C#
int GetTotalClicks(string shortCode, string apiKey)
{
    using (xcoapirpt.ReportingClient rpt = new xcoapirpt.ReportingClient())
    {
        return rep.GetTotalMapClick(apiKey, shortCode);
    }
}

And the following code is the same as the above except that it uses .NET 2.0:

// C#
int GetTotalClicks(string shortCode, string apiKey)
{
    using (xcoapirpt.Reporting rpt = new xcoapirpt.Reporting())
    {
        int totalClicks;
        bool succeeded;
        rep.GetTotalMapClick(apiKey, shortCode, out totalClicks, out succeeded);
        return succeeded ? totalClicks : -1;
    }
}

Notice the slight difference between the two calls (in .NET 2.0 and higher versions.) In .NET 2.0, the returned value is specified as an output parameter.

The following code is somewhat complex than the previous. The following code returns the refer links for our short URL:

// C#
xcoapirpt.ReferrerEventInfo[] GetReferrers
    (string shortUrl, string apiKey, out int totalClicks)
{
    using (xcoapirpt.Reporting rep = new xcoapirpt.Reporting())
    {
        xcoapirpt.ReferrerEventInfo[] results =
            rep.GetMapReferrersByDates(apiKey, shortUrl,
                DateTime.Now - new TimeSpan(7, 0, 0, 0, 0), true, DateTime.Now, true);
        totalClicks = 0;
        foreach (xcoapirpt.ReferrerEventInfo r in results)
            totalClicks += r.TotalSpecified ? r.Total : 0;
        return results;
    }
}

Notice how we specify the start and end date parameters and their flags to get only the last week analytics. Notice also the type of the array returned from the function and how we used it to get the required information.

RESTful Services

If you prefer not to use the WCF services, you can start with the REST interface provided to you by the kind-hearted WCF services. A RESTful service is simply a group of related web functions that has specific formats; some of return plaint text, some return XML data, and others return JSON.

Keep in mind that WCF services are supported natively by .NET framework and thus they are faster and easier to work with.

Squeeze Service

Not surprisingly, our RESTful Squeeze service is provided to us by the address http://api.x.co/Squeeze.svc. This service has two functions to shorten URLs, one is JSON, and the other is plain text.

The first function that returns plain text can be called using the following address:

http://api.x.co/Squeeze.svc/text/{apiKey}?url={url}

Now you have the address and ready with the input, the following function calls the previous function to shorten long URLs:

// C#
string Shorten(string url, string apiKey)
{
    WebRequest req = HttpWebRequest.Create(
        string.Format("http://api.x.co/Squeeze.svc/text/{0}?url={1}",
        apiKey, url));
    req.Timeout = 10000; // 10 seconds
    string shortUrl;
    System.IO.Stream stm;
    stm = req.GetResponse().GetResponseStream();
    using (System.IO.StreamReader rdr = new System.IO.StreamReader(stm))
    {
        return rdr.ReadToEnd();
    }
}

Reporting Service

Likewise, the Reporting service has the following address: http://api.x.co/Squeeze.svc. This service provides you with many functions like its WCF counterpart, however, all of them are JSON expect one is plain text. Because JSON is not natively supported by .NET Framework and thus requires the use of other 3rd party components (e.g. Json.NET) we won’t consider those endpoints. However, we have our total clicks function that returns plain text:

// C#
int GetTotalClicks(string shortCode, string apiKey)
{
    WebRequest req = HttpWebRequest.Create(
        string.Format("http://x.co/Reporting.svc/map/{0}/{1}/total",
        apiKey, shortCode));
    req.Timeout = 10000; // 10 seconds
    System.IO.Stream stm;
    stm = req.GetResponse().GetResponseStream();
    using (System.IO.StreamReader rdr = new System.IO.StreamReader(stm))
    {
        return int.Parse(rdr.ReadToEnd());
    }
}

Again, the short code is the only required piece of the short URL, you do not need to include the http://x.co/ (actually, you can’t!)

Source Code

Download the source code files from here.

What’s next

Consider reading more about URL shortening services here.

Similar Posts:


Random Posts:


Recent Posts:

  • UD

    Would it be possible to create a web-based version of this example?  If so, what would be needed to do this?  

    • http://JustLikeAMagic.com Mohammad Elsheimy

      It’s easy to do, just develop the interface and use the same functions!