Microsoft & .NET.NETTapping Into Microsoft Live Services with C#

Tapping Into Microsoft Live Services with C#

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Chances are that you have already used Microsoft Live services from a consumer standpoint. For instance, if you have used Microsoft Live Search instead of Google, or created a free e-mail account with Hotmail or Windows Live Mail, then you have used some of the services. These useful services are however only two examples of what is available.


In fact, there are about 15 more services in the Live offering. These services allow you to share your files, photos and contacts, synchronize them automatically between different devices, and more. Although many of these services are consumer-oriented, this doesn’t mean that they wouldn’t be useful in corporations and enterprises. Since the services are by definition open to everyone, the same solutions can be used by both consumers and businesses alike.


Developers on the other hand are interested in the programmable nature of these services. In addition to a regular, interactive web browser interface, most of the services can be accessed from application code. Microsoft supports using especially REST based endpoints to the Live services, but depending on the nature of the service, an XML web service interface (a SOAP interface) might also be supported.


In addition to supporting access from the code level, Microsoft has developed a set of installable tools and components that plug into the Visual Studio IDE. By installing the Live Tools for Visual Studio, you get a set of new components in the tool palette as shown in Figure 1. As an example, with these components, adding an interactive map to your ASP.NET web application is a breeze.


Figure 1. The Live Services tools installed in Visual Studio 2008.

The Live services that Microsoft offers can be divided roughly into five categories as shown in Figure 2. The identity service supports authentication, knowing who is who and which devices belong to whom. Directory service, then, maintains relationships between identities, for example to form a group of people to share information. Storage services allow people to save their data into the cloud (which can also be called a mesh). Communications and presence let people send messages to each other and know who is online or not. Finally, the search and location (or geospatial) services support finding information from the web and showing interactive maps inside your application.


Figure 2. The five Live Services groups.

Next, you are going to see three examples of different Live Services being used from C#.


Searching the Web


To get started with development using the Live services, you can start from the most commonly used offerings. You might have previously used the Live search engine (which, by the way, rumors indicate will be re-branded as Kumo) and the Virtual Earth interactive maps on the Live web site. Both these services apply to a broad range of users, but you can also benefit from these services in your own applications.


For instance, you might want to include the ability to search the web directly from your application, for instance to help in the research of a particular topic. With this in mind, I’ll show you how the Live Search can be used from your own applications. With a SOAP interface, it actually doesn’t matter whether your application is a GUI, web-based, console or a service application.


To get started using the Live Search from your code, you need to register as a developer and then get your personal (or corporate, as you prefer) application ID or AppID for short. This AppID string works as an identifier when you access the SOAP interface; no other authentication is needed. To register for the service, you would first need to go to the Live Search Developer Center (follow the link “Create an AppID”).


To access the SOAP interface, you need to add a service reference to your Visual Studio project. The correct address for the WSDL document is:


http://api.search.live.net/search.wsdl?AppID=NNN…


Here, you would need to replace NNN… with the AppID you created earlier. Once you have added the service reference to your project (it might be a good idea to rename it to something like “LiveSearchServiceReference” instead of just “Service1”), you can start accessing the interface. To do so, you need to prepare a request object of type SearchRequest and then launch the query. The Request object is defined as part of the SOAP interface. For instance, to search for a given string, you would use code similar to this:


const string AppId = “NNN…“;

LiveSearchPortTypeClient client =
new LiveSearchPortTypeClient();
LiveSearchServiceReference.SearchRequest request =
new SearchRequest();
request.AppId = AppId;
request.Query = “c# development developer.com”;
request.Sources = new SourceType[] { SourceType.Web };
request.Version = “2.0”;
request.Market = “en-us”;
request.Web = new WebRequest();
request.Web.Count = 5;
request.Web.CountSpecified = true;
request.Web.Offset = 0;
request.Web.OffsetSpecified = true;

SearchResponse response = client.Search(request);


Here, the SOAP client object is first constructed, after which the process is repeated for the SearchRequest object. To search for web content, you need to specify the AppId, your search keywords (the Query property) and select the correct SoruceType with the Sources property. Live Search supports different sources like the web, images, weather information, and even a spell checker (it works with single words only, though).


To execute the search request, you need to call the SOAP interface’s Search method. This returns a SearchResponse object which can be thought of as a collection to hits that the search returns. In the example code above, the Web.Count property is used to specify that the first five hits should be returned. The process the results, you could use code like this:

StringBuilder builder = new StringBuilder();
foreach (WebResult result in response.Web.Results)
{
builder.AppendLine(result.Title);
builder.AppendLine(result.Description);
builder.AppendLine(result.Url);
builder.Append(“Last crawled: “);
builder.AppendLine(result.DateTime);
builder.AppendLine();
}
MessageBox.Show(builder.ToString());

The Response object contains a collection property called Web.Results which is easy to enumerate through using a foreach construct. Here, the results are simply collected into a StringBuilder object line by line. Once completed, the results are shown in a message box as illustrated in Figure 3.



Figure 3. Results of a Live web search.

Adding a map


Having the ability to do web searches can be useful, but it is much more fun when you can add an interactive map into your application. By installing the Live Tools into Visual Studio, you will have the possibility to add a Virtual Earth map as a component to your ASP.NET web applications. The map is similar to the one available at Microsoft’s Live Search Maps site at maps.live.com. Virtual Earth on the other hand is the name of the service providing the maps and bird’s eye view of select locations.


Adding the map to your web application is as easy as adding a regular ASP.NET component: you simply drag and drop the Map component from the Visual Studio Toolbox onto your form (see Figure 4). If you now run the application, you can use your mouse to navigate the map, zoom in and out, and even switch to an aerial view. Very cool!

Of course, for such a map to be useful in your applications, you need to be able to control it programmatically. Luckily, this is easy with the Map control and its properties and events. For example, if you wanted to focus the map on the famous Yellowstone national park, you could set the latitude and longitude like this:

Map1.Center = new Microsoft.Live.ServerControls.VE.LatLong(
44.62, -110.49);

For Virtual Earth (VE), the namespace you will often need is called Microsoft.Live.ServerControls.VE, which in turn is, not surprisingly, implemented in the assembly Microsoft.Live.ServerControls.VE.dll. Showing locations on the map can have many uses. For instance, you could store customer locations in your database, and then use a map to visualize that location.


Or even better, you can add simple pushpin shapes into the map to signal important locations. This way, you could plot multiple locations on the map and even give each pushpin a title and a description. This is also very straightforward task to do in C#, given that you know the latitude and longitude already:

using Microsoft.Live.ServerControls.VE;

LatLongWithAltitude point = new LatLongWithAltitude(
latitude, longitude);
Shape shape = new Shape(ShapeType.Pushpin, point);
shape.Title = “Yellowstone NP”;
shape.Description = “Established in 1872, “+
“Yellowstone National Park is America’s “+
“first national park.”;
Map1.AddShape(shape);
Map1.ZoomLevel = 5;

The code first creates a point object that specifies the location of the pin, and an optional altitude (think mountains, for instance). The next step is to construct the share object and specify its location and type, the pushpin. Of course, the title and optional description can also be shown here. Finally, the map’s zoom level is set so that cities and states can easily be seen (Figure 4). A ZoomLevel of zero would mean no zoom at all— the whole planet would be visible.


Understanding the Presence Service


With real-time or near real-time communications, it is especially important to know whether your communication partner is available for a phone call, meeting or just a quick chat. The presence service allows your applications to gather this kind of information in connection with the Windows Live Messenger application (see Figure 5). The Windows Live Presence API allows you to send HTTP based queries that pass back and forth JSON (JavaScript Object Notation) formatted data.

This sharing can be allowed through the user’s properties, or you can provide a direct URL for the user which takes him/her to the correct location, and then returns back to your application. In this case, the URL is:

http://settings.messenger.live.com/applications/websignup.aspx?returnurl=URL&privacyurl=URL

On this page, the user must approve your application, after which they get a unique identifier which is needed by the API. This ID is also returned as a query parameter to your return URL. With the ID (such as “m94h27j358s9421v”), you can start programming. C# doesn’t yet have a ready-made library for JSON queries, but since the data passed between the systems is more or less plain text, it is rather straightforward to parse. Here is an example code snippet to query for the presence of a user, given that his or her ID is already known:

const string userID = “m94h27j358s9421v@apps.messenger.live.com”;
const string apiUri = “http://messenger.services.live.com/”+
“users/{0}/presence/”;
string presenceUri = string.Format(apiUri, userID);
WebRequest request = WebRequest.Create(presenceUri);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream,Encoding.UTF8);
string jsonResponse = reader.ReadToEnd();
reader.Close();
stream.Close();
response.Close();
MessageBox.Show(jsonResponse);

This code first constructs a special URL than can be used to determine the presence of a user. This URL has the following format:

http://messenger.services.live.com/users/{0}/presence/

At runtime, the placeholder {0} in the string gets replaces with the user’s unique identifier (the userID constant value in the code listing), which resembles an e-mail address. After a regular HTTP GET request has been sent to this address, the results is a JSON encoded text string, such as the following:

{    “icon”: {        “url”: “http://www.wlmessenger.net/static/img/
presence/Online.gif”, “height”: 16, “width”: 16
},
“statusText”: “Online”, “status”: “Online”, “displayName”: “”,
“id”: “m94h27j358s9421v@apps.messenger.live.com”,
“result”: { “code”: 200, “response”: “OK” }
}

The result contains the requested status information of the given user. Especially useful are the status and statusText properties. Above, their values are simply “Online” meaning that at the time the call was made, the user (contact) was online and available for instance for a chat. Your application is then free to do whatever it prefers with this information. For instance, you might want to display a certain icon next to the user’s name to show whether s/he is online or not. In case of an ASP.NET web application, it is easy to parse the icon property in the above result, and then use the GIF image pointed to by the “icon/URL” field in the response.


Conclusion


In this article, you have seen three different ways to access and utilize Microsoft’s Live Services. As you can guess with over a dozen of services, a single article like this cannot cover all of them in detail; however, the services selected for the previous demos give you a terrific overview of the ways that the other services can be accessed. That is, most services are available through a web interface, which is commonly SOAP based but could be plain HTTP interface as well.


By taking the Live Services into use, you can bring many typical Web-2.0-like social networking features into your own applications. Because of their open nature, these services are not limited to just the .NET development world, or C# programmers. However, these two environments provide a convenient combination with which accessing the services is easy and fast.


Furthermore, you can utilize the Live Services from regular WinForms desktop applications, graphical WPF applications or web applications. These web applications can in turn run in an Azure cloud, as RIA solutions using Silverlight, or as regular ASP.NET WebForms applications. Although each Live Service is different, it wouldn’t be a big surprise if later on they would combine into a single integrated solution.


That said, actually using the present Live Services is far from difficult. You just need to know they exist.


About the Author


Jani Järvinen is a software development trainer and consultant in Finland. He is a Microsoft C# MVP and a frequent author and has published three books about software development. He is the group leader of a Finnish software development expert group at ITpro.fi. His blog can be found at http://www.saunalahti.fi/janij/. You can send him mail by clicking on his name at the top of the article.


Links


Live Services Developer Center:
http://dev.live.com/


Live Search Developer Center:
http://search.live.com/developers


Windows Live Tools for Microsoft Visual Studio Download:
http://www.microsoft.com/downloads/details.aspx?FamilyID=f438b207-96af-497c-94db-152d48344af5&DisplayLang=en


Live Search SDK Download:
http://www.microsoft.com/downloads/details.aspx?FamilyId=0F513086-078B-47A8-A889-842DC93A69AB&displaylang=en

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories