Sunteți pe pagina 1din 84

LI

VE

TThe
h e LLeading
e a d i n g IIndependent
ndependent M
Magazine
a g a z i n e ffor
or M
Microsoft
icrosoft D
Developers
evelopers

Volume 5 / Issue 2

Live from the Web!


Bring Windows Live
Messenger to Your
Applications
Windows Live
Delegated APIs
Weaving the
Windows Live Services
into Your Web Sites
Getting Started with
the Windows Live Tools
www.code-magazine.com
US $ 5.95 Can $ 8.95

CoDe_FocusLive.indd 1

12.02.2008 23:48:25 Uhr

Are You Ready To Start?

CoDe_FocusLive.indd 2

12.02.2008 23:48:47 Uhr

EPS
Can Help!
EPS Software provides:

Application
Development

.NET 3.0 (WPF, WCF)


Windows & Smart Client
ASP.NET & AJAX Web
Tablet PC & Mobile PC
Windows Mobile

Prototyping Services
Situation Assessment
Project Management
Mentoring
Training

Contact us at:
info@eps-software.com
866-529-3682

www.eps-software.com

CoDe_FocusLive.indd 3

12.02.2008 23:48:52 Uhr

TABLE OF CONTENTS

Features
6 Welcome to the Windows Live Platform
CoDe Focus Magazine
Angus Logan

7 Introduction to Microsofts Windows Live


Platform
Dr. Neil examines some of the history behind the Windows
Live Platform and explores where it is heading now and
might be destined to go in the future.

Dr. Neil Roodyn

11 Live from the Web! Bring the Windows


Live Messenger Experience to Your Web
Applications

46 Windows Live Delegated APIs


Dr. Neil helps you understand how the Windows Live
delegated authentication system is used to access certain
Windows Live data stores and the technologies Microsoft is
building to make this work easier for you.

Dr. Neil Roodyn

52 Light Up the WebMicrosoft Silverlight


Streaming by Windows Live
Rob shows you how to get started with Silverlight and how
to upload your applications and rich media to the Silverlight Streaming Service.

Rob Blackwell

56 Developing Plugins for Windows Live Writer

You can now easily add IM capabilities to your Web site


either using the Windows Live Messenger library or the IM
Control. Michle and Paul show you how.

Sctt shows you how to start writing plugins for Windows


Live Writer, including how to get started, how to debug,
and how to package the final plugin.

Michle Leroux Bustamante and Paul Birkbeck

Sctt Lovegrove

24 Virtual EarthWhat's New in the Latest


Release?
John walks you through all the latest upgrades to the user
interface, compatibility, and functionality of Virtual Earth.

John OBrien

32 Weaving the Windows Live Services into


Your Web Site
Whether youre developing a business application, an
enthusiast site, or the next big social networking site,
Jason shows you how to use Windows Live Services and
Windows Live Quick Apps to make it quicker and easier to
create your site.

Jason Kelly

38 Building Personalized Applications on the


Windows Live ID Platform
Vaishali shows you how to use Windows Live ID to get
Live ID authentication in your Web or rich client applications, letting you reach millions of Live ID users, integrate
with Live Controls, and access Live services.

Vaishali De

67 Introduction to the Live Search API


Bronwen teaches you how to implement search capabilities
on your own Web site without having to implement the
logic and deal with issues such as storage and indexing.

Bronwen Zande

68 Getting Started with the Windows Live Tools


Vikas walks you through the various new tools and how
you can best use them.

Vikas Ahuja

76 Windows Live Admin Center


Jon introduces you to a new service from Microsoft that
helps you administer user accounts and customize services
around your Web site.

Jon Arking

Departments
5 CoDe Compilers
37 Advertisers Index

US subscriptions are US $29.99 for one year. Subscriptions outside the US pay US $44.99. Payments should be made in US dollars drawn on a US
bank. American Express, MasterCard, Visa, and Discover credit cards are accepted. Bill me option is available only for US subscriptions. Back issues
are available. For subscription information, email subscriptions@code-magazine.com or contact customer service at 832-717-4445 ext 10.
Subscribe online at www.code-magazine.com
CoDe Component Developer Magazine (ISSN # 1547-5166) is published bimonthly by EPS Software Corporation, 6605 Cypresswood Drive., Suite
300, Spring, TX 77379. POSTMASTER: Send address changes to CoDe Component Developer Magazine, 6605 Cypresswood Drive., Suite 300,
Spring, TX 77379.

Table of Contents

CoDe_FocusLive.indd 4

www.code-magazine.com

12.02.2008 23:48:55 Uhr

developer

CODE COMPILERS

component

March 2008

magazine

Volume 5 Issue 2

Group Publisher
Markus Egger
Associate Publisher
Rick Strahl
Managing Editor
Ellen Whitney
Content Editor
H. Kevin Fansler
Writers In This Issue
Vikas Ahuja
Jon Arking
Paul Birkbeck
Rob Blackwell
Vaishali De
Jason Kelly
Angus Logan
Michle Leroux Bustamante
Sctt Lovegrove John OBrien
Dr. Neil Roodyn Bronwen Zande
Technical Reviewers
H. Kevin Fansler
Angus Logan
Ellen Whitney
Art & Layout
King Laurin GmbH

info@raffeiner.bz.it
Production
Franz Wimmer
King Laurin GmbH
39057 St. Michael/ Eppan, Italy
Printing
Fry Communications, Inc.
800 West Church Rd.
Mechanicsburg, PA 17055
Advertising Sales
Vice President, Sales and Marketing
Tom Buckley
832-717-4445 ext 34
tbuckley@code-magazine.com
Sales Managers
Erna Egger
+43 (664) 151 0861

erna@code-magazine.com
Tammy Ferguson
832-717-4445 ext 26

tammy@code-magazine.com
Circulation & Distribution
General Circulation: EPS Software Corp.
Newsstand: Ingram Periodicals, Inc.
Media Solutions
Worldwide Media
Subscriptions
Subscriptions Manager
Cleo Gaither
832-717-4445 ext 10

subscriptions@code-magazine.com
US subscriptions are US $29.99 for one year.
Subscriptions outside the US are US $44.99.
Payments should be made in US dollars drawn
on a US bank. American Express, MasterCard,
Visa, and Discover credit cards accepted. Bill
me option is available only for US subscriptions.
Back issues are available. For subscription
information, email subscriptions@code-maga-

zine.com
or contact customer service at 832-717-4445 ext 10.
Subscribe online at

www.code-magazine.com
CoDe Component Developer Magazine
EPS Software Corporation / Publishing Division
6605 Cypresswood Drive, Ste 300,
Spring, Texas 77379
Phone: 832-717-4445
Fax:
832-717-4460

CoDe_FocusLive.indd 5

12.02.2008 23:48:57 Uhr

ONLINE QUICK ID 0804012

Welcome to the
Windows Live Platform
CoDe Focus Magazine
Angus Logan
Senior Technical Product
Manager
alogan@microsoft.com
Angus Logan is a Senior
Technical Product Manager
in the Windows Live Platform
team in Redmond.
Anguss team is responsible for
all technical marketing content
ranging from conference
presentations (MIX, TechEd)
to online samples (Windows
Live Quick Apps).
Prior to being on the Windows
Live Platform team, Angus was
a Portals Technology Specialist
with Microsoft Australia.
Prior to that, Angus worked
for several Microsoft partners,
was an MVP, and co-authored
a book on Microsoft Content
Management Server.
You can read Anguss blog
at http://blogs.msdn.com/
angus_logan/

Building compelling applications and Web sites just got easier.


Microsoft is opening up Windows Live Services to developers everywhere. This
edition of CoDe Focus shows you how to use Windows Live Services to draw
users to your Web site, get them hooked, and keep them engaged.
Windows Live uses a broad range of services to
provide rich Web applications. Now, these services
are available to any developer to build into their
application. From small blogs and Web sites to the
largest enterprise Web application, Windows Live
Services make it quicker and easier to build worldclass Internet scenarios.
Windows Live Services help
you build engaging Web experiences by providing state-of-theart services in these areas:
Infrastructure such as
Silverlight Streaming by
Windows Live and Admin
Center.
Personal Data stored on
a per user basis such as
Live Contacts and Spaces
Photos.
Notifications and Messaging leveraging the vast
Windows Live Messenger
network.

Find and Locate for accessing the Live Search


index and mapping information from Virtual
Earth.
Identity using Windows Live ID APIs to provide a secure experience for users.

Fast Facts
The Windows Live Platform
Quick Applications are
segment-focused, open
source demos.
They range from
Tafiti Search Visualization
(Silverlight front end over
Live Search API) to Adventure
Works Resorts
(a fictitious social network).
For more information see
http://dev.live.com/quickapps

This edition of CoDe Focus


shows you how to use Windows
Live Services to build these scenarios into your Web site. Read
on for the business value, stepby-step development instructions, and free source code to
get you started.
Windows Live adds new applications and services all the
time. To keep up on the latest
news about Windows Live Services, go to http://dev.live.com.
Angus Logan

More Resources
This issue of CoDe Focus
is a great place to start,
but here are some other
Web sites you might want
to check out:
www.ViaWindowsLive.com

has a great gallery of


Windows Live mashups.
www.ProgrammableWeb.com

has a gallery of Windows Live


and non-Windows Live mashups.
http://dev.live.com has a section
on what people are building.
There are also some good blogs
you can read:
http://blogs.msdn.com/angus_logan/
http://dev.live.com/blogs/sls/

The best place for more


information is http://dev.live.com

Welcome to the Windows Live Platform CoDe Focus Magazine

CoDe_FocusLive.indd 6

www.code-magazine.com

12.02.2008 23:48:58 Uhr

ONLINE QUICK ID 0804022

Introduction to Microsofts
Windows Live Platform
From the consumer products associated with the MSN Butterfly,
the Windows Live Platform has steadily grown and evolved.
In this article you will discover some of the history behind the Windows Live
Platform and explore where it is heading now and might be destined to go in the
future. This article will explore the opportunities for you as a developer in this
brave (nearly) new world.

Dr. Neil
Neil@Roodyn.com

n the mid 1990s, Microsoft began to address the


In recent years this form of stickiness has become
World Wide Web and the boom that was about to
commonly known as a social networking applicahappen. To be fair, for any company that thinks
tion. Once a user has committed energy into a platas big as Microsoft does, the Internet and Web was
form they are likely to stick around, unless they find
probably not worth considering much before this
something far superior or their current investment
time anyway. It wasnt until the mid to late 1990s
starts to cost too much. This can happen if the prothat the Internet really proved its commercial valvider creates a pain (real or hyped) for the user. An
ue to be worth more than a few million dollars. In
example might be charging the user for the service
many ways the Internet boom
that was previously free or sellof the late 1990s would never
ing the users personal details to
Fast Facts
have been possible if Microsofts
other companies.
The Windows Live platform
mission statement (a computer
enables developers to
A few years back, Microsoft
on every desktop) had not been
decided to rebrand some of
nearly achieved.
leverage Microsofts online
the MSN services to Windows
consumer offerings into their
Live. Microsofts success in the
Microsoft made some bold
own online applications.
operating system world with
moves to ensure they had a
Microsofts infrastructure
the Windows products has led
position within the new online
handles billions of
to Microsoft Windows as a
world. Through both acquisitransactions daily;
brand having enormous value.
tion and invention, Microsoft
You can probably imagine the
has over the last 10 years posiyour applications can plug
thought process behind trytioned themselves as one of the
into this infrastructure
ing to leverage this high value
most popular online consumer
enabling you to focus on the
brand into the online world.
platforms. Offerings such as
functionality that makes your
For consumers this meant
Windows Live Messenger, Winapplication special.
MSN Messenger became Windows Live Hotmail, Windows
Live Search, and Windows
dows Live Messenger and
MSN Spaces became Windows Live Spaces, and
Live Spaces have become the flagship products
with hundreds of millions of users. Other products
so on. Something else was also stirring underneath
have more niche or slowly growing markets: Virtual
the exterior consumer products. Developers were
getting more than curious about how to plug into
Earth, Expo, QnA, and Events to name a few.
the value being provided to the users through the
If youve been paying attention, youll have noticed
products. Hacks for Messenger and Spaces were
that the flagship big ticket products have somealready emerging on blogs and forums and the
thing in common. They have a well defined revenue
APIs involved in creating these were about to be
stream and they have stickiness to them. The stickiexposed.
ness comes from the connections that you make using the products:

Hotmail provides your e-mail address, once


you have handed that e-mail address to enough
people you are going to keep using Hotmail.
Messenger encapsulates your buddy list, once
you have more than a couple of buddies on
Messenger you are going to want to stay there.
Spaces provides a store for you to share your
pictures, thoughts (blog posts), and other interests (e.g., Xbox Live gadgets).

www.code-magazine.com

CoDe_FocusLive.indd 7

Dr. Neil is an independent


itinerant consultant, trainer,
and author. He travels the
world working with software
companies. Dr. Neil loves
Australia, where he spends the
summer enjoying the Sydney
lifestyle and helping software
development teams get more
productive. Dr. Neil spends his
other summer each year flying
between northern Europe and
the USA working with software
teams and writing about his
experiences. Neil brings his
business and technical skills to
the companies he works with
to ensure that he has happy
customers. His latest book
eXtreme .NET (Addison Wesley,
2005) introduces eXtreme
Programming Techniques to
.NET developers. Dr. Neil is a
Microsoft Regional Director
and a Windows Live Developer
MVP.

Dr. Neil founded

http://ViaWindowsLive.com,
a Web site to help developers
build on Windows Live
services.

You can find out more about


Neil from
http://www.Roodyn.com.

With the brand shift


to Windows Live came an
attitude shift to developers on
the newly branded
Windows Live products.

Introduction to Microsofts Windows Live Platform

12.02.2008 23:48:59 Uhr

With the brand shift to Windows Live came an


attitude shift to developers on the newly branded
Windows Live products. While developers were
not entirely embraced, they were starting to be supported in some form. Microsoft was releasing APIs
that would allow you plug into the Windows Live
products. This was certainly not something that
happened overnight, there are still APIs that are
wished for but not available, but the surface area
that you can program against has been increasing
steadily over the last few years.

The new
cloud services are changing the
way that developers
can write code online.
The Sunshine Through the Clouds
You are probably wondering what impact this has on
you as a developer. You might be questioning the value of accessing these in the cloud services. In many
ways this is a similar situation to when Windows
(and OS2) started shipping on PCs. Many developers
didnt really see the point in getting involved in all that
messy point-and-click mouse movement; it turned out
to be the way that every PC developer would end up
working. In the same way that Windows changed
the way developers wrote software for PCs, the new
cloud services are changing the way that developers
can write code for their online applications.
The opportunities to place your application in the
hands of the millions of users that already have a
commitment to the Windows Live products are numerous and potentially very rewarding. To make
your life more interesting, the world of online users
that utilize the Windows Live products is incredibly
diverse and segmented. If you want to create a Web
site for rock climbers that live in Manhattan you
can be fairly certain that a large percentage of them
will have a Live ID (the standard Windows Live
authentication) to log in to a Hotmail, Messenger,
or Spaces account. Letting a user log in to your site
with their existing credentials does several things:
The user doesnt have to remember another
user name and password for your site, they use
something they are already familiar with.
Your site can potentially get access to the users
Windows Live connections, often that means
their social network, but it could be as simple
as providing them a gadget for their Windows
Live Spaces account.
Your new Web site aligns itself with the powerful Microsoft Windows Live brand by leveraging their services.
Your site can utilize Microsofts online infrastructure to host content, manage domains,
stream media, and maintain relationships between users.

Introduction to Microsofts Windows Live Platform

CoDe_FocusLive.indd 8

Rich Internet Applications


Alongside the exposure of the new APIs for the online products has been a movement towards richer online experiences, often called Rich Internet
Applications or RIAs. Several technologies have
emerged to enhance the users experience when
working in a browser: smarter use of JavaScript in
manipulating components of a Web page, which
has been brought about by a wide adoption of
standards across the browsers, AJAX (Asynchronous JavaScript and XML) enables parts of a Web
page to refresh without the whole page refreshing,
and browser plugins such as Flash and now Silverlight.

The Buzz and the Fuzz


Building an RIA is not as simple as it may appear.
Web sites are no longer online brochures with
text and pretty pictures formatted and laid out in
a way that pleases the eye. This new RIA Web
site has all the same issues that desktop software
needs to address: user interaction models, feature
discoverability, application state, security models,
and so on. These new RIAs need to achieve all
this while still being constrained to running in a
Web browser. Building these online applications
is not a trivial matter and, for this reason, RIAs
are currently far more buzz than reality.
In reality the Web sites are becoming a fuzzy mix
of old style HTML brochures and rich components containing media or functionality such as
mapping or an instant messenger chat window.
There can be little doubt that the trend is driving
more Web sites to provide richer experiences and,
over the next few years, the user expectation will
shift towards more advanced and fulfilling interaction.

Online Applications
Before you start thinking about how to build these
new Internet applications, it is worth taking a step
back and thinking of some of the concepts behind
an online application. If your application is no longer simply serving markup files to be rendered in a
browser, there are some considerations to be taken
on the architecture of your product.

In reality the
Web sites are becoming
a fuzzy mix of old style
HTML brochures
and rich components.

www.code-magazine.com

12.02.2008 23:48:59 Uhr

Massively Scaled Client/Server


The model of central server and multiple terminals
is hardly new; this is exactly how computers have
evolved. Initially a single mainframe computer
would be shared between users at multiple terminals. As this model grew, the mainframe servers
changed from single servers to multiple servers,
mostly indistinguishable from each other for the
end user on a terminal. The model evolved over
the years, firstly to smaller mini computers, still being addressed by terminals, moving through to the
world in which we now live, where most terminals
are themselves as powerful as the mainframe servers were 40 years ago.
The Internet and the world of online applications
hasnt changed that much. The application architecture is still mostly client/server architecture-the servers being Web servers and the clients being Web browsers. One of the major challenges of
these new client/server applications is the issue of
scale. With more and more nodes connecting to
the Internet every day, the potential number of client transactions your application will have to service is huge, in the millions, and if you hit it really
big it could be in the billions.
Building an application to service millions (or billions) of transactions a day seems like a daunting
task, but the architecture is well defined and the
client/server model has stood up well to the test
of time.
Microsoft has been addressing these scaling issues
for many years now with billions of transactions
going through their services every day, such as
Hotmail and Messenger. Being able to work alongside these services and leverage this infrastructure
can only be good for your online application.

Massively Hyped Mashups


The Internet is a rich source of data and services.
If you want to discover something, the chances of
finding the answers somewhere online are incredibly high. Often the answers may lie in places that
are disconnected from your initial interest. For example, if you are interested in the weather off shore
for a sailing trip but also mapping your sailing trip,
finding ports to moor your boat, and seeing the currents at sea, you may have visit multiple online sites.
Some Web developers have seen this rich source of
disconnected information as an opportunity to create Web sites that combine the data from multiple
sources into one location. Often (as suggested) this
might be for niche interests. The concept of combining multiple online data sources into one application has led to the term mashup. These new sites
mash up the data from the servers to create a new
online application. Microsofts Popfly addresses this
opportunity for the enthusiast market.
There has been a large amount of press and media
interest in mashups, but so far it seems to be an av-

www.code-magazine.com

CoDe_FocusLive.indd 9

enue of smaller financial returns. The big money is


still in the client/server model where you own (or
at least license) the data the clients are viewing.

Where to Get Started


This special issue of CoDe Focus Magazine has an
abundance of information to help you get going
with using the Windows Live Platform services.
Looking through the author list felt like looking at
my friends list in Windows Live Messenger; I have
worked with many of these authors over the last
couple of years, helping to explain the intricacies
of the Windows Live platform as it evolved from
the early concepts to what you see today.

Building an application
to service millions (or billions)
of transactions a day seems like a
daunting task but the
architecture is well defined.

As you read through the articles you will learn a


wealth of information on how to use many of the
Windows Live services in your applications. You
will learn about the JavaScript library of Windows
Live Messenger and how to embed Instant Messenger capabilities into your application. You will
discover the new APIs in Virtual Earth version 6.
You will understand how to use Windows Live
ID, the authentication technology provided by the
Windows Live platform. There is a full explanation of Silverlight Streaming and how you can
programmatically work with this Windows Live
service to manage your Silverlight applications
using Microsoft infrastructure. The technology
for enhancing Windows Live Writer with plugins
will be demystified. Windows Live Admin Center
is fully described, the centralized place for you to
manage your Live Domains and application IDs.
The Windows Live Search API is explained; you
will discover how to add search to your application and manipulate the search results. You will
explore how you can access Windows Live Data
and what you will be able to achieve with the new
Windows Live Data technologies. You will learn
how you can work with Windows Live services
without leaving the comfort of ASP.NET using the
new Windows Live Tools for Visual Studio. Finally, you will be guided on how to glue the services
together into your own mashups and explore the
sample applications provided by Microsoft.
Once you have absorbed all the goodness from the
articles, you should head to Microsofts official developer center for Windows Live at http://dev.live.com.
The community portal run and maintained by several of the authors of articles in this magazine will

Introduction to Microsofts Windows Live Platform

12.02.2008 23:48:59 Uhr

also provide more articles to help you get started


and solve issues, http://ViaWindowsLive.com.

The Browser Is Now


All of the Windows Live services (barring Live
Writer, which isnt really a service anyway) discussed in this magazine have terms of usage-guidance from Microsoft as to how you can use
the services. At the time of writing these terms
stipulate that the Windows Live services can only
be accessed through an application running in a
browser.

one of these applications today. RSS Readers, email Clients, iTunes, and Live Writer are all great
examples of smart client applications that provide
richer experiences for users than their browserbased counterparts.
Consider this as you start building your applications to take advantage of Windows Live services.
Right now you might be constrained to the browser, but the future of online services will be defined
by applications that disregard the browser and
build on the power of the computer.
Neil Roodyn

The future of online services will


be defined by applications that
disregard the browser and build on
the power of the computer.

The Web browser is the terminal through which


you access most of the Internet. You access all the
buzz and hype around Web 2.0 and the new wave
of online social networks through browsers. The
browser is the green-screen terminal of the 2000s.
Browsers are getting smarter and more capable
and Web developers are getting more skilled at
building rich experiences, but to create the really
rich experiences the browser is used to host plugins such as Flash and Silverlight.
While it may seem that in order to raise funding
a software company must have a Web application, it is clear that the constraints of the browser
may never be solved. Applications that run in a
browser are considered to be sandboxed--in that
they should not be able to access the resources of
the computer upon which they run. Users can only
access browser-based Web applications when they
are online and, even though there is a massive increase of online availability, it is still not a 100%
online world. When you travel, this becomes even
more apparent and many businesses have mobile
resources that are not always online.

Back to the Future


Running an application locally on your own server has many advantages, such as performance, offline availability, direct access to peripherals, and
security.
The way to provide really extraordinary and rich
experiences for the user is by building software
that runs on the computer, often called rich client
or smart client software. There are many examples
of utilizing services from the Internet within client
applications, in fact it is quite likely you will use

10

Introduction to Microsofts Windows Live Platform

CoDe_FocusLive.indd 10

www.code-magazine.com

12.02.2008 23:48:59 Uhr

ONLINE QUICK ID 0804032

Live from the Web!


Bring the Windows
Live Messenger Experience
to Your Web Applications
Windows Live Messenger is one of the central offerings nestled
among a suite of products and services under Microsofts
Windows Live brand.
For years online chat has been progressively and swiftly revolutionizing how
you communicate with your friends, family, coworkers, and businesses you deal
with. It is the foundation of the original chat room concept and the heart of
instant messaging applications. Online chatalso called instant messaging or
just IMconnects people for one-to-one or group chat, for social networking
purposes, or for business directives, such as enabling access to technical support,
customer services, or sales. Now, Windows Live Messenger supports a rich set of
features for Web applications through the Windows Live Messenger IM Control,
the Windows Live Messenger Presence API, and the Windows Live Messenger
Library. The collective features of these products go beyond the simplicity of a
chat application, making it possible to embrace this new era of social networking
by leveraging your built-in Windows Live network within any Web application.
xtending Windows Live Messenger features
The new suite of offerings within the Windows Live
to the Web makes it possible for personal
Messenger family support these Web-enabled scesites, community sites, and business applinarios as follows:
cations to increase their reach
Windows
Live
Messenand interactivity with visitors.
Fast Facts
ger IM Control: Enables
For community sites such as
The collective features
Web applications to show the
your blog or other social netof the Windows Live
online presence of a Windows
working sites, this could mean
Messenger IM Control,
Live ID account to visitors and
sharing your online messenger
the Windows Live
allows those visitors to interpresence so that visitors can
act with the account through a
easily contact you. You can
Messenger Presence API,
Web-based instant messaging
also supply fully functional or
and the Windows Live
control. This interaction can be
completely customized WebMessenger Library go
anonymous or the visitor can
driven instant messaging feabeyond the simplicity of a
identify themselves by name or
tures from your site or Web
chat application, making it
by their Windows Live account.
applications to enhance this
possible to embrace this
interactive experience. You
new era of social networking Windows Live Messenger Presence API: Enables site visitors
can apply the same ideas to
by leveraging your built-in
to log in to their Windows Live
business applications in the
Windows Live
ID account and enable Web apform of supplying technical
network within any Web
plications to access their online
support directly from the corapplication.
presence. This facilitates nonporate site or interacting with
anonymous interactions with
other departments or personthe IM Control.
nel. In either case, an important benefit of Web Windows Live Messenger Library: Makes it
enabled Windows Live Messenger is that it allows
possible to build Web applications that intevisitors that dont use Windows Live Messenger
grate with Windows Live Messenger with more
to interact with other Windows Live Messenger
granular control over the UI and underlying
users, without installing the Windows Live Mesinstant messaging features exposed to visitors.
senger Client.

www.code-magazine.com

CoDe_FocusLive.indd 11

Michle Leroux
Bustamante
mlb@idesign.net
Michle Leroux Bustamante is
Chief Architect of IDesign Inc.,
Microsoft Regional Director
for San Diego, and a Microsoft
MVP for Connected Systems.
At IDesign Michle provides
training, mentoring and highend architecture consulting
services focusing on scalable
and secure architecture
design for .NET, Web services,
interoperability, federated
security scenarios, CardSpace,
and globalization architecture.
Michle participates in
Software Design Reviews
for products in the Microsoft
roadmap, including WCF,
CardSpace, and other securityfocused products. During
the Beta 1 phase Michle
participated in prototyping
elements of the CardSpace
technology for the product
team. She is a member of the
International .NET Speakers
Association (INETA), a
frequent conference presenter,
conference chair for SD West,
and is frequently published
in several major technology
journals. Michle is also on
the board of directors for IASA
(International Association of
Software Architects) and a
Program Advisor to UCSD
Extension. Her latest book
is Learning WCF, OReilly
2007see her book blog here:
www.thatindigogirl.com. Reach
her at mlb@idesign.net or visit
www.idesign.net and her main
blog at www.dasblonde.net.

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

11

12.02.2008 23:48:59 Uhr

While the IM control and presence API are the easiest to implement and do not require development
experience, the Messenger Library provides a rich
set of features that require developers to provide the
UI and programmatically control all interactions
with Windows Live Messenger. Each has their place
in the community depending on the goals of your
Web application. This article will explain when and
how to incorporate the IM control, presence API,
and Messenger Library in your Web applications
while discussing common scenarios where each are
distinctly useful.

Paul Birkbeck
paul.birkbeck@multiplied.com
Paul Birkbeck is Director of
Software Development and
Lead Architect at Multiplied
Media Corporation
(www.multiplied.com).
At Multiplied Media,
Paul leads the development
effort for their flagship product,
Poynt
(www.mypoynt.com)a
multimedia local search service
that leverages Windows Live
Messenger as its primary
delivery channel. Pauls
technology expertise lies
in building large enterprise
systems for the past 15 years,
focusing primarily on Microsoft
technologies. His current focus
is in the Windows Live product
suite including Messenger,
Virtual Earth, and Search. Paul
has his MCSD.NET and he
recently started a new .NET
User Group in Barrie, Ontario,
Canada. Reach him at

Its All About Online Presence!


Introducing the Windows Live
Messenger IM Control and Presence API
The Windows Live Messenger IM Control was released in November 2007. This control is a fantastic
addition to a blog, a Web site, or any other space on
the Web where you want to communicate your online presence or allow visitors to communicate with
you when you are signed-in to a Windows Live Messenger client. Visitors can communicate with you
anonymously, by a specified name, or by first logging
in to their Windows Live account and thus making it possible for you to add them to your contact
list for future communications. The Windows Live
Messenger Presence API compliments the IM control, released in December 2007. It lets you explicitly
invite visitors to log in to their account and share
their online presence so that your Web application
can identify them. Both of these products are very
easy for the non-developer to include on a Web page.

The coming sections will explain how to work with


the IM control, and then show you how to add value
with the presence API.

Features of the IM Control


You can host the Windows Live Messenger IM Control on any Web page. This allows visitors to reach
you when you are logged in to the Windows Live
Messenger client application. Visitors can see your
online presence and, when you are online, they can
send messages through the IM control while you receive them at your messenger client. Whats particularly compelling about the IM control is that you can
let anonymous visitors communicate with youthey
dont have to log in and they dont have to have a
Windows Live ID account. This is unlike the user
experience with the messenger client, which requires
all users to log in before they can send messages to
one another. The IM control is perfect for enabling
chat with visitors of your Web application to answer
questions or discuss topics, without adding to your
contact list. Since the IM control is Web-based, even
non-messenger users can interact with you without
installing the messenger client application to their
machines.
You can share your online presence with the IM control in three different ways: a status icon, a button, or
an IM window (see Figure 1). The status icon and
button give you the freedom to preserve real estate
on your Web page and still supply a way for visitors
to chat with you. Visitors are presented with a new
browser window when they click the status icon. The
new window shows the full IM window ready to be-

paul.birkbeck@multiplied.com

Figure 1:
From the Create
HTML page in
Web Settings you
can configure
the IM controls
appearance
and copy the
resulting HTML
to any Web page.
The Windows
Live Messenger
IM Control lets
you share your
presence as a
status icon, a
button, or by
presenting an IM
window.

12

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

CoDe_FocusLive.indd 12

www.code-magazine.com

12.02.2008 23:49:00 Uhr

Live Team

Figure 2: On the Home page in Web Settings you must first allow Web sites access to your messenger presence before the
IM control can be useful.
gin a chat session. If you are online, the IM window
is enabled so that visitors can send messages, otherwise it is disabled. To set up, you will generate the appropriate HTML for the IM control according to the
choice of online presence you prefer to share within
your Web application.
The IM control is supported by IE 6, IE 7, and Firefox 2.0 on Windows or Mac OS. Aside from deciding
how you would like to share your online presence
with visitors, you can also personalize the controls
appearance and culture settings. When you generate
the HTML for the control, you can choose a template to initialize font and color properties to match
your Web applications appearance. The control is
also localized to 32 languages, so by simply setting
a property you can adjust the language presented to
your visitors. This article will talk about the control
HTML and related properties next.

Generating HTML to Share


Online Presence
It takes just a few minutes to get a Web page up and
running with the IM control. The first step is to enable your online presence and generate the HTML
according to the type of online presence you want
to show. The next step is to copy that HTML to
any Web pages where you want to host the control.
Then, let the chatting begin!

Start by browsing to this URL: http://settings.messenger.live.com/applications/WebSettings.aspx. You will be


prompted to sign in to your Windows Live ID account (if you arent already signed-in) and presented
with the Web Settings page where you can enable
others to see your online presence on the Web.
Figure 2 illustrates how to enable this. Once enabled,
Web applications will be able to host HTML that allows visitors to send you messages.
On the same Web Settings page there is an option
to create the HTML that would host the IM control
(see Figure 1). This is where you decide which type
of online presence you want to sharein the form
of status icon, button, or IM window. As you select
each option, the page shows the appropriate HTML
for the selection so you can review its appearance.
Listing 1 illustrates the HTML generated for each
form of online presence, without any themes applied.
All three pass parameters to the IMMe.aspx page,
including a required invitee parameter which holds
your messenger ID in the form:
[unique id]@apps.messenger.live.com

The unique ID is a hash that uniquely identifies your


messenger account. When visitors initiate a conversation using the IM control, this identity is used to direct messages to your IM account, which you receive
in the messenger client application if you are online.

Steve Gordon
Lead Software Design
Engineer
Steve's team is on point to
expose the rich capabilities
of Windows Live Messenger
and Contacts to the full range
of Web developers. Using
controls that can be quickly
embedded into existing Web
sites or APIs that facilitate rich
IM and presence-enabled Web
applications, developers can
build powerful and compelling
experiences for their users with
minimal effort.
Steve has been a member
of the Messenger team for
three years. During his tenure,
he has had the opportunity
to implement a range of
functionality within the service;
however, he is most excited
about enabling developers to
leverage the platform to create
applications that delight users.

Listing 1: The resulting HTML generated for the status icon, button, and IM window, with no themes applied.
<!-- HTML for status icon -->

msgr:altBackColor="#FFFFFF"
msgr:foreColor="#424542"
msgr:conversationUrl="http://settings.messenger.live.com/
Conversation/IMMe.aspx?invitee=[unique id]@apps.messenger.live.
com&mkt=en-US"></div>
<script type="text/javascript"
src="http://messenger.services.live.com/users/
[unique id]@apps.messenger.live.com/presence?mkt=enUS&cb=Microsoft_Live_Messenger_PresenceButton_onPresence"></
script>

<a target="_blank" href="http://settings.messenger.live.com/


Conversation/IMMe.aspx?
invitee=[unique id]@apps.messenger.live.com&mkt=en-US">
<img style="border-style: none;"
src="http://messenger.services.live.com/users/
[unique id]@apps.messenger.live.com/presenceimage?
mkt=en-US" width="16" height="16" /></a>
<!-- HTML for button -->

<!-- HTML for IM window -->


<script type="text/javascript" src="http://settings.messenger.live.
com/controls/1.0/
PresenceButton.js"></script>
<div
id="Microsoft_Live_Messenger_PresenceButton_[unique id]"
msgr:width="100"
msgr:backColor="#D7E8EC"

www.code-magazine.com

CoDe_FocusLive.indd 13

<iframe
src="http://settings.messenger.live.com/Conversation/IMMe.aspx?
invitee=[unique id]@apps.messenger.live.com&mkt=en-US"
width="300" height="300" style="border: solid 1px black; width:
300px; height: 300px;" frameborder="0"></iframe>

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

13

12.02.2008 23:49:03 Uhr

Figure 3: To start a new conversation via the IM windowidentify yourself, retype the CAPTCHA text, and send your message.

The status icon, button, and IM window all show


your messenger status using the presence API, which
will be discussed shortly. All three also support the
mkt property, which defaults to en-US but you
can set it to any of 32 culture codes specified here:
http://msdn2.microsoft.com/en-us/library/bb936685.aspx.
When you select an alternate culture code, IM controls show text in the requested language, which is
important if you are using the IM control on a localized Web application.
You can also customize the visual appearance of the
IM control. Of course the status icon does not support customization since it merely displays your online status icon, but you can select a theme for the
button and IM window to fit with your Web page
color scheme. By default, the button supports a few
properties that control the buttons appearance and
supply invitee details to the button script imported
by PresenceButton.js in the first <script> statement:
msgr:width="100"
msgr:backColor="#D7E8EC"
msgr:altBackColor="#FFFFFF"
msgr:foreColor="#424542"
msgr:conversationUrl=
http://settings.messenger.live.com/Conversation/
IMMe.aspx?invitee=[unique id]@
apps.messenger.live.com&mkt=en-US

If you select a theme for the IM control, all forms of


online presence will include additional properties to
control the color scheme of the IM window when
presented. These properties are included in the invitee property setting as shown highlighted here for the
IM window <iframe> settings:
<iframe src="http://settings.messenger.live.com/
Conversation/IMMe.aspx?invitee=
[your invitee ID here]@
apps.messenger.live.com&mkt=en-US&
useTheme=true&
foreColor=333333&backColor=E8F1F8&
linkColor=333333&borderColor=AFD3EB&
buttonForeColor=333333&buttonBackColor=EEF7FE&
buttonBorderColor=AFD3EB&
buttonDisabledColor=EEF7FE&

14

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

CoDe_FocusLive.indd 14

headerForeColor=0066A7&headerBackColor=8EBBD8&
menuForeColor=333333&menuBackColor=FFFFFF&
chatForeColor=333333&chatBackColor=FFFFFF&
chatDisabledColor=F6F6F6&chatErrorColor=760502&
chatLabelColor=6E6C6C"
width="300" height="300" style="border: solid 1px
black; width:300px; height:300px;"
frameborder="0"></iframe>

Of course you can customize these values if the


canned themes dont meet your needs. At least the
HTML gives you a head start. The point is that with
just a few clicks on the Web Settings page you can
create working HTML that you can copy and paste
to any Web page. Although the examples in this article will be ASP.NET (.aspx pages), the resulting
HTML is interoperablefor example it works on
plain HTML pages (.htm and .html) or PHP (.php)
to name a few alternatives.

Putting the IM Control to Work


After pasting the generated HTML for the status icon,
button, or IM window to your Web application, visitors will be able to chat with you when you are online.
As mentioned earlier, when visitors click the status
icon or button, the control launches a new browser
window with the IM window shown in Figure 1 inside. Visitors can click the icon or button even if you
are offline, but the IM window is disabled until you
are online. Your online status will not update in the
icon or button until the visitor refreshes the page.
When you log into your Windows Live Messenger
Client, the IM window is dynamically updated with
your online status without a browser refresh. To initiate a conversation with you, visitors click the Begin
a conversation link in the chat window.
Figure 3 illustrates the dialog flow for beginning a
new conversation using the IM window. When visitors start a conversation, they have three options for
identifying themselves to you:
They can remain anonymous.
They can provide their real name.

www.code-magazine.com

12.02.2008 23:49:04 Uhr

IM Control

IM Client

Figure 4: Communications between the IM Control


hosted on a Web site and the traditional messenger
client.
They can sign in to their Windows Live account
and use that identity.

that the control can gain access to your online presence and do things like display your status icon and
name. You can do the same for users that visit your
Web application by inviting them to share their online presence via the Web sign-up URL. This makes
it possible to identify visitors by their messenger ID
and use that to show their online presence information for a personalized experience.

The first dialog in Figure 3 illustrates a visitor typing


their real name, but they could as easily use the default Visitor or some other anonymous name. Visitors can also sign in to their Windows Live ID account from this dialog, if they arent already signedin. Regardless of the visitors identity, the control will
always present a HIP-CAPTCHA (Human Interactive ProofsCompletely Automated Public Turing
test to tell Computers and Humans Apart) image to
prevent IM spamming. Once completed the IM window is ready for chat.

The following hyperlink will send the user to the Windows Live ID sign-up page (websignup.aspx) to sign
in, supplying a return URL (default.aspx) for the host
application, and a privacy policy URL (privacypolicy.
aspx) so that users can verify trust:

Once the visitor types a message and hits Send


which is only possible if you are onlinethe control
directs the message to your messenger client and
you receive a message as you would from any other
contact. If the visitor is not signed in to messenger,
although the name they presented is in the conversation dialog title, their ID has this format:

<asp:HyperLink ID="lnkSharePresence"
runat="server" NavigateUrl=
"http://settings.messenger.live.com/
applications/websignup.aspx?
returnurl=http:///default.aspx&
privacyurl=http:///privacypolicy.aspx">
Share Your IM Presence</asp:HyperLink>

[unique id]@anonymous.messenger.live.com

The link directs users to http://login.live.com, which is


a page where they can sign in to their Windows Live
ID account, if they arent already signed-in. The next
page prompts them to approve sharing their online

If the contact, signed-in to Windows Live ID or not,


is sending you messages from the Web, their identity
includes the (Web) prefix as shown in Figure 4. You
have the option to add the contact to your list, but
for anonymous visitors this has no real value.
The steps to set this all up are fairly trivial: enable
sharing your online presence, generate HTML, host
the HTML in your Web application, and wait for
visitors to send you messages! What can enhance
this experience is the presence API, which you can
use to identify visitors to your Web application and
to encourage them to log in to their Windows Live
ID account before proceeding with chat.

Inviting Visitors to Share Online Presence


When you generate HTML for the IM control, it
uses your messenger ID in the invitee address so

www.code-magazine.com

CoDe_FocusLive.indd 15

Figure 5: During the Windows Live Web sign-in process, users are asked to enable their presence
and to confirm that they will share their messenger ID with the site they are visiting.

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

15

12.02.2008 23:49:04 Uhr

Listing 2: Processing the JSON response with a JavaScript callback function.


<b><label id="lblName" ></label></b><br />
<b><img id="imgStatusIcon" /><label id="lblStatus"></label></b>

var status = document.getElementById('lblStatus');


status.innerText = presence.statusText;

<script type="text/javascript" language="javascript">


function displaypresencedetails(presence)
{
var statusIcon = document.getElementById('imgStatusIcon');
statusIcon.src = presence.icon.url;
statusIcon.alt = presence.statusText;
statusIcon.style.border = 'none';
statusIcon.width = presence.icon.width;
statusIcon.height = presence.icon.height;

var name = document.getElementById('lblName');


name.innerText = presence.displayName;
}
</script>
<script type="text/javascript" language="javascript"
src="http://messenger.services.live.com/users/
[messenger id hash]@apps.messenger.live.com/presence/?
cb=displaypresencedetails">
</script>

presence with the requesting host, as shown in Figure


5. If they accept, the page redirects to the return URL
passing their messenger ID as a query string parameter named id. If they decline, or if there is no privacy
policy, the query string indicates this in the result
parameter. Basically, the return URL is responsible
for determining if the user approved sharing their online presence.

The presence API is a simple, HTTP-based API that


exposes two queries about a particular messenger
account: one for the status icon, another for a more
detailed representation of the users presence. The
URL syntax for a query is:

The following code illustrates how to gather the query string parameters and process the various possible
responses:

You can pass the messenger ID for any user, including one retrieved from a call to the Web sign-up
page discussed earlier. The messenger ID is in the
form:

if (!this.IsPostBack)
{
string result = Request.QueryString["result"];
string id = Request.QueryString["id"];
if (!String.IsNullOrEmpty(result))
{
if ((result == "Accepted") && (id != null))
this.lblName.Text = "Presence ID: " + id;
else if (result == "Declined")
this.lblName.Text = "Presence unavailable.";
else if (result == "NoPrivacyUrl")
this.lblName.Text = "No privacy Url.";
}
}

You can use the messenger ID provided by sharing


online presence to personalize the Web application,
passing it to the presence API.

Gathering Details through the Presence API


The Windows Live Messenger IM Control leverages
the Windows Live Messenger Presence API to display information about the control host (the invitee),
such as their online status and name. You can also
use the presence API directly from any Web page to
identify visitors if they agree to share their presence
with the requesting host. Together with the Web signup URL, you can use the presence API to encourage
visitors to sign in to their Windows Live ID account,
share their online presence with the Web application, and allow the application to identify the visitor
in order to present personalized information about
them, such as their online status and name.

16

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

CoDe_FocusLive.indd 16

http://messenger.services.live.com/users/
[messenger id]/[resource]/[?queryparameters]

[unique id]@apps.messenger.live.com

The resource can be presenceimage or presence. A


query for the presence image returns a URL for the
status icon of the messenger account. You can use
this to present a graphic representing if a user is
online or not as follows:
<img id="imgStatusIcon"
src="http://messenger.services.live.com/users/
[unique id]@apps.messenger.live.com/
presenceimage" />

A query for the presence details returns a JSON


result, which includes the accounts messenger ID,
the display name, and the status name and icon.
The format of the JSON response is:

The Messenger Library


does not replace the functionality
of the IM control since it does not
support anonymous conversations,
but it does make it possible
to build a rich experience
for existing Windows Live
users with some very powerful
customization possibilities.

www.code-magazine.com

12.02.2008 23:49:05 Uhr

{
"status": "[messenger status]",
"icon": {
"height": 16,
"url":
"http://settings.messenger.live.com/static/w13r2
/Conversation/img/[status icon lename].gif",
"width": 16
},
"statusText": "[localized messenger status]",
"id": "[messenger id]@apps.messenger.live.com",
"displayName": "[messenger display name]"
}

The best way to work with the JSON response is to


provide a callback script function that can process
the presence details. Listing 2 shows an example of
this.
Why display the status of a user visiting your site? A
perfect example is a social networking site that uses
Web signup to register users for their own personal
space, and then subsequently stores their messenger
ID to provide a personalized experience for the user.
When they log in to their personal space on the Web,
the application can show their messenger status (using the presence API) and provide a link to the IM
window (using the IM control). This allows others
visiting their personalized page to chat with them! In
fact, Listing 1 shows this in the HTML for the button
representation of the IM control.

Kick it up a Notch with the Windows


Live Messenger Library
Based on the discussion thus far, you should gather
that the Windows Live Messenger IM Control provides a quick and easy way for non-developers to enable their presence on the Web and is particularly
useful for chatting with anonymous visitors. The
Windows Live Messenger Presence API provides a
way for visitors to log into their Windows Live ID account and identify themselves to the IM control and
to the host application for personalization. Together
these products enable interaction with a particular
messenger account, specified by the invitee, and allow non-Windows Live users to send messages without installing the Windows Live Messenger Client.
The Windows Live Messenger Library extends this
functionality by providing a rich SDK to build a customized messenger client on the Web. The features
supported by the Messenger Library include:
A simple sign-in control for authenticating messenger accounts.
Access to the signed-in users online presence
for personalization.
Access to the signed-in users contact list and
groups to replicate Messenger client functionality on the Web.
A rich API for programmatically interacting
with the signed-in users contact list and groups;
for sending and receiving messages; and for interacting with conversations.

www.code-magazine.com

CoDe_FocusLive.indd 17

NOTE: At the time of this writing, the Messenger


Library was still in beta and not yet released. For
the latest status and SDK updates please go to dev.
live.com/messenger.
Using this SDK you can reproduce the messaging functionality of Windows Live Messenger on
the Web or customize it to fit the business drivers of the hosting Web application. The Messenger Library does not replace the functionality of
the IM control since it does not support anonymous conversations, but it does make it possible to
build a rich experience for existing Windows Live
users with some very powerful customization possibilities.
Why would you want to replicate messenger (customized or not) on the Web? First and foremost it
definitely increases the stickiness of your Web application if visitors can interact with their social network
without navigating away from the Web page to open
the messenger client. In particular for full-screen experiences such as online videos or games, accessing
the chat window in place is also a huge convenience.
Another important benefit is the instant social network that is available through the Windows Live ID
contact list of a signed-in visitor. This simplifies life
for the visitor since their existing contacts are immediately available to themrather than building a
new network for the Web application, they have an
instant network in their Windows Live ID contacts.
This also opens the door to interesting possibilities
for the Web application to provide functionality to
interact with that network.
The coming sections will explore the richness of this
SDK, explain how to get set up to use it, and show
you how to use the key features available to your
Web applications that employ it.

Developing with the Messenger Library


The Windows Live Messenger Library is a clientside library written in JavaScript. Thus, any page in
your Web application that leverages the Messenger
Library must import messenger.js as follows:
<script src="http://settings.messenger.live.com/
api/1.0/messenger.js" type="text/javascript"
language="javascript"></script>

From here, your job is to write code in JavaScript


to access the features and functionality of the library. For example, to add the SignInControl
from the Messenger Library to a Web page, you
would include both the Messenger Library script
and another script containing a function to load
the control. In the following example, when the
page loads, it calls AuthenticateUser() from the
custom JavaScript library, MyMessengerScriptLibrary.js:
<body onload="AuthenticateUser()">
<script src="http://settings.messenger.live.com/
api/1.0/messenger.js" type="text/javascript"

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

17

12.02.2008 23:49:05 Uhr

Messenger Library. Call those functions from


any Web page in the dependent application.
Copy the .js output of the compiled Script# library to the Web application that will use the
library. You can automate this with a post build
step for convenience.

language="javascript">
</script>
<script
src="App_Scripts\MyMessengerScriptLibrary.js"
type="text/javascript" language="javascript">
</script>

The Importance of
Privacy Policies
As they say: with great power
also comes great responsibility.
The privacy policy of the
Windows Live Messenger
Library explicitly forbids the
use of the information available
through the SDK for SPAM
over IM (SPIM). Certainly any
sites that misuse this power
will swiftly be blacklisted or
become social outcasts.
Thus Web applications that
leverage the Windows Live
Messenger Library must
provide very clear privacy
policies and use ethical
business practices as they
interact with the information
available to them.

<div id="divSignIn">
</div>
</body>

As for the coding experience, the previous code snippet for the JavaScript function named authenticateUser() would look like this in the Script# library:

Inside MyMessengerScriptLibrary.js is the following


JavaScript function creating a SignInControl instance
passing the required parameters (to be discussed):

namespace MyMessengerScriptLibrary
{
public class Authentication
{
public static void authenticateUser()
{
SignInControl signinControl = new
SignInControl("divSignIn",
"http://.../PrivacyPolicy.htm",
"http://.../Channel.htm", "");

function AuthenticateUser()
{
signinControl = new
Microsoft.Live.Messenger.UI.SignInControl(
'divSignIn',
'http:///PrivacyPolicy.aspx',
'http:///Channel.aspx', '');
}

Although Visual Studio 2008 introduces support for


JavaScript debugging, which is fantastic for script
writers, building a complete library of functionality
in JavaScript is usually a cumbersome process given
the lack of rich IntelliSense and lack of knowledge
for the correct syntax. Fortunately, there is a product
called Script# that significantly improves your productivity for building rich JavaScript functionality for
your ASP.NET applications.

Turning C# Developers into Scripting Ninjas


with Script#
Client-side scripting is a necessity with todays AJAXenabled applicationsand working with the Messenger Library adds yet another reason for developers
to learn JavaScript. The problem is that many serverside developers find client-side scripting to be something of a dark art. The coolest thing about Script# is
that C# developers can implement JavaScript without writing JavaScript!
Script# is a C# compiler (at the time of this writing Visual Basic support does not exist) that generates JavaScript instead of MSIL. When you install Script#, it integrates into the Visual Studio
IDE so that you can write libraries of functions in
C# that are then compiled into JavaScript for deployment with your Web application. Here is a summary
of the steps necessary to create a Script# library:
Install Script#, which also installs several Visual Studio templates for creating script libraries.
Create a new project using the Script# Class
Library template. For convenience, include this
project in a solution that also contains your
Web application.
Add a reference to Microsoft.Live.Messenger.
dll, the core assembly containing the Messenger
Library metadata.
Begin writing C# functions to interact with the

18

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

CoDe_FocusLive.indd 18

}
}
}

To call this from a Web page, import the Script#


library JavaScript file:
<script
src="App_Scripts\MyMessengerScriptLibrary.js"
type="text/javascript"
language="javascript"></script>

To trigger the authenticateUser() JavaScript function


when a Web page is loaded, you use the fully qualified function name which includes the namespace
and class name:
<body onload=
"MyMessengerScriptLibrary.Authentication.
authenticateUser()">

NOTE: Keep in mind that at the time of this writing, the Script# compiler changes Pascal case
function names to Camel case names.
In this article, all code to work with the Messenger
Library is written in a Script# library, and thus will
be illustrated in C# using the steps just described.
The compiled JavaScript is ultimately what Web
pages invoke at run timeand given the richness
of the Messenger Library, using Script# is the key
to developer productivity. The Windows Live Messenger Library is a substantive library with over 70
classes for building Messenger-enabled applications.
The remainder of this article will discuss three key
scenarios related to working with users and sign in,
contacts, and conversations.

Signing In and Working with Users


To leverage the power of the Messenger Library, you
must first gain access to a user account. The library
includes a single UI component, the SignInControl,

www.code-magazine.com

12.02.2008 23:49:05 Uhr

Figure 6: The SignInControl


(shown left) allows users to
log in to their Windows Live
account at the login.live.com
site (shown right).

About Script#
which handles authentication of users against the
Windows Live ID domain. Once it authenticates the
user, you can gain access to the user identity and interact with the sign-in and sign-out process for that
user. In addition, through the user identity you can access many other details related to the users Windows
Live ID accountwhich makes it possible to replicate
the messenger client in a customized Web interface.
To add Windows Live ID sign-in functionality to a
page, create an instance of the SignInControl located
in the Microsoft.Live.Messenger.UI namespace of the
Messenger Library. The control constructor has four
parameters:
controlId: The name of the <div> on the page
where the control should be rendered.
privacyStatementUrl: The URL of the Web applications privacy policy, explaining how the
application will use the users account details.
channelUrl: A URL for a page containing
JavaScript for safe cross-site scripting. See following reference for more details on how this
secures communication between third-party
sites and the Windows Live ID domain: http://
msdn2.microsoft.com/en-us/library/bb735305.aspx.
market: An optional culture code specifying
which culture the control should use to display
text.

tication (see Figure 7). If they choose to be automatically signed in, Windows Live ID Web Authentication
(http://dev.live.com/liveid) is used to authenticate the
user with the Windows Live ID cookie stored on the
machine.
NOTE: Windows Live ID Web Authentication
is a free product you can also employ in your
Web applications to authenticate users to your site
using their Windows Live ID accounts, instead of
employing a custom authentication mechanism.
While the SignInControl does provide core functionality for authentication, to fully leverage the Messenger Library you will have to write code to interact
with the authentication process. Listing 3 includes
the code necessary to create the SignInControl, interact with the authentication process, access the authenticated users identity, and, post sign in, access

Script# is a well documented,


well maintained, and well
supported productand the
best part is that is it FREE!
Script# was created by Nikhil
Kothari, a software architect
within the Developer Division
at Microsoft. At the time of
this writing, Script# Version
4.5.0 has been released and is
compatible with Visual Studio
2005 and 2008.
You can download Script# and
read more about the product at
this site:
http://www.nikhilk.net/
ScriptSharpIntro.aspx

You must write the code to create the SignInControl


inside a JavaScript function called by the page (most
likely during load)as discussed in the previous section. The UI representation of the SignInControl is
shown in Figure 6. The user is presented with a Sign
In button, which sends the user to the Windows Live
ID login page. If the user has never signed in and
saved a Windows Live ID cookie to the machine,
they will be asked to log in as shown in Figure 6. If
they have previously logged in and allowed their last
authentication to be remembered, the SignInControl
indicates that the user is already signed in.
The first time that the user authenticates to Windows
Live ID with their account, they are provided with
a page where they can adjust their sign-in settings.
Specifically, this determines if the user wants to be
automatically or manually signed in for future authen-

www.code-magazine.com

CoDe_FocusLive.indd 19

Figure 7: Users have an opportunity to configure their sign-in settings with Windows Live ID. The
Web site clearly states what the requesting host application will have access to and provides a link
to the privacy policy specified in the SignInControl constructor.

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

19

12.02.2008 23:49:05 Uhr

Function Name

Description

authenticateUser()

Creates the SignInControl and hooks its AuthenticationCompleted event so that you can
retrieve the user identity during sign in.

signinControl_
AuthenticationCompleted()

Creates an instance of the User from the identity passed in; hooks the SignInCompleted
event so that you can verify the status of the sign in; and invokes the SignIn() function to
complete the sign-in process.

userAccount_SignInCompleted()

Verifies the success or failure of the sign-in process and, if successful, displays the user
accounts details.

displayAccountDetails()

Accesses the user accounts details through the User object model.

Table 1: The functions used to handle SignInControl authentication and access to user account details.

users account details. Table 1 explains the purpose


of each function shown in the listing.
Essentially, you must hook the SignInControls AuthenticationCompleted event in order to do anything
useful with the users account. This provides you with
access to the user identity, which you can use to create
an instance of the User class from the Microsoft.Live.
Messenger namespace. This class is the root of the
object model for the users account details including
account settings, presence, contacts, conversations,
and messaging. Before signing the user in, hook the
SignInCompleted event of the User type so that you
can verify a successful sign in prior to accessing properties of the user instance. You must also invoke the
SignIn() function for the user instance to complete
the sign-in process. The SignInCompleted event is
fired once the user completes sign inpassing a result
of Success or Failure.
In Listing 3, displayAccountDetails() is called upon
successful sign in to update the page display and show
account information. This listing shows only a subset
of what the code sample illustrates, but Table 2 lists
the type of information accessible through the User
class hierarchy. Most of the functionality in a messenger-enabled application can trace its roots back to the
User class. Beyond sign-in and sign-out functionality,
through this class you can access and modify properties of the user account such as DisplayName, DisplayPictureUrl, Status, and PersonalMessage; access
the contact list; interact with the users mailbox to
add Web e-mail functionality to a site; and create and

interact with messaging conversations with a particular set of contacts.

Working with Contacts


After a user logs in using the SignInControl, you can
access the users contact list through the User instance. The User class exposes three collection properties to access the users contact list:
Contacts: A ContactCollection containing all
contacts in the list.
AllowedContacts: A ContactCollection containing only allowed contacts.
BlockedContacts: A ContactCollection containing only blocked contacts.
You can use any of these ContactCollection instances
to access a list of contacts as follows:
foreach (Contact c in userAccount.Contacts){}
foreach (Contact c in
userAccount.AllowedContacts){}
foreach (Contact c in
userAccount.BlockedContacts){}

To organize contacts according to the groups they


are associated with, you can also access a ContactCollection exposed by the Groups property of the User
instance:

Category

Description

Sign in and Sign out

Functions to sign in or sign out and events to interact with the process providing access to the user identity.

Account settings

Properties to interact with account settings related to privacy mode, the existence of a mailbox or special
features such as mobile messaging, and other settings such as the ability to update the display name of the
account.

Account details

Properties to interact with address settings, address capabilities, online status, presence details including
display name and IM address, and the users identity.

Contacts

Access to the users contacts collection, the ability to add new contacts and access contact details, access to
contact groups, and functionality to send messages to contacts.

Conversations

Functionality supporting creating new conversations with contacts, sending and receiving messages, and
interaction with message generation and formatting.

Table 2: A high-level look at the powerful features available through the User type in the Windows Live Messenger Library.

20

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

CoDe_FocusLive.indd 20

www.code-magazine.com

12.02.2008 23:49:06 Uhr

foreach (Group g in userAccount.Groups){


foreach (Contact c in g.Contacts)
{
if (c.IsAllowed)
{}
}
}

Each ContactCollection contains a list of Contact instances that contain details about each contact. This
information is useful for presenting the signed-in
users contacts in the UI for them to interact with.
Listing 4 shows you how to present a list of contacts to the user after they sign in, organizing the
list by group. In the SignInCompleted event, if sign
in is successful, listContacts() is called to traverse
the contacts within each group. The contact collection for the user and the list of contact IMAddress
instances are saved for later use at the client. Then,
the contact collection for each group is traversed
building an <a> element showing the address of the
contact:
<a href='javascript:MyMessengerScriptLibrary.
ContactsByGroup.showContactDetails([contactIndex])
'>[contactAddress]</a>

The result is a list of links on the page that show


the contacts within their group heading. When a
user clicks the contact link, showContactDetails() is
called passing the index of the contact to display their
details in the page. The information displayed about
the selected contact includes the following properties of the Contact class: Presence.DisplayName,

Presence.PersonalMessage,
Presence.IMAddress.
Address, Presence.Status, IsAllowed, and IsBlocked.
You can use the collection to produce a contact list
for the signed-in user to communicate with directly
from the browser. You can filter this list to organize
by groups, include only unblocked contacts, or even
to produce UI to toggle contact properties, such as
unblocking or blocking contacts using the Allow()
and Block() functions (respectively) exposed by the
Contact class. You can also provide messaging features for the signed-in user so they can exchange
messages with their online contacts. Beyond messenger-like functionality, your Web applications can
also provide other unique ways for signed-in users to
interact with their contact list, such as inviting them
to join the application or sending them a link to the
content they are browsing. In this respect, youve
created an instant social network for the user within
the context of your Web application.

The Art of Conversation: Sending and Receiving


Messages
Providing users with a way to send and receive messages is one of the primary features exposed by the
Messenger Library. To send messages to a contact programmatically, you must have access to the signed-in
User instance and a reference to the IMAddress of the
contact to whom the message will be sent. The Conversation class provides functionality to create a new
conversation and subsequently interact with that conversation by sending messages, handling received mes-

Listing 3: C# code illustrating how to create the SignInControl, handle authentication, and access user account details.
{

namespace MyMessengerScriptLibrary
{
public class AccountDetails
{
private static SignInControl signinControl;
private static User userAccount;

StringBuilder sb = new StringBuilder();


sb.Append("<h1>Account Info</h1>");
sb.Append("DisplayName: ");
sb.Append(userAccount.Address.Presence.DisplayName);
sb.Append("<br/>");

public static void authenticateUser()


{
signinControl = new SignInControl("divSignIn",
"http://.../PrivacyPolicy.htm",
"http://.../Channel.htm", "");
signinControl.AuthenticationCompleted += new
AuthenticationCompletedEventHandler(
signinControl_AuthenticationCompleted);
}

sb.Append("DisplayPictureUrl: ");
sb.Append(userAccount.Presence.DisplayPictureUrl.ToString());
sb.Append("<br/>");
sb.Append("PersonalMessage: ");
sb.Append(userAccount.Address.Presence.PersonalMessage);
sb.Append("<br/>");
sb.Append("Address: ");
sb.Append(userAccount.Address.Address);
sb.Append("<br/>");

static void signinControl_AuthenticationCompleted(object


sender, AuthenticationCompletedEventArgs e)
{
userAccount = new User(e.Identity);
userAccount.SignInCompleted += new
SignInCompletedEventHandler(userAccount_SignInCompleted);
userAccount.SignIn(null);
}

sb.Append("LiveId: ");
sb.Append(userAccount.Identity.LiveId);
sb.Append("<br/>");
sb.Append("Status: ");
sb.Append(userAccount.Address.Presence.Status.ToString());
sb.Append("<br/>");

static void userAccount_SignInCompleted(object sender,


SignInCompletedEventArgs e)
{
if (e.ResultCode == SignInResultCode.Success)
displayAccountDetails();
}

Document.GetElementById("divWelcome").InnerHTML =
sb.ToString();
}
}
}

public static void displayAccountDetails()

www.code-magazine.com

CoDe_FocusLive.indd 21

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

21

12.02.2008 23:49:06 Uhr

sages, adding contacts to the conversation for multiple


party conversations, and other related features.
If you provide a user interface with a list of contacts
and maintain a reference to the signed-in user and
contact list as shown in Listing 4your JavaScript
functions will be able to access those references. The
following code assumes the user invokes a function
that passes an index for the correct contact to send a
message to. The User instance is used to create a Conversation instance with a particular contact by calling
Create() on the Conversations collection for the user.
A text message is subsequently sent by calling SendMessage() on the new Conversation instance:
IMAddress address = addressList[index];
Contact contact =
contactList.FindByAddress(address);
Conversation conv = userAccount.Conversations.
Create(contact.CurrentAddress);
conv.SendMessageFailed += new
SendMessageFailedEventHandler(
conv_SendMessageFailed);
conv.SendMessage(
new TextMessage("test message", null), null);

The message is sent to the Windows Live account associated with the IM Addressand if they are signed
in to the messenger client, a new conversation window will appear with the message. If you handle the
SendMessageFailedEventHandler, you will be informed of any failed deliveries so you can present this
information to the user.
SendMessage() supports three different types of messagesTextMessage, NudgeMessage, and ApplicationMessagethe latter of which provides an extensibility
point for custom messages. You can send a nudge to
the participants of a conversation as follows:
conv.SendMessage(new NudgeMessage(), null);

Messages sent from a messenger-enabled Web application will be sent to the messenger application
where the user is signed in. They, in turn, will likely
send messages back. In order to retrieve messages
sent by conversation participants you must hook the
MessageReceivedEventHandler of the Conversation
class after creating the conversation:
Conversation conv = userAccount.Conversations.
Create(contact.CurrentAddress);
conv.MessageReceived += new
MessageReceivedEventHandler(conv_MessageReceived);

When messages are received, the event handler is


passed a parameter, MessageReceivedEventArgs, that
provides access to the Message object. Message is the
base type for all message types including TextMessage and NudgeMessage. You can detect which type
of message it is through the Type property and, subsequently, cast to the correct type to gather necessary
information about the message to present to the user.
Listing 5 illustrates this.

22

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

CoDe_FocusLive.indd 22

You can Close() a conversation instance to free the


resource after sending a message or create a new conversation for subsequent messages. However, if you
save a reference to the Conversation instance, you
can send and receive messages as part of the same
conversation for the user session. Furthermore, you
can invite other contacts to join the conversation by
calling the InviteAddress() function exposed by the
Conversation class. Assuming that you have a reference to the active conversation instance, the following code checks the participant list via the Roster
property to verify if the invitee is already in the conversation. If not, InviteAddress() sends an invitation
to this address:
Conversation conv = null;
if (activeConversation !=null)
{
conv = activeConversation;
foreach (IMAddress a in
activeConversation.Roster)
{
if (a.Address == address.Address)
conv = null;
}
}
if (conv != null)
conv.InviteAddress(address, null);

Of course participants using the messenger client application may also invite additional participants. If
you are presenting a list of participants to the user,
youll need to know when they add or remove new
participants. The Roster property of the conversation
instance tracks these changes. You can handle the
CollectionChanged event of the Roster as follows:
conv.Roster.CollectionChanged += new
NotifyCollectionChangedEventHandler(
Roster_CollectionChanged);

In the event handler, you can iterate through the


Roster collection and present the current conversation participants. Likewise, the conversation instance
exposes a History property that you can monitor for
changes. The History property holds the collection of
messages in the conversation and you can use it to
display or save conversations.
CAUTION: While you should always test and protect against Cross-Site Scripting (XSS) attacks, the
need for secure code is heightened for scenarios like
those discussed in this article since the Windows
Live Messenger Library is accessed via JavaScript.
For more information on protecting against XSS see
the following resources: http://search.microsoft.com/results.aspx?mkt=en-US&setlang=en-US&q=XSS. The code
sample for this article will also include appropriate
measures to protect against XSS, so be sure to note
those recommendations.

Conclusion
Unlike the simplicity of the Windows Live Messenger
IM Control and Windows Live Messenger Presence
API, the Windows Live Messenger Library provides

www.code-magazine.com

12.02.2008 23:49:06 Uhr

Listing 4: Listing contacts by group and displaying contact details.


public static void showContactDetails(int index)
{
IMAddress address = addressList[index];
Contact c = contactList.FindByAddress(address);

private static User userAccount;


private static IMAddress[] addressList;
private static ContactCollection contactList;
static void userAccount_SignInCompleted(object sender,
SignInCompletedEventArgs e)
{
if (e.ResultCode == SignInResultCode.Success)
{
listContacts();
}
}

StringBuilder sb = new StringBuilder();


sb.Append("<h1>");
sb.Append(address.Address);
sb.Append("</h1>");
sb.Append("DisplayName: ");
sb.Append(address.Presence.DisplayName);
sb.Append("<br/>");

public static void listContacts()


{
StringBuilder sb = new StringBuilder();
int index = 0;

sb.Append("PersonalMessage: ");
sb.Append(address.Presence.PersonalMessage);
sb.Append("<br/>");
sb.Append("Address: ");
sb.Append(address.Presence.IMAddress.Address);
sb.Append("<br/>");

contactList = userAccount.Contacts;
addressList = new IMAddress[userAccount.Contacts.Count];
foreach (Group g in userAccount.Groups)
{
sb.Append("<h1>");
sb.Append(g.Name);
sb.Append("</h1>");

sb.Append("Status: ");
sb.Append(address.Presence.Status.ToString());
sb.Append("<br/>");
sb.Append("<b>Contact</b><br/>");

foreach (Contact c in g.Contacts)


{
IMAddress address = c.CurrentAddress;
addressList[index] = address;

sb.Append("IsAllowed: ");
sb.Append(c.IsAllowed.ToString());
sb.Append("<br/>");
sb.Append("IsBlocked: ");
sb.Append(c.IsBlocked.ToString());
sb.Append("<br/>");

sb.Append("<a href='javascript:MyMessengerScriptLibrary.ContactsByGroup.
showContactDetails(" + index + ")'>" +
c.CurrentAddress.Address + "</a><br />");
index++;
}

Document.GetElementById("divSelectedContact").InnerHTML +=
sb.ToString();

}
}
Document.GetElementById("divContactList").InnerHTML +=
sb.ToString();
}

an incredibly rich set of features for interacting with


messenger accounts to produce a messenger-client
experience on the Web. The IM control combined
with the presence API play a very important role
since they dont require development expertise. Just
put the control on a Web page and you have an instance presence on the Internet where others can
reach you. Specifically, the IM control can be used
by anonymous visitors and by non-Windows Live accounts. The Messenger Library is not considered an
extension to the IM controlit serves a much different
purpose with its rich SDK for building a social networking experience for a Web application. Although
exposing a customized messenger client is one aspect
of this, to increase the stickiness of an application,
leveraging the SDK to provide extended features that
enable users to interact with their social network is
extremely compelling and quite powerful. From this
article, you can only begin to appreciate the amount
of functionality available through the Messenger Librarybut the hope is that this inspires you to take a
look at the code and play with the SDK yourself!

Listing 5: Handling received messages.


static void conv_MessageReceived(object sender,
MessageReceivedEventArgs e)
{
string message = "";
if (e.Message.Type == MessageType.TextMessage)
{
TextMessage textMessage = e.Message as TextMessage;
message = textMessage.Text;
}
else if (e.Message.Type == MessageType.NudgeMessage)
{
NudgeMessage nudgeMessage = e.Message as NudgeMessage;
message = "Nudge";
}
Document.GetElementById("divMessageLog").InnerHTML +=
"<b>Received from " + e.Message.Sender.Address + ": </b>" + message + "<br/>";
}

Michle Leroux Bustamante, Paul Birkbeck

www.code-magazine.com

CoDe_FocusLive.indd 23

Live from the Web! Bring the Windows Live Messenger Experience to Your Web Applications

23

12.02.2008 23:49:07 Uhr

ONLINE QUICK ID 0804042

Virtual EarthWhat's New


in the Latest Release?

John OBrien

Now in its sixth major release, Virtual Earth offers an entire world
of opportunities for innovative Web-based mapping.
Microsofts premier Web-based mapping solution has undergone upgrades to
its user interface, compatibility, and functionality making it an ideal time to
get started with the platform or upgrade your existing application. Lets explore
whats new and what has changed in this latest release.

john@soulsolutions.com.au
John OBrien is a Director
of Soul Solutions, based in
Brisbane, Australia.
John is a Windows Live
Developer MVP and
moderates the Virtual Earth
forum on MSDN. He is part
of the core team that runs
the ViaWindowsLive.com
community site for Windows
Live technologies.
John has presented on
Windows Live technologies at
many events including Tech
Ed Australia, Museums and
the Web, and MSDN/SQL user
groups.

24

he Virtual Earth platform combines a


JavaScript library, a rich set of mapping data
and imagery, a set of Web services, and a powerful 3D control. Getting started with the platform
is trivial; a simple HTML Web page is all that you
need to access the powerful AJAX mapping. Listing 1 shows a basic hello world example.

You have three built-in dashboards in Virtual Earth


to choose from or you turn them off completely and
create your own. If you want to change to a different, built-in dashboard, you must do this before you
load the map as follows:

The power of the 2D interface comes from


map = new VEMap('myMap');
JavaScript manipulating the HTML DOM and
map.SetDashboardSize(VEDashboardSize.Tiny);
making AJAX calls directly to Microsofts Web
map.LoadMap();
servers. The interface requires no plug-ins and, in
version 6, supports Internet Explorer 6, 7, Firefox
2, and Safari 2. The 3D conPhotosynth Style
trol, installed on demand and
Fast Facts
still offering a seamless in
Birds Eye Images in 3D
Whether you need a store
browser experience, supports
The Birds Eye images within
locator, sell Real Estate,
Internet Explorer and Firefox
Virtual Earth are truly amazon Windows-based machines
track assets, or simple have
ing. These oblique images are
with adequate 3D hardware.
some data to visualize on the
taken from a low angle and
Earth, Microsoft Virtual Earth
give high-resolution images of
Virtual Earth code developis ready to provide a stable,
all four sides of a scene. Popument is not tied to any server
high-performance, accurate,
lar with Real Estate applicaside technology. As demonand engaging Web-based
tions, these images compliment
strated in Listing 1, the conthe straight down orthogonal
trol only relies on HTML and
experience for your clients.
images providing much more
JavaScript allowing developRich features include in
location detail than simply
ment in your favorite editor.
browser 3D, unique birds eye
rooftops.
Although Microsoft Visual Stuimages, turn-by-turn directions,
dio combined with ASP.NET
and place searches. Visualize
New to Virtual Earth is the
AJAX extensions is an obvious
your
data as a static tile overlay
incorporation of these images
choice, you can quite happily
or interactive pushpins, lines,
in 3D mode. With an interachieve great results with PHP
face style directly based on
and other AJAX frameworks
and polygons.
the upcoming Microsoft Phothe choice is yours.
Development is straightforward
tosynth, the user visually sewith your choice of serverlects high-resolution scenes to
side technology and a well
New Navigation with a
be loaded into the 3D space.
documented and supported
Combined with the existing
New Default Dashboard
JavaScript API.
and ever expanding 3D modWith SSL support and an SLA,
The new navigation dashboard
els, this provides an innovative
as shown in Figure 1 provides
experience ready for develbring Virtual Earth into your
all the default navigation funcopers to utilize in their own
project today!
tionality like zooming, panning,
applications. Figure 2 shows
and changing map styles and
a birds eye scene loaded over
map modes. Revamped in nearly every version to
a set of 3D buildings in New Yorknote the outdate, the latest control has a minimalist look and
line of surrounding images easily selectable by the
smaller download footprint. Importantly the user
user.

Virtual EarthWhat's New in the Latest Release

CoDe_FocusLive.indd 24

can minimize the control if they need more screen


real estate for the map application.

www.code-magazine.com

12.02.2008 23:49:07 Uhr

Listing 1: Virtual Earth Hello World code listing.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Virtual Earth Hello World!</title>
<!--A meta tag declaring utf-8 is required.-->
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<!--There is a single URL for the Virtual Earth JavaScript.-->
<script type="text/javascript"
src="http://dev.virtualearth.net/mapcontrol/
mapcontrol.ashx?v=6">
</script>
<script type="text/javascript">
var map = null;
function GetMap()
{
//The Virtual Earth constructor takes the

//ID of the DIV.


map = new VEMap("myMap");
//LoadMap() creates the map.
//Many optional parameters can be used here.
map.LoadMap();
}
</script>
</head>
<!--You must create the map after the DOM has completely
loaded.-->
<body onload="GetMap();">
<!--A simple DIV is needed as the placeholder for the map.-->
<div id="myMap"
style="position:relative; width:400px;
height:400px;"></div>
</body>
</html>

A tip, use the keyboard arrow keys and the dashboard rotate buttons to navigate between the images seamlessly. You can preview this amazing functionality at http://maps.live.com.
Additionally you get two new Birdseye methods in
the traditional 2D mode, first:
VEBirdseyeScene.GetBoundingRectangle();

This method returns an oversized approximation


of the bounds of the current scene. This method is
perfect if you need to query for data within the current scene. For example you could use the bounding latitude and longitude values returned from
this method to query a database for records within
this birds eye scene, thus loading the records for
display in Virtual Earth on demand and improving
your applications performance.
Due to licensing restrictions, you cannot access
exact latitude and longitude values from birds eye
images.

Figure 1: The Default Virtual Earth Dashboard.

The second method is:


VEMap.SetBirdseyeScene(veLatLong,
orientation,zoomLevel,callback);

This method allows you to request a birds eye scene


based on a latitude/longitude coordinate and zoom
level.
To facilitate highly accurate placement of shapes plotted within the birds eye scene, Microsoft has added
several new methods. Firstly you can configure a
shapes accuracy policy using the method VEMap.
SetShapesAccuracy(policy) where the options are:
None: no shapes are accurately converted (default).
Pushpin: only pushpins are accurately converted.
All: all shapes are accurately converted.

www.code-magazine.com

CoDe_FocusLive.indd 25

Figure 2: Photosynth style navigation of birds eye images


in Virtual Earth 3D.

Virtual EarthWhat's New in the Latest Release

25

12.02.2008 23:49:07 Uhr

Earth just like Figure 3. The application allows you


to build your 3D model in a simple environment
and add either built-in textures or your own. This
allows you to capture an image yourself for use on
your custom model.

Know Your Keyboard


Controls
Arrows (pan)
Ctrl Arrows (pan faster)
+ (Zoom In)
- (Zoom Out)
A (Aerial Style)
R (Road Style)
H (Hybrid Style)
B or O (Birds Eye Style)
3 (3D Mode)
Ctrl and a Left mouse click and
drag (draw new view box)

The models themselves are stored at http://maps.


live.com in a personal collection and you can add
them to your own map by importing that collection
as a layer as follows:
var l = new VEShapeLayer();
var veLayerSpec = new
VEShapeSourceSpecication(VEDataType.VECollection,
"54139577DC329980!625", l);
map.ImportShapeLayerData(veLayerSpec,null,false);

Figure 3: Building a 3D model in 3DVIA.

Within 3D mode:
Ctrl-Q enters 1st person mode
Mouse operates viewpoint
W A S D (move around)
C (Zoom In)
SPACE (Zoom Out)
ESC (Exit)

Secondly you can configure the number of shapes to


accurately convert using VEMap.SetShapesAccurac
yRequestLimit(number). The default is 50. It is important to understand that this process is slow and
you should only use it where absolutely required.

Create Your Own 3D Models


Virtual Earth has had world-class, highly accurate,
3D models for some time. Now, thanks to a partnership with Dassault, the new 3DVIA technology allows you to create your own models within Virtual

Routing Now Supports Multiple Points


Do you want to enhance your application by letting
your users get visual and textual map directions?

The new 3DVIA technology


allows you to create
your own models
within Virtual Earth.

Listing 2: Virtual Earth multi-point route with directions code listing.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Virtual Earth 6 Route Example</title>
<!--A meta tag declaring utf-8 is required.-->
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<!--There is a single URL for the Virtual Earth JavaScript.-->
<script type="text/javascript"
src="http://dev.virtualearth.net/mapcontrol/
mapcontrol.ashx?v=6">
</script>
<script type="text/javascript">
var map = null;
function GetMap()
{
//Load the map as normal.
map = new VEMap("myMap");
map.LoadMap();
//Create an object to set all the route options.
var options = new VERouteOptions();
//The RouteCallback will get the route information.
options.RouteCallback = onGotRoute;
//The array of locations species multi-point routing.
map.GetDirections(["Microsoft", "Everett WA",
"Bellingham WA"], options);
}
//This method res on once the route is calculated.
function onGotRoute(route)
{
var legs = route.RouteLegs;
var turns = "Total distance: " +

26

Virtual EarthWhat's New in the Latest Release

CoDe_FocusLive.indd 26

route.Distance.toFixed(1) + " mi<br />";


var numTurns = 0;
var leg = null;
//The route contains legs, the legs contain items.
for(var i = 0; i < legs.length; i++)
{
leg = legs[i];
var turn = null;
for(var j = 0; j < leg.Itinerary.Items.length; j ++)
{
turn = leg.Itinerary.Items[j];
numTurns++;
turns += numTurns + ". " + turn.Text + " (" +
turn.Distance.toFixed(1) + " mi)<br />";
}
}
//Simply write your string to your directions DIV.
document.getElementById("myDirections").innerHTML = turns;
}
</script>
</head>
<!--You must create the map after the DOM has completely
loaded.-->
<body onload="GetMap();">
<!--A simple DIV is needed as the placeholder for the map.-->
<div id="myMap"
style="position:relative; width:400px;
height:400px;oat:left;"></div>
<!--A simple DIV to house your directions.-->
<div id="myDirections" style="position:relative;
width:400px;height:400px;oat:left;overow:auto;"></div>
</body>
</html>

www.code-magazine.com

12.02.2008 23:49:08 Uhr

Figure 4: A route with turn-by-turn directions.

Great news, the Virtual Earth routing functions


have had a complete makeover for version 6.
Routing will overlay a line along the streets and
roads and provide turn-by-turn instructions for
your selected route, see Figure 4 for an example.
The new method VEMap.GetDirections() accepts
an array of locations for true multi-point routing
and the return method gives a wealth of information about the resulting route, including distances
and estimated time. You can format this information into turn-by-turn directions. Listing 2 provides
a simple example.

It is now supported in an ever-growing number of


cities and is as simple to use as adding one line of
code:
map.LoadTrafc(true);

Additionally you can show a built-in legend to


explain the colors (customizable options include
the title and the position of this legend on the
map):
map.LoadTrafc(true);
map.ShowTrafcLegend(200, 200);
map.SetTrafcLegendText("myTrafc");

Importantly the objects added to the map are true


VEShape classes. Virtual Earth no longer uses the
old VEPushpin, VEPolygon, and VEPolyline classes.
The GetDirections method allows you to specify the
following options:
Whether to display measurements in kilometers or miles.
Whether to draw the route on the map.
Route line color.
The line weight (thickness).
Line Zindex (above or below other objects).
Whether to set the map view to best fit the
route.
Whether to show a disambiguation dialog box if
it cant determine any of the supplied locations.
Whether to show error messages.

Traffic Overlays Anyone?


Being able to plot a route is great, but how about
overlaying the latest traffic flow data like in Figure 5?

www.code-magazine.com

CoDe_FocusLive.indd 27

Figure 5: Traffic flow in San Francisco.

Virtual EarthWhat's New in the Latest Release

27

12.02.2008 23:49:08 Uhr

Support for SSL (Encrypted, Secure)


Web Sites
Virtual Earth targets commercial applications
with accurate and feature-rich functionality. Version 6 now supports the use of HTTPS to support
the growing number of enterprise, e-commerce, or
membership applications that require this level of
security for communications. Previously if your site
ran under SSL, you either had to redirect to another page or put up with mixed content warning
messages.

Localization: First Steps


Microsoft must address a number of different areas
to fully localize Virtual Earth. These include the
control text, the map tiles themselves, and the Web
service results. Version 6 provides the first steps towards localization by providing localized direction
information for routing. To enable localized results,
firstly you must add a query parameter to the Virtual Earth Script URL, for example French:
<script type="text/javascript"
src="http://dev.virtualearth.net/mapcontrol/
mapcontrol.ashx?v=6&mkt=fr-fr"></script>

Table 1 gives the complete list of supported locales.

Clearly it is uncommon
to actually know these coordinates
unless the data
is coming from a GPS device.

Mercator Projection
Virtual Earth 2D uses the
Mercator projection and
uses the WGS84 standard
for its coordinates in decimal
degrees. Essentially in order
to flatten a sphere onto a flat
surface this projection distorts
the earth horizontally while
maintaining accuracy vertically.
This distortion increases as you
move from the equator to the
poles. The side effect is that
countries like Greenland, at the
extreme, look significantly bigger
than in reality. Change to 3D
mode to see objects without this
distortion.

There are two changes required to the Virtual Earth


Script URL to enable SSL. First you must change
the protocol to SSL, second you must add a query
parameter of s=1. The complete URL is as follows:
<script type="text/javascript"
src="https://dev.virtualearth.net/mapcontrol/
mapcontrol.ashx?v=6&s=1"></script>

This functionality is only supported for paying Virtual Earth customers at this time.

Description

Code

English, Canada

en-ca

English, Great Britain

en-gb

English, United States

en-us

Japanese, Japan

ja-jp

Czech, Czech Republic

cs-cz

Danish, Denmark

da-dk

Dutch, Netherlands

nl-nl

Finnish, Finland

fi-fi

French, France

fr-fr

German, Germany

de-de

Italian, Italy

it-it

Norwegian, Norway

nb-no

Portuguese, Portugal

pt-pt

Spanish, Spain

es-es

Swedish, Sweden

sv-se

Chinese, China

zh-cn

Table 1: A complete list of supported locales.

28

Virtual EarthWhat's New in the Latest Release

CoDe_FocusLive.indd 28

The second step to enable the localized directions


is to set the property UseMWS equal to true in the
GetDirections method as follows:
var myRouteOptions = new VERouteOptions();
myRouteOptions.UseMWS = true;
map.GetDirections(['redmond,wa','seattle,wa'],
myRouteOptions);

Improved Geocoding and


Confidence Data
Geocoding is the process of assigning latitude and
longitude values to data such as street addresses. In
order to position anything on the Virtual Earth map,
you need the location as a VELatLong class. Clearly
it is uncommon to actually know these coordinates
unless the data is coming from a GPS device or is
previously geocoded. Virtual Earth provides geocoding within its routing and, importantly, through
the VEMap.Find() method.
The VEMap.Find() method is responsible for geocoding a user-submitted location. This process is
required to make a best guess based on the text
supplied. The method returns an array of VEPlace
objects, which contains:
VEPlace.LatLong: gets a VELatLong Class
object that represents the location of the found
result.
VEPlace.Name: gets the String object that represents Virtual Earth's unambiguous name for
the location.
VEPlace.MatchCode: a VEMatchCode Enumeration value specifying the match code
from the geocoder.
VEPlace.MatchConfidence: a VEMatchConfidence Enumeration value specifying the
match confidence from the geocoder. Values
are High, Medium, or Low confidence.
VEMatchCode enumeration contains:
None: no match was found.
Good: a successful match.
Ambiguous: a number of possible locations
match.

www.code-magazine.com

12.02.2008 23:49:09 Uhr

UpHierarchy: the match was found by a


broader search.
Modified: the match was found, but to a modified place.
These classes give you, the developer, detailed information you need to customize the results for your
application and required accuracy.
Virtual Earth now supports Roof Top Geocoding
in the United States. Rather than simply marking
the location of the address on the road, this process
will mark the actual house at that address. This is a
very important feature for Real Estate applications.

Usage Tracking and Client Identification


with Tokens
The Virtual Earth platform now supports a mechanism to track individual usage. Essentially your
Web server requests a specific token identifier using a secure Web service for each instance of a Virtual Earth map you serve. This token, specific to
your application, is then set within the JavaScript
Virtual Earth control before the map is loaded:
var map = new VEMap("mymap");
map.SetClientToken(token);
map.LoadMap();

As JavaScript executes on the client, this token


is public. For this reason the token is generated
uniquely for each map, specific to your application.
Microsoft has added two new Virtual Earth events
to support possible errors with tokens. You can attach to ontokenerror to receive notification if the
token is not valid. Second, as the tokens themselves
have a configurable lifespan, you attach to ontokenexpire to receive a notification if the token expires.

Figure 6: The new Hill Shaded tiles in Virtual Earth.


map.SetMapStyle(VEMapStyle.Shaded);

With this addition you now have four tile sets, as


well as the unique birds eye images and textured 3D
models making up the imagery of Virtual Earth.

Prefer to Zoom to the Mouse Pointer?


A new option for navigating Virtual Earth is to
change from the default, where the mouse scroll
wheel zooms on the center of the screen, to a mode
where Virtual Earth will zoom on the mouse location
itself. It can be a little counter-intuitive at first as this
functionality was previously reserved for a double
click on the map. It does however, with a little practice, allow for a click-less zoom to any point on the
planet. It is enabled with one line of code:
map.SetMouseWheelZoomToCenter(false);

The usage statistics are then available for review


on the Virtual Earth Platform Customer Services
site alongside your Map Point Web Service usage.
Microsoft is recommending all commercial applications implement the new tracking system. It
will be a requirement of a Service Level Agreement
(SLA) offered to commercial customers.

New Tile SetHill Shaded


The core imagery of Virtual Earth is broken into
tile sets, these 256 x 256 px images are loaded on
demand in both the 2D AJAX control and the 3D
control. Hill Shaded is a new tile set that combines the lightweight, easy-to-read road tiles with
a 3D shading effect based on the elevation data
(Figure 6). The result provides an alternative to
the existing Hybrid tile set which provides the
road information over the satellite and aerial photography available in the Aerial tile set. To switch
to the new shaded tiles, use the new enumeration
value in the map load or call:

www.code-magazine.com

CoDe_FocusLive.indd 29

Shapes Get Faster and Some New


Methods Also
Shapes are interactive elements you can add to your
map. These include:
Pushpins: representing a single point.
Poly lines: representing a path of many points.
Polygons: representing a closed area of points.

Zindex
You can now change the Zindex of shapes. As
shapes can easily overlap, it is important to be able
to control which shape appears on top or behind.
This is the same concept as in applications like Microsoft PowerPoint, where you may send objects
backwards or forward in their Z index. Microsoft
has added three new methods to retrieve and set
Zindex for the icon (pushpin) and the line or polygon separately, collectively called the polyshape.

Virtual EarthWhat's New in the Latest Release

29

12.02.2008 23:49:09 Uhr

Number of Pins

Single Add in Loop (sec)

Bulk Add (sec)

0.008

0.004

10

0.066

0.022

100

0.632

0.209

500

2.883

1.477

1000

7.264

2.259

2000

21.831

5.644

Table 2: Performance comparison of AddShape() as executed in Internet Explorer 7 under


Microsoft Vista x64 on a Dell XPS1330 2.4 Ghz 4 GB RAM.

Reduction of Polygon / Poly Line Accuracy


Enabled by default, Virtual Earth will now remove
points within a polygon or poly line that are very
close visually given the current zoom level. The
concept is to reduce the complexity of these objects to improve performance, for example when
a 1000 point polygon over New York is viewed at
the country level it only needs a few points or, in
fact, is too small to render at all.
You can disable this new performance feature with
the following code:
map.EnableShapeDisplayThreshold(false);

VEShape.GetZIndex();
VEShape.GetZIndexPolyShape();
VEShape.SetZIndex(icon, polyshape);

Altitude
Within 3D mode, you can now position shapes at a
specific altitude. The VELatLong class now has two
extra properties:

Performance of Bulk Add


The Virtual Earth team has made a significant performance improvement for the addition of many
pushpin shapes to the map. The simple change allows an array of shapes to be added in the existing
function:
VEShapeLayer.AddShape(Array);

VELatLong.Altitude
VELatLong.AltitudeMode

The Altitude is a floating point number while the


Altitude Mode is an enumeration supporting the
following options:
Absolute: the altitude is meters above the
WGS 84 ellipsoid.
RelativeToGround: the altitude is meters
above ground level (default).
This opens up a world of possible visualizations
within 3D mode for anything above the ground.
You may have already seen some great applications
tracking aircraft online.
Polygons and Poly lines also get a new method to
draw a line to the ground from the shape at altitude.
This also opens up some interesting visualization
options:
VEShape.SetLineToGround(extrude);

Conditional Zoom Level Range

30

It is a simple change to most existing applications to


benefit from this. Rather than adding directly to the
map, add your shapes to an array, and then add this
array of shapes to the map in one call.

Map Cruncher Is Now Part of the Virtual


Earth Platform
The core of Virtual Earth is accurate image tiles
representing the Earth in several different formats. The system allows the user to stream just
the images they require as they pan and zoom
around the planet. This provides the fluid experience and fast load times for such a massive set of
data. A powerful feature is the ability to add your
own tile layers on top of the map. This allows for
the same highly scalable performance for your data
overlay or additional imagery for your application.

It is a common issue with Virtual Earth that as you


zoom out, shapes overlap. You have already seen
how you can adjust the Zindex, but it is also now
possible to hide shapes. Two new methods allow
for the specification of a maximum and minimum
zoom level to show the shape:

Map Cruncher is a tool that imports raster-based


and vector-based images, provides an interface to
align the images directly with Virtual Earth, and
outputs the tiles in the correct format and naming convention for use with the control. Figure 7
shows Map Cruncher in action. You can also run
Map Cruncher from the command line.

VEShape.SetMaxZoomLevel(level);
VEShape.SetMinZoomLevel(level);

Import Your Data Here

This allows you simply to hide some or all of the


shapes or provide additional shapes at other zoom
levels to represent the density.

Lastly Virtual Earth now supports the import


of the common XML format KML or KeyHole
Markup Language. The process to import is iden-

Virtual EarthWhat's New in the Latest Release

CoDe_FocusLive.indd 30

The performance increase is very measureable;


Table 2 shows performance improvements of using
the bulk method over a loop of single AddShape()
calls.

www.code-magazine.com

12.02.2008 23:49:09 Uhr

Figure 7: MapCruncher Beta in action.

tical to the existing GeoRSS or a Live collection


import types; Microsoft added a new enumeration:
VEDataType.ImportXML.
var spec = new
VEShapeSourceSpecication(VEDataType.ImportXML,
"http://enteryourkmlurlhere.htm");
map.ImportShapeLayerData(spec);

Rather than add directly


to the map, add your shapes
to an array, and then
add this array of shapes to the
map in one call.

Unlike GeoRSS, the KML file itself must be located on


a publicly accessible Web server, not a local file or localhost, as the data is parsed through maps.live.com.

Conclusion
Virtual Earth has grown into a mature application ready for use in demanding enterprise applications. The recent update added new functionality, improved the user interface, and increased the
performance while having no breaking changes.
Applications using version 5 may simply need to
change the version number to 6. However to support this, certain functionality from previous versions, such as the old routing method, still works
but has been marked as deprecated:

www.code-magazine.com

CoDe_FocusLive.indd 31

VEMap.GetRoute: use VEMap.GetDirections


instead.
VERouteDeprecated: old VERoute class.
VERouteItineraryDeprecated: old VERouteItinerary class.
Now is the perfect time to update your Virtual Earth
applications to the latest version or begin using this
exciting technology to visualize your location-based
data in your application.
John OBrien

Virtual EarthWhat's New in the Latest Release

31

12.02.2008 23:49:09 Uhr

ONLINE QUICK ID 0804052

Weaving the Windows Live


Services into Your Web Site
Ready to build a Web experience your users will love?
Windows Live Services are the building blocks of your new site. Get started right
now with the Windows Live Quick Applications.

Jason Kelly
jasonk@akonasystems.com
http://blog.akonasystems.com
Jason Kelly is a senior
consultant at Akona Systems,
Inc. in Kirkland, Washington.
He is the development lead for
Akonas Windows Live Center
of Excellence and spends his
time helping customers create
solutions on the Windows Live
platform. Before joining Akona,
Jason worked for eight years
in software development at
Microsoft.

t takes an engaged audience and compelling exWindows Live Spaces Photo API. Just adding those
periences to reach success on the Web. Using
two services gives you full-motion video, user-genWindows Live Services, your site can provide
erated content, and photo albumsall hosted by
engaging experiences that conWindows Live and presented
nect directly with hundreds of
by your site.
Fast Facts
millions of Windows Live users.
The Windows Live Quick
But how do you start? Windows
Visitors to your site can also
Applications are fully
Live Quick Applications gives
communicate and stay connectfunctional Web applications
you an easy way to get started
ed with Windows Live Services.
by showing you how to build
Build Windows Live Messenger
that show how to use
new experiences for your cusinto your site so your users can
Windows Live Services
tomers with Windows Live Sercommunicate with one anto build compelling Web
vices. You can quickly and easother; integrate Windows Live
scenarios. The source code is
ily use Windows Live Services
Alerts to keep them connected
free to download and modify.
to give your users new ways to
anywhere on the network, even
Visit http://www.codeplex.
share information, communiwhen offline.
com/ WLQuickApps for
cate, and stay connected.
You dont have to create an auinformation and downloads.
Each Quick Application uses
thentication scheme for your
several Windows Live Services
users. Your server doesnt need
to store and share data in a fully functional Web
to host streaming media or run a database to keep
application. You can download the source code to
track of contacts. Just build the glueconnect the
learn about Windows Live development and modify
Windows Live Services together to create your own
the code to create your own site.
new user experience.

Everything you need to get started is at http://dev.


live.com/QuickApps/. On this site you can download
the source code, learn how to customize the Quick
Applications, and deploy them on your own site.
Read on for a tour of the Quick Applications and
step-by-step instructions for using the Quick Applications as a starting point for building your next
generation Web experience.

Tafiti uses Silverlight 1.0,


Windows Live ID, and Live Search
to present a highly
immersive search experience.

Windows Live Services


Work Together

You can use each of the Windows


Live Services on its own. You
can build a Web site that uses
Windows Live ID to manage its
user base or add Live Search to
an existing site. However, the
services realize their full potential when combining
several of the APIs into one Web application.
For example, to develop a rich media experience,
just glue together Silverlight Streaming and the

32

Weaving the Windows Live Services into Your Web Site

CoDe_FocusLive.indd 32

Exploring the Quick Applications


The Windows Live Quick Applications are sample
Web applications that use Windows Live Services
to bring a Web scenario to life. Each Quick Application is a free source code download you can customize and use in your own site.
Youll find the source code for each Quick Application on http://dev.live.com/QuickApps, along with
demos, deployment guides, webcasts and more. Using this code to develop your own Web site is easy.
Just download the source code, customize the application to meet your needs, and deploy the finished
Web site.
Lets explore several of the Windows Live Quick
Applications.

Tafiti
Tafiti is one of the newest Quick Applications. It mixes Live Search with Silverlight and Windows Live ID
to present a highly immersive search experience.

www.code-magazine.com

12.02.2008 23:49:10 Uhr

To explore Tafiti, browse to http://tafiti.mslivelabs.


com. Enter a search term, browse the results, and
drag your favorite hits to the Shelf on the right, as
seen in Figure 1.
The Live Search Web Service provides Tafitis
search results. Web results, images, news, book
search, and more are available from the service.
You can integrate Live Search into your site with
the Web service or by inserting a special HTML
block in your Web page. Learn more about integrating Live Search at http://dev.live.com/livesearch.
Live ID enables two features in Tafiti. When you
sign in with a Windows Live ID, Tafiti saves your
shelf with your search results. The next time you
sign in with your Live ID, Tafiti retrieves the shelf,
letting you start researching where you left off.

Windows Live Services


combine the features of Windows
Live with an easy-to-use
developer platform.

Figure 1: Tafiti integrates Windows Live Search with Silverlight and Windows Live ID to make Web
research an engaging experience.

Tafiti also uses Live ID when you send the contents


of your shelf to a friend in e-mail. Tafiti stores your
shelf, associates it with your Live ID, and sends
the recipient a hyperlink to the results.

Contoso ISV
Contoso ISV uses many of the Windows Live Services to build an online Customer Relationship
Management (CRM) application. This Quick App
glues together Silverlight Streaming, Windows
Live Messenger, Windows Live Alerts, and Virtual
Earth to demonstrate a business-focused Web application.
Windows Live Messenger enables several features
in Contoso ISV. The Windows Live Messenger
IM Control drops right into the Web site. It lets
visitors have instant messaging conversations with
Contoso staff without leaving the home page (Figure 2).
Several Windows Live Services come into play
when a customer schedules a meeting. Virtual
Earth is integrated with Windows Live Messenger
to schedule an appointment and get driving directions (Figure 3). When the sales staff schedules
the appointment, the company representative automatically receives a Windows Live Alert notifying them of the new appointment.
Contoso ISV also uses Silverlight Streaming to
deliver the video content displayed on the home
page. Silverlight Streaming offers free hosting of
videos and interactive content. Windows Live

www.code-magazine.com

CoDe_FocusLive.indd 33

Figure 2: Contoso ISV shows how to build a site that incorporates the Windows Live Messenger IM
control.
hosts and streams the media, relieving developers
of storage and scalability concerns.
To see this combination of Windows Live Services
in action, go to http://contosoisv.mslivelabs.com.

Weaving the Windows Live Services into Your Web Site

33

12.02.2008 23:49:10 Uhr

Windows Live
Services
The Windows Live Quick
Applications provide sample code
to get started developing with all
of the following Windows Live
Services:

Silverlight Streaming
Live ID
Live Search
Live Messenger
Virtual Earth
Live Alerts
Live Contacts
Live Spaces
Live Expo

More information on these


services and developer
documentation for all of the APIs
is available at http://dev.live.com.

Figure 3: Contoso ISV uses the Windows Live Messenger Activity SDK to integrate Virtual Earth and Windows Live Alerts
with Messenger.

Contoso Bicycle Club


Contoso Bicycle Club is a place for bicyclists to post
photos and reports from their favorite rides. Despite
the rich content displayed on the site, the application itself does not store any images or maps. All
the photos, reports, and ride routes are hosted by
Windows Live. Its a great example of how you can
glue Windows Live Services together into a complete Web site. The back end is handled by Windows Live; you only need to develop the presentation layer.
Windows Live Spaces stores most of the content for
Contoso Bicycle Club. Members post a description
of each new ride to the space at http://contosobicycleclub.spaces.live.com/. The blog posts include
links to a map of the ride, directions, and a photo
albumall hosted by Windows Live.
The route and directions for the ride come from
Live Search Maps and Spaces hosts a photo album
of the ride. The club Web site combines the data
from these Windows Live APIs into an integrated
view of the ride (Figure 4).
Contoso Bicycle Club also has the Bikes & Kit
sectiona place for users to buy and sell their bicycles and gear. Windows Live Expo hosts the content
for this section; the Quick App uses the Expo API
to retrieve the list of items for sale.

34

Weaving the Windows Live Services into Your Web Site

CoDe_FocusLive.indd 34

This Quick App shows how you can develop a Web


site and use Windows Live to store all the content.
Explore the site and download the code at http://
contosobicycleclub.mslivelabs.com.

More Quick Applications


Youll find several other Quick Applications on the
site. Each of them has full documentation, deployment instructions, and source code available for
download. You can mix and match code from each
one to create the site you want.
For all the Quick Applications, documentation,
demos, webcasts, and source code, go to http://dev.
live.com/QuickApps.

From Quick Application to Your Site


Reviewing the Quick Applications source code is an
easy way to learn how to develop with Windows Live
Services. You can also use the code as a template to
develop new Web sites. The quickest way to build a
Windows Live-enabled Web site is to download the
Quick Applications source code, modify it to meet
your needs, and then incorporate it into your own site.
To get started building your own Windows Live-based
Web site, choose the Quick Application that integrates

www.code-magazine.com

12.02.2008 23:49:11 Uhr

Figure 4: Contoso Bicycle Club mixes content from Windows Live Spaces with geo-tagged data from Live Search Maps to
show the route of a bicycle ride.

the Windows Live Services youd like to use. Then


change the look and feel of the site to reflect your
own design and add any new pages you need. Perhaps
youll want to weave a few more of the Windows Live
Services into your site. Whatever youre building, the
Quick Applications are the perfect starting points.

Getting Started
I am building a site for home theater enthusiasts called
Ultimate Home Theater. The front page will show a blog
of the latest home theater news and will have a link to a
photo gallery. Users should be able to sign up for alerts
when new content is posted and the site needs a place
for users to buy and sell home theater equipment.
I want to get the site online as quickly as possible
without writing custom code to store and retrieve
blog posts, show pictures, or keep track of items for
sale. Thats where Windows Live Services save the
day: Windows Live takes care of uploading and hosting the data. I just write the glue code that calls the
Windows Live APIs and presents the data.
Ill start with Contoso Bicycle Club, because it already
has several features that I want to build into Ultimate

www.code-magazine.com

CoDe_FocusLive.indd 35

Home Theater. It has photo albums and blog posts


and also offers bicycle gear to buy or sell. Thats just
what I need to start building Ultimate Home Theater.
Ill start by downloading the code and getting the
basic site up and running. Then just customize the
site however you like. You might need to add or remove some pages. Perhaps youll want to integrate
more Windows Live Services.

Getting the Code


First, download the Quick Applications code. Go
to http://www.codeplex.com/WLQuickApps and
click the Releases tab. All of the Quick Applications
come in one source code package. Download the
package, unzip it, and then open one of the Quick
Applications in Visual Studio.
Before you start customizing the application, get
the Quick Application up and running on your Web
server. Each of the applications has prerequisites
and installation instructions on its individual CodePlex Web page. After you get the unmodified application up and running, its time to evolve it into
your site.

Weaving the Windows Live Services into Your Web Site

35

12.02.2008 23:49:12 Uhr

Integrating Windows Live Spaces


The home page of Ultimate Home Theater has a
sidebar listing the latest posts to a home theater blog.
Windows Live Spaces hosts the blog content and my
site just subscribes to an RSS feed to get the content. Ill use my existing Space at http://jason-kelly.
spaces.live.com/. A new HomeTheater category in
my Space will contain the content for the blog.
Fi
Figure
55: TTo notify
tif readers
d off
new content, add Windows Live
Alerts to your site. Users who
opt-in receive real-time alerts
in Windows Live Messenger or
e-mail.

Contoso Bicycle Club has an ASP.NET user control


named LatestRidesControl.aspx. It retrieves blog
posts from the Windows Live Spaces RSS feed and
displays them on the site. This control is just what I
need. I simply moved this user control to the main
panel of the page. Then, in Web.config, I changed
the application settings to point to the URL for my
HomeTheater RSS feed. Now, visitors to the Ultimate Home Theater site can see the latest blog posts
from my Space.
For more information on integrating Windows Live
Spaces into your site, browse to http://dev.live.
com/spaces.

Sending Alerts for New Content


With Windows Live Alerts on the site, readers can
opt-in to receive alerts whenever new content is
posted. If a reader is signed into Windows Live

Messenger, an alert will pop up on their screen


with a link to the new post. Alerts can also be sent
by e-mail or to a mobile device.
To add alerts to your site, start at http://signup.
alerts.live.com/ and fill out a Web form with information about the site and the RSS feed URL for
the content. After activating your account, youll
receive an e-mail with a short block of HTML code
to add to your site. The HTML block adds a signup button to the page. Clicking the button brings
readers to the Windows Live Alerts signup page
for your site.
To add Windows Live Alerts to Ultimate Home
Theater, I filled out the registration form and
placed the HTML block on the home page. When
a reader opts-in to alerts from the site and is signed
into Windows Live Messenger, they receive alerts
like the one in Figure 5.

Adding a Photo Album


Contoso Bicycle Club has a photo slide show feature for each ride, but for the home theater site
I want a separate page to host the photos. To do
this, I started with Contosos Ride Report page
and removed several elements I didnt want on the
page. Then I changed the main menu to include a
Photos link that shows the slide show.
The page uses the SlideShow control from the
ASP.NET AJAX Control Toolkit to display an ongoing photo slide show. The control consumes an
RSS feed from my photo album in Windows Live
Spaces and displays each photo in turn.

Listing 1: Photos.aspx.
<asp:Image ID="Slides" runat="server" Height="480"
ImageUrl="images/blank_slide.png"/>
<ajaxToolkit:SlideShowExtender ID="slides"
runat="server" TargetControlID="Slides"
SlideShowServiceMethod="GetSlides"
AutoPlay="true" UseContextKey="true"
Loop="true" />

Listing 1 shows the ASPX code used to create the


slide show. Listing 2 shows the GetSlides() method that parses the photos RSS feed and returns
the slides to the slide show control.

Listing 2: GetSlides method.


public static Slide[] GetSlides(string request)
{
// Spin up a new XML document to house the RSS FEED.
System.Xml.XmlDocument xmlDocument = new XmlDocument();

// Enumerate the enclosures


foreach (XmlNode xmlNode in xmlNodeList)
{
// fetch the description
string description =
xmlNode.ParentNode.FirstChild.InnerText;

// Execute the request using the Reader


XmlReader xmlReader = XmlReader.Create(request);

// Add the slide


slides.Add(new Slide(xmlNode.Attributes["url"].Value,
description, description));

// Load the XML Document with the reader output


xmlDocument.Load(xmlReader);
}
// Fetch the node list from the RSS
XmlNodeList xmlNodeList =
xmlDocument.SelectNodes("/rss/channel/item/enclosure");
// Create arraylist to house the slides
ArrayList slides = new ArrayList();

36

Weaving the Windows Live Services into Your Web Site

CoDe_FocusLive.indd 36

// Return the slides.


return (Slide[]) slides.ToArray(typeof(Slide));
}

www.code-magazine.com

12.02.2008 23:49:12 Uhr

Windows Live Spaces takes care of hosting the


photos, saving me from writing code to handle uploading and storing the images. More information
is available at http://dev.live.com/spaces/photos.

Including Windows Live Expo


To complete Ultimate Home Theater, Ill add a
marketplace for users to buy and sell home theater
equipment. Windows Live Expo is a free online
classified ad service. Live Expo exposes all of its
functionality to developers through a Web service
API. Contoso Bicycle Club already uses this service to allow members to buy and sell bicycle gear.
I just need to change the site to search for home
theater equipment instead of bicycles.
The Contoso Bicycle Club Quick Application implements a useful wrapper for the Live Expo Web service. I can use the ExpoService wrapper for Ultimate
Home Theater by just changing a few parameters.
Each caller to the Windows Live Expo API must
send a unique string called an application key. To
request a free Expo application key, go to http://
expo.live.com/MyAPIKeys.aspx and sign in with
your Windows Live ID. I added my key to the
Web.config file of the application. Then I changed
the code in Classifieds.aspx to search for the desired category and keywords:

The Finishing Touches


To finish up Ultimate Home Theater, I customized
the layout to create a new look and feel for the site.
Modifying the CSS, changing the graphics, and editing the master pages are the final steps of turning
a Quick App into a custom site. You can see the results at http://www.jasonkelly.net/HomeTheater.

Conclusion
Windows Live Services open up the features of Windows Live to any Web site with an easy-to-use developer platform. The wide array of services, simple
terms of use, and helpful documentation simplify
many aspects of modern Web development.
Quick Applications are rich sample applications designed to help you integrate Windows Live Services
into your Web site. More than just sample code,
Quick Applications are fully functional applications that you can customize and extend to build
your own site much more quickly than starting from
scratch.
The latest information on the Windows Live Services is at http://dev.live.com.
Jason Kelly

// Get your appKey from expo.live.com


ExpoService expoService =
new ExpoService(appKey, "1");
XmlDocument xmlDocument =
expoService.GetListings("66", "","home theater");

For information about the API keys and how to call


the Windows Live Expo APIs, view http://dev.live.
com/expo.

CoDe Magazine
www.code-magazine.com

5, 45

Devscovery Conferences
www.devscovery.com

51

EPS Software Corp.


www.eps-software.com

2-3

Microsoft Windows Live


www.devlive.com

83

Xiine
www.xiine.com

84

ADVERTISING INDEX

Advertisers Index
This listing is provided as a courtesy to our readers and
advertisers.
The publisher assumes no responsibility for errors
or omissions.

Advertising Sales:
Vice President,
Sales and Marketing
Tom Buckley
832-717-4445 ext. 34
tbuckley@code-magazine.com
Sales Managers
Erna Egger
+43 (664) 151 0861
erna@code-magazine.com
Tammy Ferguson
832-717-4445 ext 26
tammy@code-magazine.com

www.code-magazine.com

CoDe_FocusLive.indd 37

Weaving the Windows Live Services into Your Web Site

37

12.02.2008 23:49:13 Uhr

ONLINE QUICK ID 0804062

Building Personalized
Applications on the
Windows Live ID Platform
Vaishali De
vaishde@microsoft.com
Vaishali De has been a Program
Manager on the Windows Live
ID team since she graduated
from the University of Illinois
at Urbana-Champaign in
2004. She has worked on
a smorgasbord of features
including profile management,
rename, device authentication,
and service provisioning.
Apart from writing killer specs,
she loves fattening up her
colleagues with home-baked
goodies. With a wide range
of interests outside work, her
office reflects her colorful
personalityit is famous on
the Lakeridge campus for its
wall art.

Do you have a cool personalized application that you want to


offer to over 400 million users? Do you want to light it up with
Live controls or create a mashup with Live resources?
Windows Live ID now offers a simple way for third parties to get Live ID
authentication in your Web or rich client applications, letting you reach millions
of Live ID users, integrate with Live Controls, and access Live services.
indows Live ID supports more than 400 milWindows Live ID authenticates users using crelion active users, performing over a billion
dentials such as user name and password, or Cardauthentications per day, with a consistent
space information cards, which provide higher
availability of over 99.9%. This
security against phishing. The
foundation service is also availLive ID service supports a variFast Facts
able to third-party developers,
ety of authentication protocols,
allowing them to build identityincluding WS-*, which allows
Windows Live ID offers a
aware Web and rich client apfederated users of Windows
simple way for you to get
plications using Windows Live
Live federation partners to use
Live ID authentication in
services, user data, and social
Windows Live and other Live
your Web or rich
relationships.
ID-enabled services. Live ID
client applications, letting
supports a variety of browsers
you tap into over 400 million
This article focuses on the Winand Windows PCs, as well as
Live ID users.
dows Live ID Web and client
phones, MSN TV, and XBox.
authentication and explains
Enrich your Live ID
how you can use it in your apauthenticated applications
Windows Live ID Web
plication.
with Live Controls and data

from other Live services.

What is Windows Live ID?


Windows Live ID is the identity and authentication
platform for all Microsoft online services, such as
Windows Live, Xbox Live, Office Live, etc. Many
third-party sites also use Live ID authentication.
Formerly known as Microsoft Passport, the service
was rebranded to reflect the Windows Live brand,
as well as new scenarios and features developed to
support Windows Live.
To a user, Live ID is their identity on various Microsoft online services. It is what they use to send/
receive e-mail, chat on messenger, or set up a new
Office Live accountso they use it anywhere they
see the Live ID logo. Windows Live ID provides
single sign-on between all Live ID-enabled services,
so once the user is logged in at one of these sites
or rich applications, they are seamlessly signed into
other Windows Live sites as well. For example, the
user can open Live Mail or Windows Live Spaces
from Windows Live Messenger without the need to
provide their credentials again. Also, a user gets a
consistent experience across Microsoft online sites,
since all these sites have access to the users profile.

38

Building Personalized Applications on the Windows Live ID Platform

CoDe_FocusLive.indd 38

Authentication

Windows Live ID Web Authentication helps you build identity-aware Web applications. It is a service that allows you to:
Verify the identity of visitors to your site.
Offer personalized access to your sites content to millions of Live ID users, who dont
need to create yet another identity.
Provide single sign-on from your application
to Windows Live services.
Seamlessly integrate the advanced, and useful,
functionality of Windows Live controls in a
non-programmatic way.
Access users Windows Live data with their
explicit consent.

Why Does Your Web Application Need Live ID?


Wondering what kind of cool functionality Live ID
can help you deliver?
The Party Planner
You have a Web application that helps users host
that perfect party. With the users explicit consent,

www.code-magazine.com

12.02.2008 23:49:13 Uhr

you get access to their Live Calendar and add tasks


to help them get everything done well in time for
the big day.
Discovering the Lonely Planet
You have a mashup Web application that helps
users with their travel plans. Your site is a repository of information on cool locations all over the
world. You help users from picking their vacation
spot to booking their flights, hotels, and attractions to sharing memories from their holiday with
their friends. You incorporate the Live Contacts
Control, letting the user choose what contact information they want to share with your site. The
user then shares vacation plans or even plans a
vacation with selected contacts. You incorporate
the Live Spaces Photo Control and let users upload photos from their vacation from their Live
space. By using Windows Live ID, the user will
be automatically authenticated by these rich controls.

Your Web Server

Users Browser

Figure 1: The Web Authentication flow.

Windows Live ID
Authentication Service

The Web Authentication Flow


Figure 1 shows the Web authentication flow:
1. User visits your Web site.
2. Your site displays a sign-in link in an IFRAME
element.
3. User clicks the sign-in link.
4. Windows Live ID returns the sign-in page.
5. User enters their Windows Live ID credentials
on the sign-in page and submits the form.
6. Windows Live ID validates the users credentials.
7. Windows Live ID authentication server redirects the user to your site along with an authentication token as a form post parameter.
This token is proof that Windows Live ID has
verified the users identity. Your site can decrypt this token to obtain the users unique
site-specific identifier.
8. Your site uses the users site-specific unique
identifier to store or display protected or personalized content. You also incorporate the
Live Contacts Control and Live Spaces Photo Controls into your site.

System Requirements for Web Authentication


Web Authentication uses industry-standard HTTP
protocols and does not depend on any precompiled
or executable components. You can implement it on
any Web-development platform. The SDK provides
samples for ASP.NET, Perl, Java, Ruby, Python, and
PHP. It uses the standard encryption algorithm
available on these platforms.

Getting Started with Web Authentication


Do the following to start using Windows Live Web
Authentication in your Web application:

www.code-magazine.com

CoDe_FocusLive.indd 39

Register your Web application.


Display the sign-in/sign-out link.
Handle responses from Windows Live ID authentication server, to implement login, logout, and clearcookie.
Incorporate Windows Live Controls.
Integrate with Windows Live APIs to access
other Live services via delegation.

Registering Your Web Application


To use Windows Live ID Web Authentication on
your site, you must use a valid Live ID to register
your Web site with Microsoft as an application. The
Windows Live ID application management page
located at https://msm.live.com/app/default.aspx
assists you with the registration process, issues you
an application ID for use with the service, and provides a place for you to manage all the applications
you register.
Register your application and provide the following:
Application Name: The unique and friendly
name you use to refer to your application.
Return URL: The URL of the page on your
Web site that handles responses from the Windows Live ID authentication service. The service redirects users and their authentication
tokens to this URL after they have successfully
signed in, signed out, or cleared their cookies.
Secret Key: The shared secret between you
and Windows Live ID that is used to encrypt
and sign all tokens that Windows Live ID
sends to your site. The secret key must be in a
format specified by Windows Live ID. Choose
one that is difficult to guess and create security
procedures to manage this key.

Building Personalized Applications on the Windows Live ID Platform

39

12.02.2008 23:49:14 Uhr

There is no certification or approvals process. Accept the Windows Live Terms of Use and youre all
set!

Handling Responses from Windows Live ID

Displaying the Sign-in/Sign-out Link


Insert the sign-in/sign-out link into your page to incorporate Windows Live ID. Include the following
code in the HTML of your site, replacing the values
for appid, context, and style with proper values for
your implementation:
<iframe
ID="WebAuthControl"
Name="WebAuthControl"
Src="https://login.live.com/controls/
WebAuth,htm?Appid=<%MyAppID%>&Context=
MyContext&Style=font-size%3A+10pt%3B+
font-family%3A+verdana%3B+background%3A+
white%3B">
</iframe>

Include Windows Live controls


in your Web application to
seamlessly combine these features
with your innovation.

thentication. Style is the set of attributes that makes


the sign-in IFRAME element fit your site visually.

When Live ID users successfully sign in or out of


your site, the Windows Live ID authentication
service responds and redirects them to the return
URL you specified when registering your Web application. This URL must correspond to a dynamic
page that receives and appropriately processes this
response.
The response has an action query-string parameter
that tells your site what it needs to do. The following is the list of possible action values and what
your site must do:

Appid is the application ID you


received when you registered
your site. Context is the parameter holding the user state
for your application and gets
returned in the response from
Windows Live ID authentication server so that you can preserve user state across the au-

login: Your site extracts the users encrypted


authentication token from the HTTP POST response and stores it in a session cookie to keep
the user signed in to your site during multiple
page views.
clearcookie: Your site clears the session cookie
you created at sign in, and returns a Graphics
Interchange Format (GIF) image to the service
to indicate that the user has been signed out.
logout: Your site clears the session cookie and
redirects the signed out user to a page on your
site that is appropriate for unauthenticated users.

Listing 1: Handling different actions in the response from the Windows Live ID authentication service for Web Authentication.
//Handling a login action
If (action == "login")
{
WindowsLiveLogin.User user = wll.ProcessLogin(Request.Form);
//The ProcessLogin method parses, decrypts, and validates the
//encrypted authentication token received from the Windows Live ID
//authentication service, letting you access the user's unique ID
//easily
HttpCookie loginCookie = new HttpCookie("webauthtoken");
//Storing the authentication token in a cookie called
//"webauthtoken" to keep the user signed in to your site during
//multiple page views
if(user != null)
{
loginCookie.Value = user.Token;
if (user.UsePersistentCookie)
//The ProcessLogin populates the user object with properties like
//the user.UsePersistentCookie property. If UsePersistentCookie
//is true, your application is expected to use a persistent cookie
//to store the authentication token. A persistent cookie keeps
//the user signed in across multiple browser sessions
{
loginCookie.Expires = DateTime.Now.AddYears(10);
}
}
else
{
loginCookie.Expires = DateTime.Now.AddYears(-10);
}
Response.Cookies.Add(loginCookie);
Response.Redirect("default.aspx");

40

Building Personalized Applications on the Windows Live ID Platform

CoDe_FocusLive.indd 40

Response.End();
}
//Handling a clearcookie action
else if (action == "clearcookie")
{
HttpCookie loginCookie = new HttpCookie("webauthtoken");
//Deleting the current "webauthtoken" cookie
loginCookie.Expires = DateTime.Now.AddYears(-10);
Response.Cookies.Add("webauthtoken");
string type;
byte[] content;
wll.GetClearCookieResponse(out type, out content);
//GetClearCookieResponse returns a GIF image to the
//authentication server to indicate that the user has signed out
Response.ContentType = type;
Response.OutputStream.Write(content, 0, content.Length);
Response.End();
}
//Handling a logout action
else if (action == "logout")
{
HttpCookie loginCookie = new HttpCookie("webauthtoken");
//Deleting the current "webauthtoken" cookie
loginCookie.Expires = DateTime.Now.AddYears(-10);
Response.Cookies.Add("webauthtoken");
Response.Redirect("default.aspx");
//Redirecting users to the page on your Web application that is seen
//by users who are signed out
Response.End();
}

www.code-magazine.com

12.02.2008 23:49:14 Uhr

Listing 1 demonstrates the handling of the different actions.

Incorporating Windows Live Controls


Include Windows Live Controls in your Web application to seamlessly combine these features with
your innovation. When users log into your site with
their Live ID credentials, they are also signed into
these controls. For example, the Windows Live
Contacts control is a client-side JavaScript object
that allows users to share their contacts with your
site. Users can view presence information for their
contacts and initiate a Windows Live Messenger
conversation with a contact; and you can predefine
messages for users to send to their contacts.

Windows Live ID Delegated Authentication


Create a mashup of rich user content from various
Live services in your application with the users explicit consent using the Delegated Authentication technology. With your site already using Windows Live ID
Web Authentication, this is a simple additional step.
Through delegation, the Windows Live ID users of
your site have the ability to consent to the scoped
release of their personal information to you. For example, the user could consent to share their Live
Calendar with your site and your application can
then access the calendar to retrieve and edit data.

Windows Live ID Client


Authentication
Windows Live ID Client Authentication helps you
build personalized, identity-aware, rich client applications for the huge Live ID user base. Client
Authentication is a managed API intended for use
in developing applications for users desktops, using
.NET Framework. The API lets you:
Verify the identity of users of your client application.
Access information about saved credentials to
implement automatic sign in.
Integrate with other Windows Live services
and obtain authentication tickets necessary to
access users personal data provided by them.
Navigate to Windows Live ID sites in an authenticated browser window.

Why Does Your Rich Client Application Need


Live ID?
Wondering what kind of cool functionality Live ID
can help you build into your client?
Blogit
Your rich client application is a word processor for
authors. An author uses your application to create

www.code-magazine.com

CoDe_FocusLive.indd 41

Figure 2: Sign-in dialog box for Client Authentication.

documents. By incorporating access to Live Spaces,


your application lets the author post their documents to their space and get feedback from their
editor and friends.

The Client Authentication Flow


The Client Authentication flow consists of the following:
1. User runs your client application.
2. Either automatically or in response to a user
action, your client calls the Authenticate
method. Figure 2 shows the sign-in dialog box
that is displayed.
3. User enters their Windows Live ID credentials. If user chooses to store their credentials,
these are persisted to the local store so that
user does not need to provide them to your
client again in the future and is automatically
signed in.
4. Your client application sends the users credentials, encrypted through Secure Sockets
Layer (SSL), to the Windows Live ID authentication server.
5. Windows Live ID authentication server validates the credentials and returns an authentication ticket.
6. The user is now authenticated and your
client provides them with personalized
features.
7. Either automatically or in response to a user
action, your client calls the GetTicket method
to obtain a service ticket to access a specific
Windows Live ID site or service.
8. Your client requests protected content from
the Windows Live ID site or service with the
service ticket.
9. The protected content is returned and displayed to the user.

Sign Me Up!
Get the Windows Live ID Web
Authentication 1.0 SDK from
http://msdn2.microsoft.com/
en-us/library/bb676633.aspx.
Register your application at
https://msm.live.com/app/
default.aspx.
Get the Windows Live ID Client
Authentication 1.0 SDK from
http://msdn2.microsoft.com/enus/library/ bb404791.aspx.

Building Personalized Applications on the Windows Live ID Platform

41

12.02.2008 23:49:14 Uhr

Listing 2: What to do when the user clicks the Sign-in/Sign-out button in your client application.
//Event handler for Sign-in/Sign-out button clicks
private void buttonSignInOrOut_Click(object sender, EventArgs e)
{
//Check to see if the user is currently authenticated
if (!oID.IsAuthenticated)
{
try
{
//Try to authenticate the user by showing the
//Sign-in dialog window
if (oID.Authenticate())
{
currentUserName = oID.UserName;
}
else
{
MessageBox.Show("Authentication failed");
}
}
catch (WLLogOnException wlex)
{
if (wlex.FlowUrl != null)
{
MessageBox.Show(wlex.ErrorString + "Please go
to " + wlex.FlowUrl.AbsoluteUri + "to correct
the condition that caused the error");
}
else
{
MessageBox.Show(wlex.Error String);
}

Windows Live
Controls
Windows Live Controls allow
you to easily incorporate
cool functionality into your
applications. Visit https://dev.live.
com to learn more.

Create a mashup
of rich user content
from various
Live services in
your application
with the users
explicit consent
using the
Delegated
Authentication
technology.

42

else
{
//If user is authenticated, they intended to Sign-out. Try
//signing the user out.
try
{
oID.CloseIdentityHandle();
currentUserName = "";
}
catch (WLLogOnException wlex)
{
if (wlex.FlowUrl != null)
{
MessageBox.Show(wlex.ErrorString + "Please go to " +
wlex.FlowUrl.AbsoluteUri + "to correct the condition
that caused the error");
}
else
{
MessageBox.Show(wlex.ErrorString);
}
}
}
UpdateDisplay();
}

System Requirements for Client


Authentication
Your development computer and users desktop
must be running the following software:
Windows XP Professional with SP2 or Windows Vista (32-bit versions only).
IE 6.0 or 7.0/Firefox 1.5 and above.
.NET Framework 2.0.

Getting Your Application ID


The application ID, your unique identifier, is a
combination of your organization name, e-mail address, and application name. Declare oIDMgr as an
instance of IdentityManager at the class level so
that all your code can access it. Pass the application
ID as a parameter to the CreateInstance method
and assign the return value to oIDMgr:

I strongly recommend you use the Visual Studio


IDE to develop your client application.

oIDMgr = IdentityManager.CreateInstance("BlogIt;
vaishali@contoso.com;BlogIt Application",
"Windows Live ID Client");

Getting Started with Client Authentication

Setting Up Your Development Environment

To start using Windows Live Client Authentication


in your rich client application, do the following:

Add a reference to the component to your Visual


Studio project, so that you can use Windows Live
ID for your client application.

Get your application ID.


Install the Windows Live ID Client 1.0 SDK.
Set up your development environment.
Implement system requirement detection, authentication, automatic sign in, personalization, and access to Windows Live ID sites and
services.

The SDK includes a sample application intended


to help you understand how to code your client,
by showing you the source code that is required to
implement the features of Windows Live ID Client
Authentication.

Building Personalized Applications on the Windows Live ID Platform

CoDe_FocusLive.indd 42

}
}

Implementing System Requirement Detection


Your client developed using Windows Live ID for
client applications requires the installation of the
Windows Live ID Client Authentication redistributable component. This component is the assembly
(DLL) that contains the Microsoft.WindowsLive.
Id.Client namespace. Without this, your client will
not run. Your application needs to handle the case
when this assembly is not available on the machine.

www.code-magazine.com

12.02.2008 23:49:15 Uhr

Implementing Authentication
Call the Authenticate method to authenticate the user.
This method shows the user the sign-in dialog box shown
in Figure 2. This standard dialog box allows the user to
enter their Windows Live ID credentials and makes it
really easy for you to log the user in. Listing 2 shows you
what you need to do when the user clicks the Sign-in/
Sign-out button. Declare oID as an instance of Identity
at the class level so that all your code can access it.

Implementing Automatic Sign-in


Your client must automatically sign-in the user if
the user previously signed into your client application and selected the check boxes to remember both
their sign-in name and password.
To implement automatic sign-in, your application
must recognize the concept of this default user who
will be automatically signed in. Store the sign-in name
of this default user in a configuration file, the registry,
text file, Web service, or any other method and pass it
in as the parameter to the CreateIdentity method.

Implementing Personalization
A user personalizes your client application by specifying various data and settings to customize it. Every
time the user signs into your client, you load these data
and settings into the application. For example, users
could pick a background color for the application or
organize their Live contacts in a particular manner.
Your client:
Lets the user create data and settings for personalization.

Stores user-specific data and settings.


Loads and displays user-specific data and settings when user logs in.
Lets the user modify or delete their data and
settings.
Windows Live ID provides a permanent, unique
identifier for the user in the form of the Client ID
or CID. Access to the CID
is provided through the CID
property of a currently authenYour rich client can
ticated Identity object. Storing
the user-specific data and setaccess Windows Live sites and
tings with the CID gives you
services through a Web service,
the power to roam the data
across machines. Store the
an API installed on the local
data and settings in a configucomputer, or an authenticated
ration file, the registry, a database, text file, Web service,
browser window.
or any other method of your
choice.

Implementing Access to
Windows Live ID Sites and Services
Your client can access Windows Live ID sites and
services in the following ways:
Through a Web service API, such as SOAP or
XML-RPC.
Through an authenticated browser window.
For access through a Web service API, your code
will:
Authenticate the user with the Authenticate
method.
Obtain a service-specific ticket with the GetTicket method.

Windows Live
Delegated
Authentication
Windows Live Delegated
Authentication allows thirdparty applications to access
Live ID users information with
explicit user consent. For more
information, please refer to
Windows Live Delegated APIs
on page 46.

Listing 3: Calling the MetaWeblog API from your client application.


//Posting to a blog
public static void PostBlog(string subject, string body, string
spaceUrl, Identity oId)
{
spaceUrl = ReplaceInvalidXMLChars(spaceUrl);
body = ReplaceInvalidXMLChars(body);
subject = ReplaceInvalidXMLChars(subject);
//
//
//
//
//
//
//
//

The following statement creates the HTTP request to post a


new blog. The statement creates a byte array that is based
on the requestXML string, which contains the metaweblog API XML
statement for creating posts. This string is then modied with
four variables: a blog name, which is "MyBlog", spaceUrl, which is
a user-supplied identier of their blog location, a string that
contains the subject of the blog, and a string that contains the
blog entry.
byte[] postData = new UTF8Encoding(false).GetBytes(String.
Format(requestXml, "MyBlog", spaceUrl, "", subject, body));

// Building the HTTPWebRequest object, using a pre-dened string,


// SPACES_API_URL

www.code-magazine.com

CoDe_FocusLive.indd 43

HttpWebRequest request = (HttpWebRequest)HttpWebRequest


Create(SPACES_API_URL);
// Create a string to get the authentication ticket, then acquire
// the ticket
string ticket = "";
try
{
ticket = oId.GetTicket("storage.msn.com", "MBI", true);
}
catch (WLLogOnException wlex)
{
if (wlex.FlowUrl != null)
{
MessageBox.Show(wlex.ErrorString + "Please go to "
+ wlex.FlowUrl.AbsoluteUri +
"to correct the condition that caused the
error");
}
else
{

Building Personalized Applications on the Windows Live ID Platform

43

12.02.2008 23:49:15 Uhr

Listing 3: Continued
MessageBox.Show(wlex.ErrorString);
}
}

// Build the HTTP headers, including the authorization ticket


request.Headers.Add("Authorization", "WLID1.0 " + ticket);
request.AllowAutoRedirect = false;
request.UserAgent = "WindowLiveClientSDKSpacesLoginTester";
request.ContentType = "text/xml";
request.Pipelined = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postData, 0, postData.Length);
}
// Get the response back from the HTTP request
HttpWebResponse response = (HttpWebResponse)request.
GetResponse();
// Code that manages the response could go here
}

//Getting posts from a blog


public static void GetPosts(string spaceUrl, int numberOfBlogs,
Identity oId)
{
spaceUrl = ReplaceInvalidXMLChars(spaceUrl);
//
//
//
//
//
//
//
//
//

The following statement creates the HTTP request to get a


specied number of blog posts. The statement creates a byte
array that is based on the getPostsXml string, which contains the
metaweblog API XML statement for getting posts. This string is
then modied with three variables: a blog name, which is "MyBlog",
spaceUrl, which is a user-supplied identier of their blog
location, and a number that species the number of blog entries
to return. In this case, you are getting one blog entry back, but
you can return up to 20

byte[] postData = new UTF8Encoding(false).


GetBytes(String.Format(getPostsXml, "MyBlog", spaceUrl, "",
numberOfBlogs));

// Building the HTTPWebRequest object, using a pre-dened string, SPACES_API_URL


HttpWebRequest request = (HttpWebRequest)HttpWebRequest.
Create(SPACES_API_URL);
// Create a string to get the authentication ticket, then acquire
// the ticket
string ticket = "";
try
{
ticket = oId.GetTicket("storage.msn.com", "MBI", true);
}
catch (WLLogOnException wlex)
{
if (wlex.FlowUrl != null)
{
MessageBox.Show(wlex.ErrorString + "Please go to "
+ wlex.FlowUrl.AbsoluteUri + "to correct
the condition that caused the error");
}
else
{
MessageBox.Show(wlex.ErrorString);
}
}

// Build the HTTP headers, including the authorization ticket


request.Headers.Add("Authorization", "WLID1.0 " + ticket);
request.AllowAutoRedirect = false;
request.UserAgent = "WindowLiveClientSDKSpacesLoginTester";
request.ContentType = "text/xml";
request.Pipelined = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postData, 0, postData.Length);
}
// Get the response back from the HTTP request
HttpWebResponse response = (HttpWebResponse)request.
GetResponse();
// Code that manages the response (parses, etc.) could go here
}

Add the ticket as a request header for the


SOAP or XML-RPC calls.
For HTTP-based SOAP calls, refer to the documentation for the service to find the URL of the Web
Service Description Language (WSDL) file that describes the service and add a Web reference to your
application project in Microsoft Visual Studio.
Listing 3 demonstrates calling the MetaWeblog
API, both to post data and to get data back.
How you open an authenticated browser window
depends on which browser the user has installed.

44

Building Personalized Applications on the Windows Live ID Platform

CoDe_FocusLive.indd 44

For IE 6.0 or 7.0, call the OpenAuthenticatedBrowser method. For browsers other than IE, invoke the execution of the browser and make sure
that the browser sends the appropriate authentication data in a form post to the Windows Live ID site
or service URL. Obtain this authentication data by
calling the GetNavigationData method.
Special thanks to Dave Shevitz and Vivek Nirkhe
for their help with this article.
Vaishali De

www.code-magazine.com

12.02.2008 23:49:15 Uhr

Get 1 year of CoDe plus this


book for ONLY $37.95*

Pay the special combination price of just $37.95


and you will receive a 1 year subscription to
CoDe Magazine AND a copy of Pro VS 2005 Reporting!
Two great developer references, one low price! With this special offer
you get cutting edge, in-depth Visual Studio .NET articles delivered to your door six times a year with Code Magazine plus a copy of
Pro VS 2005 Reporting by Kevin Goff and Rod Paddock (the editor of
CoDe Magazine).
This combination offer is only available online using this special URL:

www.code-magazine.com/subscribe/ap37

Visit www.apress.com for more great .NET titles!


* While supplies last. Please allow 4-6 weeks for delivery. US addresses only.

CoDe_FocusLive.indd 45

12.02.2008 23:49:16 Uhr

ONLINE QUICK ID 0804072

Windows Live Delegated APIs


The smart way to share data between computers and other
people is to place it in an online Internet store, which the other
parties can access, but you want to make sure only the right
people can access your data.
This article will help you understand how the Windows Live delegated
authentication system is used to access certain Windows Live data stores and
the technologies Microsoft is building to make this work easier for you.

Dr. Neil
Neil@Roodyn.com
Dr. Neil is an independent
itinerant consultant, trainer,
and author. He travels the
world working with software
companies. Dr. Neil loves
Australia, where he spends the
summer enjoying the Sydney
lifestyle and helping software
development teams get more
productive. Dr. Neil spends his
other summer each year flying
between northern Europe and
the USA working with software
teams and writing about his
experiences. Neil brings his
business and technical skills to
the companies he works with
to ensure that he has happy
customers. His latest book
eXtreme .NET (Addison Wesley,
2005) introduces eXtreme
Programming Techniques to
.NET developers. Dr. Neil is a
Microsoft Regional Director
and a Windows Live Developer
MVP.

Dr. Neil founded

http://ViaWindowsLive.com,
a Web site to help developers
build on Windows Live
services.

You can find out more about


Neil from
http://www.Roodyn.com.

46

Windows Live Delegated APIs

CoDe_FocusLive.indd 46

he Internet provides a fantastic backbone for


You Need My Authority (But You
sharing data. For many years Microsofts conArent Me)
sumer services have helped users manage an asIf you are building an application that needs to acsortment of data, such as photos on Spaces and concess a users data, your application will need to ask
tacts in Messenger and Hotmail. Some of this data
the user to authenticate the access. This authenticayou want to share with a set of users; that set can
tion can happen in several ways, for this article I am
range from the entire user base of the Web to just
going to concentrate on the guidance Microsoft is
yourself. An example of data you want to share would
giving for the way forward.
be photos of your vacation you put in Spaces for your
friends to view. For other data
Windows Live delegated autypes you have an expectation of
Fast Facts
thentication is a technology
privacy and security, for example
A standard authentication
that allows a user to delegate
you dont want your contacts list
technology to allow your
authority to a particular apto be publicly available. One
plication for a set of resources.
of the advantages to putting all
Web application to access
The user is able to specify for
this data online is that it allows
the data of Windows Live
how long the application will
you, the user, to access your data
users and exposing many of
be able to access the Live refrom multiple locations.
these services with the Atom
sources; this could be a matter
Publishing Protocol will make
There are two distinct types of
of minutes, days, or months.
Windows Live Data
data that users have stored online and it is important to unSome of the services provided
easy to access and yet
derstand the difference, even if
by Windows Live will offer
remain firmly controlled by
it is not something the user conopen access services, services
the user.
sciously thinks about:
that allow anonymous calls to
be made to access the data. The
1. Shared data, this is data that a user adds with
other service offerings will require that the applicaa goal of sharing the data. Examples of this on
tion accessing the data identifies itself in a unique
the Windows Live Platform would be Spaces
way. It is entirely possible that the same service will
photos, blog posts, Silverlight streaming media,
provide both anonymous access and identified acand Virtual Earth collections.
cess. The anonymous access would contain meth2. Private data, this is data a user places online
ods to read public facing data, whereas the identiso they can access it from other machines but
fied service method would allow private data and
they dont want to share. Examples on the
public data to be read and written.
Windows Live Platform would be Contacts
in Messenger or Hotmail, Favorites, Virtual
If the service offered requires that you identify your
Earth collections, and calendar.
application with an application identifier, you will
need to obtain an application ID (or AppID) from
You should be aware that some data stored in a
the Windows Live Microsoft Service Manager at
Windows Live Service might be considered public
whereas other data in the same service could be private. In the list of examples above you can see that
There are two distinct
Virtual Earth collections are both in the shared and
types of data that users have
in the private data sets. A user might want to share
a favorite coastal drive but not the collection of
stored online and it is
locations of companies they are interviewing with
important to understand the
for a new job. As a developer building applications
on these platforms your application potentially will
difference between shared data
have access to data that a user doesnt want shared.
and private data.
You need to consider very carefully how your application will work with this data.

www.code-magazine.com

12.02.2008 23:49:24 Uhr

http://msm.live.com/APP. Here you can register your


site for an application identifier. You should remember this identifier is unique to your application not
to you as a developer or to your company. For each
application that you build to access these services
you will need a new AppID.

1. A Delegation token, this token allows your


application to access the service offered. This
token has a short lifespan, usually a matter of
hours, but defined by the policy configuration
of the target resource provider.
2. A Refresh token, this is used to get a fresh delegation token when you need to access the
service again at a later date. This token will
expire when the user whose authority you are
delegating decides.
3. The Service Offers with expiration dates, a
collection of services that the user has granted
your application to access. Along with each
service offered will be an expiration date indicating when your application access will
expire.
4. An identifier of the user, typically this will be
an ID known as the CID.

Once you have an AppID, your application can


use this ID to contact the resource provider. The
resource providers are the different Windows Live
services that support this mechanism of delegated
authentication. The number of data sources will expand throughout 2008.

The User Owns Their Data


The number one rule is that the user always owns
their data. Your application must never redistribute
its copy of the user data without consent from that
user. This is important. Any application that breaks
the users trust or the Windows Live terms of usage
(http://dev.live.com/terms/) can have its AppID revoked. Users will decide the length of time your application can continue to access their data. Within
this timeframe your application can request the user
data over the wire as often as it is needed.

Permissions Granted
Once you have your AppID you will need to build a
handler page to receive a token known as a consent
token. This consent token will be sent to your application from Microsoft once a user has consented
to allow delegated authentication to your application. A consent token contains 4 important pieces
of information:
Persist the
Consent Token &
Owner Handle

Once you have built a page


to receive this token, you will
need to add a link from your
Windows Live delegated
application to the Microsoft
authentication is a technology that
consent page. When your application makes a call to the
allows a user to delegate authority
consent page, it needs to pass in
to a particular application for a set
the address of the return page
of resources.
you built, the address of the privacy policy statement for your
site, your AppID, and a list of
the services you would like to
access. It is good practice to provide the user with
an explanation before taking them to the consent
screen. The user can then decide whether to grant
permission for your application to these services and
the length of time each service can be accessed.
Once you have a consent token, you can use the
delegation token to make server calls from your
Web server to the service, typically by passing the
delegation token in the HTTP Authentication header of your request. The delegation token will expire

(dependenton Resource)

Link to Consent Screen

Returns Consent Token (HTTP(s))

Third
party.com

Send Refresh Token

Get Delegation Token

Send request & Delegation Token

Data

Live ID
Delegation
Service

Delegation
Token
Expiresafter
short time span.

Resource
Provider
(e.g. Live Contacts)

ow

se
s

(e.g. Spaces)

(e.g. Storage)

Br

End
User

www.code-magazine.com

CoDe_FocusLive.indd 47

(e.g. Calendar)

Figure 1: Data flow in delegated authentication.

Windows Live Delegated APIs

47

12.02.2008 23:49:24 Uhr

in a short time frame, so your application may need


to use the refresh token to request a new delegation
token. Figure 1 shows the data flow in the delegated authentication process.
If your application knows about a user, for example
you use the Live ID Web authentication model to
manage logged in users, then you probably want
to store the consent token against the user ID. The
best approach for this would be to create a new data
table in your application database to maintain the refresh token and services (with expiraoffered
tion dates) for each user.

If the service
requires that you identify your
application with an
application identifier,
you will need to obtain an
application ID from the Windows
Live Microsoft Service Manager

One more thing that you


should take into consideration
is that the expiration dates you
have stored for a user may no
longer be valid. At any time a
user can change the permissions they have granted to applications. This means that the
expiration dates should be used
as a guide for your application to determine if you
need to present the consent screen to the user again
and request a new consent token. If the user has revoked the permission for your application to access
their data, your application will receive an unauthorized access response. Your application needs to
gracefully handle an unauthorized access response;
your application could reroute the user to the consent screen, but it would be smarter to indicate to
the user why they are being asked for permission
again.

Everything as an Atom
The Atom Publishing Protocol (or AtomPub as
its often called) defines a simple protocol for performing CRUD (Create, Read, Update, and Delete)
operations on data over HTTP. Over the coming
months, most of the Windows Live Services will
provide offerings that conform to the AtomPub
standards. This is a fantastic move towards standardization of the Windows Live Services APIs.
In the last few years the APIs emerging from the
various Windows Live Services have been varied
and numerous. Each product group within Microsoft created their own API set, some were REST
based, some were SOAP, others were WebDav.
Standardizing on a single technology to access the
Windows Live Services will make our lives as developers easier.

48

Windows Live Delegated APIs

CoDe_FocusLive.indd 48

2. Well defined architectural patterns will be defined to guide application development.


3. Tools will emerge to automate some of the
code generation (see next section).

ADO.NET Data Services (aka Astoria)


At the MIX07 conference in Las Vegas, a new technology codenamed Astoria was announced. Astoria
has since been named ADO.NET Data Services and
is currently available as a download as a pre-release
(CTP) for Visual Studio 2008 users in the ASP.NET
3.5 Extensions pack.
The ADO.NET Data Services consists of libraries for creating and consuming data services over
HTTP. These ADO.NET Data Services can present
CRUD operations, which can be invoked through
the use of the HTTP verbs (GET, PUT, POST, DELETE). Does this sound familiar yet?
ADO.NET Data Services are designed to work with
standard formats such as JSON and AtomPub. This
is really lucky for developers who want to use the
new Windows Live AtomPub services!
However, there is more goodness to be harvested
from the ADO.NET Data Services, as they provide
a mechanism for modeling the data into objects.
These objects are instances of entities and you can
use the ADO.NET Data Service to represent the
data as entities, and also the relationships between
the entities, as defined in the service schemas.
For developers consuming services, this means
that they can interact with Window Live AtomPub
services in terms of .NET objects that can be queried, modified, and sent back to the service. This
is a great, natural way of interacting with services
from the .NET environment. Since it is all AtomPub
under the covers, openness and interoperability are
not compromised.
As a related note, developers wanting to create
services that follow the same HTTP interface pattern as Windows Live AtomPub services can use
ADO.NET Data Services on the server to easily
do that.

Microsoft, Do It for Me

The new AtomPub services will be available for access through the delegated authentication mechanism described in the previous section. Combining these two technologies to create a well defined
mechanism for accessing, authenticating, and working with the Windows Live Services has the following implications:

By providing the Windows Live Service offerings


in the AtomPub open standard, Microsoft has enabled all developers to access the same services in a
uniform way. As an ASP.NET developer, you might
not care about those other programmers but having
a well defined and open standard way of accessing the data benefits you as well. In an ASP.NET
server-side development world, much of the code
needed to access these AtomPub services can be in
a template and reused.

1. Applications can reuse the authentication


code across multiple services.

The ADO.NET Data Services provides this templating technology. An ASP.NET AJAX library abstracts

www.code-magazine.com

12.02.2008 23:49:25 Uhr

all the nasty details of how to make the HTTP calls.


This leaves you to focus on how you want to manipulate the data in your application. All you need
to do in your ASP.NET AJAX code is create an instance of a Sys.Data.DataService class, passing the
URI of the service into the constructor:

want to perform, you call the executeActions method on the ActionSequence object and the batched
operation requests will be made.

var liveService =
new Sys.Data.DataService("xxxxxxx.live.com");

The Windows Live Photos API allows a third party


site to request delegated authentication from a user.
Once the user has granted authentication privileges
to a site, the code on that site can make requests
to read and write photos associated with that users Live ID, these are the same photos that are displayed on Windows Live Spaces.

Once you have an instance of the DataService class,


you can perform various operations on the data using the following methods:

Query, retrieve data from the service.


Insert, create new data records on the service.
Update, change data that already exists.
Remove, delete data.

Photos Example

The code in Listing 1 provides an example of how


the ADO.NET Data Services can be used to call the
Windows Live Photos API. You can see that, by encapsulating the hard work of accessing the service,

Remember that not all services will allow all of


these actions; your application might not have the
correct authorization or the services might not support the operation at all.
Each of these methods will create an instant request over the wire to carry out the operation. If
you would like your application to batch operations
together you can use the createActionSequence
method on the DataService object. ActionSequence
is a class that contains a collection of operations
to perform on the service. Once you have created
the ActionSequence and added the operations you

Standardizing on
a single technology to access
the Windows Live Services
will make our lives as
developers easier.

Listing 1: Using ADO.NET Data Services to get photos.


class LivePhotosSimpleClient
{
static void Main(string[] args)
{
LivePhotos photoSvc = new
LivePhotos("http://sitename/folder/AtomLivePhotos");

where a.ID == 371


from p in a.Photos
select p;
Photo last = null;
foreach (Photo p in photos)
{
Console.WriteLine("{0}:\t{1}", p.ID, p.Title);
last = p;
}

// list all albums


foreach (Album a in photoSvc.Albums)
{
Console.WriteLine("{0}\t(photos: {1})", a.Name,
a.Photos == null ? 0 : a.Photos.Count);
}

if (last != null)
{
photoSvc.LoadProperty(last, "PhotoBytes");
Console.WriteLine("Loaded picture of type '{0}'.
Launching in explorer...", last.PhotoMimeType);
string le = Path.GetTempFileName();
File.WriteAllBytes(le, last.PhotoBytes);
System.Diagnostics.Process.Start(le);
}

Album album;
// single album by key w/URL
album =
photoSvc.CreateQuery<Album>("/Albums(434)").Single();
Console.WriteLine(album.Name);

// create an album
Album myPics = new Album();
myPics.ID = 987;
myPics.Name = "Mix08";
photoSvc.AddObject("Albums", myPics);
photoSvc.SaveChanges();
Console.WriteLine("Created, Album ID " + myPics.ID);

// single album by key w/LINQ


album = (from a in photoSvc.Albums
where a.ID == 434
select a).Single();
Console.WriteLine(album.Name);
// photos is album 371, LINQ style
var photos = from a in photoSvc.Albums

www.code-magazine.com

CoDe_FocusLive.indd 49

}
}

Windows Live Delegated APIs

49

12.02.2008 23:49:25 Uhr

the Windows Live Photos API can be addressed as


if it was a local set of .NET objects.
The code in Listing 2 shows the details of how the
supporting classes can be created to provide this
extra layer of encapsulation. The LivePhotos class
does the heavy listing, and most of that is done by
simply deriving from the WebDataContext class.

Conclusion

The ADO.NET Data


Services provides
this template.

you provide a downgraded experience? Will you


block that user from your site? Will you provide
an equally rich experience? As always, one set of
solutions creates its own new set of challenges for
us to address.
Whatever solutions you decide for your applications, you can be sure the technologies discussed
in this article are starting to open the doors of accessibility to a large number of Web developers that
have previously found the Windows Live APIs too
diverse and complex.

Writing an article like this before the technology


is released presents some challenges but it also allows me to help you gain insight into how new
technologies will impact the way we work in the
near future. As more Windows Live Services start
to support the AtomPUB format you (with the help
of the ADO.NET Data Services) will be able to access the huge quantity of resources, personal data
and relationships between people. All of this adds
up to a far deeper level of connection between the
online applications we build. With the caveat that
only the data a user actually wants to expose will
be available to our Web applications. This is going
to become a new important consideration for you
to handle in your code. How will your application
behave if a user denies access to a set of data? Will

Dr. Neil

Listing 2: Supporting classes for photos sample.


using
using
using
using
using
using

System;
System.IO;
System.Collections.Generic;
System.Linq;
Microsoft.Data.WebClient;
System.Xml.Linq;

: base(url)
{
this.DataNamespace = "http://dev.live.com/photos";
this.SendingRequest += new EventHandler
<SendingRequestEventArgs>(SendingRequestHandler);
this.ReadingEntity += new EventHandler
<ReadingWritingEntityEventArgs>(ReadingEntityHandler);

public class Album


{
public Album()
{
this.Photos = new List<Photo>();
}

}
void ReadingEntityHandler(object sender,
ReadingWritingEntityEventArgs e)
{
if (e.Entity is Photo)
{
((Photo)e.Entity).Title = e.Data.Element(atomns +
"title").Value;
}
}

public int ID { get; set; }


public string Name { get; set; }
public List<Photo> Photos { get; set; }
}
[MediaEntry("PhotoBytes")]
public class Photo
{
public int ID { get; set; }
public string Version { get; set; }
public string Title { get; set; }
[MimeTypeProperty("PhotoMimeType")]
public byte[] PhotoBytes { get; set; }
public string PhotoMimeType { get; set; }
}
public class LivePhotos : WebDataContext
{
private readonly XNamespace atomns =
"http://www.w3.org/2005/Atom";

void SendingRequestHandler(object sender,


SendingRequestEventArgs e)
{
e.Request.Proxy = new System.Net.WebProxy(new
Uri("http://127.0.0.1:8888"));
Console.WriteLine(" --> " +
e.Request.RequestUri.ToString());
}
public IQueryable<Album> Albums
{
get { return this.CreateQuery<Album>("/Albums"); }
}
}

public LivePhotos(string url)

50

Windows Live Delegated APIs

CoDe_FocusLive.indd 50

www.code-magazine.com

12.02.2008 23:49:25 Uhr

CoDe_FocusLive.indd 51

12.02.2008 23:49:25 Uhr

ONLINE QUICK ID 0804082

Light Up the Web


Microsoft Silverlight
Streaming by Windows Live
Rob Blackwell
rob.blackwell@aws.net
Rob Blackwell is R&D Director
at Active Web Solutions
http://www.aws.net.
He is a Microsoft Most Valuable
Professional (MVP) for Virtual
Earth.
He occasionally has something
interesting to say on his blog at
http://www.robblackwell.org.uk.

Microsoft Silverlight Streaming by Windows Live is a free


streaming and application hosting service for delivering rich
interactive applications (RIAs) over the Web.
In this article Ill show you how to get started with Silverlight and how to
upload your applications and rich media to the Silverlight Streaming Service.
n summer 2007, Microsoft released version 1.0 of
directed to an installation process. The runtime is
Silverlight, a revolutionary way to build rich insurprisingly small (less than 2 MB) and is quick and
teractive experiences on the Web. Silverlight is a
painless to install.
cross-platform,
cross-browser
plug-in that extends the browsIll start with a simple Silverlight
Fast Facts
ers Document Object Model
Hello World demonstration.
(DOM) with vector graphics
Silverlight Streaming by
Using XAML, define a Canvas
and multimedia features. Based
Windows Live is a free service
that includes a TextBlock with
on XML Application Mark-up
that gives you up to
the Hello World text and
Language (XAML), the same
4 GB of storage and up to
save this file as Hello.xaml (Litechnique used in the Windows
one million minutes of video
sting 1).
Presentation Foundation (WPF),
streaming at 700 Kbps.
Silverlight can be scripted with
Silverlight supports a range
Create an HTML page to host
JavaScript and can work within
the Silverlight control; call it
AJAX-enabled Web pages.
of video formats including
Default.html (Listing 2).
high definition (HD) and
Silverlight provides a consistent
(SMPTE) VC-1.
You must also provide two Javauser experience with Firefox and
Script files. Silverlight.js is part
Safari on the Mac and Firefox
of the Silverlight SDK and CreateSilverlight.js is
and Internet Explorer on Windows. Even Linux users
shown in Listing 3. CreateSilverlight is the code
can run Silverlight using Novels open-source Moonresponsible for instantiating the Silverlight control
light code.
with your XAML.
In fact, youre not locked into the Microsoft platform
You should now have four files: default.htm, Helat allits just as easy to deliver Silverlight experiences
lo.xaml, CreateSilverlight.js, and Silverlight.js.
from PHP sites on Apache/Linux as it is from ASP.
Launching default.htm in a browser runs the apNET sites on a Windows Server.
plication (Figure 1).

Hello World in Silverlight


You need to install the Silverlight 1.0 runtime for your
browser. The first time you visit a Silverlight enabled
site like http://www.microsoft.com/silverlight, you'll be
Listing 1: Hello.xaml.
<Canvas xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.
microsoft.com/winfx/2006/xaml">
<TextBlock FontFamily="Times New Roman"
FontSize="70"
FontStyle="Italic"
Foreground="Green"
Text="Hello World" />
</Canvas>

52

Light Up the WebMicrosoft Silverlight Streaming by Windows Live

CoDe_FocusLive.indd 52

Silverlight Streaming
Microsoft has a software and service strategy
and this is where the Silverlight Streaming by
Windows Live service comes indevelopers can
deploy their Silverlight applications and rich media in the cloud, leveraging Microsofts high
performance, high availability content distribution network.
While the product is in pre-release, storage
and delivery is free up to 4 GB, with outbound
streaming up to 700 Kbps. After release, developers will have continued use of the service with
up to 1 million minutes of free video streaming at
700 Kpbs per site per month.

www.code-magazine.com

12.02.2008 23:49:27 Uhr

Figure 1: Running the Silverlight Hello World application.

You can sign up for a free Silverlight streaming account at http://silverlight.live.com. You need a Windows Live ID to get started or you can create a new
Windows Live ID for free.

Uploading
Now move your Hello World sample to the Silverlight Streaming Service.
First create a manifest.xml file, which describes the
constituent parts of your Silverlight Streaming application:
Figure 2: Uploading the application to Silverlight Streaming.
<SilverlightApp>
<version>1.0</version>
<source>Hello.xaml</source>
</SilverlightApp>

For this simple example, you no longer need the default.html or JavaScript files. You just need to create
a Hello.zip file that contains manifest.xml and Hello.
xaml.
On Windows, multiple select the files, right-click
and select Send To Compressed (zipped) folder

Light Up the Web

Its just as easy to


deliver Silverlight experiences
from PHP sites on Apache/Linux as
it is from ASP.NET
sites on a Windows Server.

For more information about


Silverlight see http://www.
microsoft.com/silverlight/

or buy Laurence Moroneys book


Introducing Microsoft Silverlight
1.0 published by Microsoft Press.
To sign up for a free Silverlight
Streaming service go to
http://silverlight.live.com

Listing 2: Default.htm.
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Hello World</title>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript" src="CreateSilverlight.js"></
script>

</head>
<body>
<div id="SilverlightPlugInHost">
<script type="text/javascript">
createSilverlight();
</script>
</div>
</body>
</html>

Listing 3: CreateSilverlight.js.
function createSilverlight()
{
Silverlight.createObjectEx({
source: 'Hello.xaml',
parentElement: document.getElementById
('SilverlightPlugInHost'),
id: 'SilverlightPlugIn',
properties: {
width: '400',
height: '400',
background:'#ffffff',

www.code-magazine.com

CoDe_FocusLive.indd 53

isWindowless: 'false',
version: '1.0'
},
events: {
onError: null,
onLoad: null
},
context: null
});
}

Light Up the WebMicrosoft Silverlight Streaming by Windows Live

53

12.02.2008 23:49:27 Uhr

Figure 5: Invoke your application directly within an IFRAME.

Click Launch Application Test Page (Figure 4).


You can also provide a link for others to run your
application using an IFRAME. The URL is of the
form:
http://silverlight.services.live.com/
invoke/accountId/appName/iframe.html

Where accountId is your Silverlight Streaming numeric account identifier and appName is the name
of your application (in this case Hello). You can
find out your accountId by clicking the Manage Account link. The IFRAME invoker redirects you to
an obfuscated URL as in Figure 5.
Figure 3: Having uploaded your application, test links and sample code are automatically created.

Expression Encoder
Hello World is a start, but what happened to the
rich multimedia I was talking about? One of the
easiest ways to get started with Silverlight video
and audio is using Expression Encoder.
You can download a Trial edition of Expression
Encoder from http://www.microsoft.com/expression.
Its simple and intuitive to use, but there is also a
short video tutorial available.
You can edit and encode digital video and audio,
add leaders, trailers, and watermarks and control
the quality and encoding of the output.
Figure 4: Click Launch Application Test Page to run your application.

Quick Applications
The Windows Live Quick
Applications are a great way to get
started with Silverlight Streaming
and Windows Live Services.
The Contoso Bicycle Club and
Contoso University samples both
include free, open source code
samples that make extensive use
of Silverlight Streaming.
http://dev.live.com/QuickApps

you can use any of the popular ZIP compression programs, but you need to make sure that the
manifest file appears in the top-level root of the
zip filezipping the parent directory is a common
error and will not work!
Log in to Silverlight Streaming at http://silverlight.live.com using your Windows Live ID and
click Manage Applications. Select Upload a Silverlight Application, specify a name (Hello)
and browse for your Hello.zip file. Click Upload
(Figure 2).
Depending on your connection speed, this may
take a while. If all goes well, you will be presented
with a page that allows you to test your application. You will also be given sample HTML and JavaScript that you can cut and paste into your own
Web site to run the application (Figure 3).

54

Light Up the WebMicrosoft Silverlight Streaming by Windows Live

CoDe_FocusLive.indd 54

There are a number of predefined Silverlight media player templates in the Job Output section of
the Output tab and these will create for you a full
Silverlight wrapper without any coding.
If you download and install the Silverlight Streaming
Publishing Plug-In for Expression Encoder, you
can publish a job output from Microsoft Expression Encoder directly to Silverlight Streaming using
the public API. Just provide your accountID and
Account Key and press Publish (Figure 6).

If you are serious about


designing rich user experiences
with Silverlight, you probably want
to use Expression Blend 2.

www.code-magazine.com

12.02.2008 23:49:28 Uhr

Expression Blend 2
If you are serious about designing professional,
rich user experiences with Silverlight, you probably want to use Expression Blend 2. This is a
full-featured Silverlight XAML authoring tool for
designers.
Using Expression Blend 2 December Preview,
you can create a new Silverlight 1.0 Site project,
and then interact with the design surface to lay
out your graphic design. In Split view, you can see
your design work and the corresponding XAML
(Figure 7).
You can also open the same site in Visual Studio,
allowing developers to attach functionality and
enabling efficient designer/developer interaction.

Notes
You can upload and manage your Silverlight applications programmatically using a simple REST API.
You can use Expression Encoder with a command
line interface allowing batch mode operation and
on-the-fly trans-coding.

Figure 6: Microsoft Expression Encoder can automatically generate Silverlight media players from
predefined templates.

You can split your application so that the XAML


is delivered from your own site, but pulls multimedia content from the Streaming Service. This
can be a useful technique to allow more flexible
scripting and avoid cross-domain issues.
The application in this article uses Silverlight 1.0,
but the streaming service will also work with the
Silverlight 1.1 pre-release and the forthcoming
Silverlight 2.0. This opens the possibility of programming in .NET as well as JavaScript.

Conclusion
Video-enabled Web applications have traditionally been expensive and difficult to host because of
their high bandwidth demands and requirements
for streaming and edge-cached networks.
Silverlight is more than a Flash replacementits
changing the way we build rich interactive applications on the Web. Just take a look around to see a
wide range of applications including video, games,
and advanced data visualization tools.

Figure 7: Microsoft Expression Blend 2 December Preview.

The Silverlight Streaming service is a great way


to distribute your Silverlight applications for free
using Microsofts high performance content distribution network powered by Windows Live.

Rob Blackwell

www.code-magazine.com

CoDe_FocusLive.indd 55

Light Up the WebMicrosoft Silverlight Streaming by Windows Live

55
12.02.2008 23:49:29 Uhr

ONLINE QUICK ID 0804092

Developing Plugins for


Windows Live Writer
Plugins for Windows Live Writer are simple to create and can
provide many extra features.
This article will show you how to start writing plugins for Windows Live Writer,
including how to get started, how to debug, and how to package the final plugin.

Sctt Lovegrove
scott@liveside.net
http://scottisafooldev.spaces.
live.com
Sctt is a Windows Live MVP
for Microsoft and is very
heavily involved with Windows
Live, not just with Windows
Live Writer. He is one of the
main writers for LiveSide.net, a
community Web site dedicated
to Windows Live and his main
area of blogging for LiveSide is
developing on Windows Live.
Sctt has written a number of
popular plugins for Windows
Live Writer and can often
be found in the Live Writer
Support forum, for both
general support and the
developer forums.

efore you can begin writing a plugin for WinWriting Your Plugin
dows Live Writer (http://writer.live.com/),
Open up Visual Studio and create a new Class Liyou need to understand what it is and what
brary project, giving it a meaningful name for your
it actually does. Windows Live Writer is a free
plugin. Rename the default class1.cs to plugin.cs (this
desktop blog authoring tool from Microsoft that
isnt essential, but will allow you to
allows you to write an entry
quickly see the main plugin class).
for your blog without having
Fast Facts
to be online and do it right
Windows Live Writer doesnt
Next you need to add the Windows
from your desktop. Live
Live Writer API reference: bring up
just support Microsofts
Writer doesnt just support
the Add Reference window, point
Microsofts own blogging
own Windows Live Spaces
to your Windows Live Writer insite (Windows Live Spaces),
blogging platform,
stall folder (typically C:\Program
it supports a multitude of
it supports a number of
Files\Windows Live\Writer\), and
different blog engines: basidifferent and popular blog
then select WindowsLive.Writer.
cally any that support the
engines, such as Wordpress
API.dll. As a best practice for this
MetaWeblog API or Atom
or Community Server.
reference, set the property of Copy
Publishing Protocol. This list
Local to be false for this reference
includes Wordpress, Com(this will stop older versions of the
munity Server, LiveJournal,
API DLL being copied into the Live Writer Plugins
and Blogger. You can write your blog entry in
folder). Open plugin.cs and include the following usthe style of your own blog as well because Live
ing statement:
Writer downloads your blog style and uses it as
a template.

using WindowsLive.Writer.Api;

Whether youre someone just starting out with


their first blog, or a seasoned pro, Windows Live
Writer makes the blogging experience that much
better. And the features that dont come with the
program can come in the form of plugins that add
extra extensibility and improve the blogging experience even more.

Your Development Environment


Pre-requisites
Live Writer plugins are written in .NET, but while
you can use .NET 1.1, it is recommended to use
.NET 2.0. You will need Visual Studio 2005 or
above installedthis can be any version of Visual Studio 2005 or 2008 (http://msdn.microsoft.
com/vstudio), including the free Express Editions
of Visual Studio (http://www.microsoft.com/express/). You will also need to download Windows
Live Writer (http://writer.live.com/) as this has
the required API DLL on which the plugins are
based.
As plugins are developed in .NET, you can use any
language that uses it, but for my examples, I will
be using C#.

56

Developing Plugins for Windows Live Writer

CoDe_FocusLive.indd 56

You also need to add a reference to the Windows


Forms namespace, so add System.Windows.Forms
as a reference and also include the following:
using System.Windows.Forms;

Now you can add the Plugins attributes: these tell


Live Writer about who made the plugin, the link to
the developers Web site, the description, whether
the plugin has options, and the location of the image
to be used as the plugins icon within the Live Writer UI. These details go in just after the namespace
(before the main class).
The code for this is as follows:
[WriterPlugin ("d39bba2b-9522-49b1-8731-61030ccd6c95",
"My First Plugin",
Description = "This is my rst plugin",
HasEditableOptions = false,
Name = "My First Plugin",
PublisherUrl = "http://www.liveside.net")]
[InsertableContentSource ("Bold Text")]

Please note: The GUID is unique for each plugin


and you shouldnt reuse it in other plugins as this

www.code-magazine.com

12.02.2008 23:49:30 Uhr

Listing 1: Full code for a very basic Live Writer plugin.


using
using
using
using
using

System;
System.Collections.Generic;
System.Text;
WindowsLive.Writer.Api;
System.Windows.Forms;

namespace LiveWriterExample
{
[WriterPlugin("d2c99304-8648-4696-9ef1-6a82a2d070c9",
"LiveWriterExamplePlugin",
Description = "Makes highlighted text bold.",
HasEditableOptions = true,
ImagePath = "icon.gif",
Name = "Bold Text Plugin",
PublisherUrl = "http://www.liveside.net")]
[InsertableContentSource("Bold Text")]

can cause problems for Writer and may cause your


plugin not to be loaded.
To add an icon for your plugin, you should include
the code:
ImagePath = "icon.gif",

The value of this attribute must be the file name of


the icon you wish to use. Its location is relative to
where it is stored in your project. The image itself
must be 20 x 18 pixels in size.
After this, you need to create your plugin class. The
plugin class has to inherit from the Live Writer API
and there are two choices to inherit from: ContentSource and SmartContentSource. ContentSource
plugins are very basic plugins and will only insert
text into the blog entry. The plugin cannot change
that text again. SmartContentSource plugins can do
a lot more and will be covered later on in the article.
For this example, I am going to inherit just from the
ContentSource interface:
public class LiveWriterExamplePlugin : ContentSource

Then you need to include how the plugin will insert


the text. There are three different types:
CreateContent (from the Insert menu).
CreateContentFromUrl (when pasting a URL
into the blog entry area or from a Blog This
action).
CreateContentFromLiveClipboard (using the
LiveClipboard, although this method isnt
widely used as there isnt much LiveClipboard
content out there due to documentation).

While the examples


given in this article are C#,
the Live Writer API is .NET,
so youre not limited
to just C#.

www.code-magazine.com

CoDe_FocusLive.indd 57

public class LiveWriterExamplePlugin : ContentSource


{
public override DialogResult CreateContent
(IWin32Window dialogOwner, ref string content)
{
// If nothing is highlighted, content will be empty.
// If this is the case, the plugin does nothing.
if (!string.IsNullOrEmpty(content))
content = string.Format("<b>{0}</b>", content);
return DialogResult.OK;
}
}
}

CreateContent is the most commonly used method,


although there are examples where the FromUrl
method has been used. The plugin code overrides all
of these methods and they are not mutually exclusive; you can have more than one type in a plugin.

Override CreateContent Method


You can see that there is a string reference of content.
There are two things of note about this reference:
1. The initial value of content is whatever may
have been highlighted in the editing window.
If no text was highlighted, then content will be
empty, if you had text highlighted, then the full
HTML code will be what content equals.
2. Whatever content is equal to, that is what will
be put back into the blog entry. This must include any HTML formatting that might be required for the plugins functionality.
Remove the base code that is put inthis is just a
placeholder. To start off with, for this first example,
just return DialogResult.OK. This first part will just
be a simple plugin to make the highlighted text bold,
so the code for the CreateContent method is simply:
public override DialogResult CreateContent
(IWin32Window dialogOwner,
ref string content)
{
if (!string.IsNullOrEmpty(content))
content =
string.Format("<b>{0}</b>", content);
return DialogResult.OK;
}

Using this code, the plugin will take in whatever


text was highlighted and the bold HTML tags to either end of that content. Listing 1 shows just how
simple the code can be for a Live Writer plugin.

Compiling and Debugging


There are several little tricks to know about compiling and debugging your plugins for Live Writer as

Developing Plugins for Windows Live Writer

57

12.02.2008 23:49:30 Uhr

Figure 1: What you need to get the plugin to copy to the plugins folder.

Figure 2: What you need to debug your plugin.

they are DLL files and so cant be run on their own.


The two main tricks are for copying the built DLL
to Live Writers plugin directory and how to start
Live Writer so that you can debug your plugin.
Figure 1 shows the command needed for copying
the built plugin to the Live Writer plugin directory,
the command being:
XCOPY /D /Y /R "$(TargetPath)" "C:\Program Files\
Windows Live\Writer\Plugins\"

Note: If your Program Files folder is in a different


location to the Windows default, you will need to
change this for the way in which your system is configured.
Alternatively, you can simply set the output folder
of the project to point to your Live Writer Plugins
folder.

Useful Windows Live


Writer Links
There are many places you
can find information on Live
Writer. Here are some of my
recommended sites for both
general Live Writer information
and developing for Live Writer.
Live Writer blog: http://
windowslivewriter.spaces.live.
com
Joe Chengs blog: http://jcheng.
wordpress.com
MSDN Developer forum:
http://forums.microsoft.
com/MSDN/ShowForum.
aspx?ForumID=994&SiteID=1
Live Writer Support Forum:
http://groups.msn.com/
WindowsLiveWriter

58

Figure 2 shows you the setting needed to be able to


debug your plugin. You must start Windows Live
Writer as an external application in order to debug
your plugin. This will only work if you have done
what is in Figure 1, otherwise the plugin wont have
been copied to the plugin directory and Writer wont
pick it up.
Once you have these two settings configured in
Visual Studio, you can press F5 as you would normally, which will then build your project, copy it to
the plugin directory, and then load Windows Live
Writer with your plugin in debug mode.
Now you are in debug mode, Figure 3, Figure 4, and
Figure 5 will show the stages of using the plugin. In
Figure 3 you have your text as it was typed in normal
font style. In Figure 4 you see the text is highlighted so that the plugin will pick up that text and use
it. Figure 5 shows the results of clicking the plugin
name from the Insert section of Writer.

Developing Plugins for Windows Live Writer

CoDe_FocusLive.indd 58

Using Forms
Windows Forms can be an integral part of your plugin, so its important to know how to call them
correctly from your plugin code. Forms can control
exactly what you want the user to put into their blog
entry. This can range from putting in video URLs,
selecting an emoticon from a range of different
emoticons, or even searching for a book from Amazon; you can use Forms in a multitude of different
ways.
You call the Form from within the CreateContent
method like so:
public override DialogResult CreateContent
(IWin32Window dialogOwner,
ref string content)
{
using (frmMain form = new frmMain())
{
DialogResult result = form.ShowDialog();
if (result == DialogResult.OK)
content = form.NewContent;
return result;
}
}

In this snippet of code I have a simple Form with a


property called NewContent, which will give me the
new content value I want to have inserted into the
blog entry. Usually the final code to be put in the
plugin will be a property of the Form.
Its important to note that in the code for your Accept button in your Form, you have to put this.
DialogResult = DialogResult.OK; so that when the
Form closes the If condition checking for that result
is actually met.

www.code-magazine.com

12.02.2008 23:49:30 Uhr

Figure 3: Some sample text to be made bold.

Figure 4: The highlighted text.

Using Settings
Settings, like Forms, can be an integral part of your
plugin if you would like the user to be able to set defaults for the plugin. Typically this would be done by
the user going to the Options area of Live Writer, selecting the plugin, and then choosing the Options button as shown in Figure 6.
To start with, Live Writer has to be told that your plugin has an options Form, which is done by making
sure you set HasEditableOptions=true in the Plugin
Attributes. Next you have to create a Settings class, as
this makes it easier to access the settings.
The Settings class also has to use WindowsLive.Writer.Api, as you need to pass it an IProperties object to
read/write the settings to. The constructor of your settings class should look like the following:
IProperties m_properties;
public PluginSettings(IProperties properties)
{
m_properties = properties;
}

Figure 5: Having used the plugin the highlighted text is now bold.

Note that I have a global variable for this class of


m_properties, this is for calling that IProperties in
the class Properties.
The Live Writer API understands five types of setting
types: String, Int, Float, Bool, and Decimal. They all
have their own Get and Set methods (GetString(),
SetString(), etc.) and these are part of the IProperties class. So a simple property for a setting that gets
saved using the Live Writer APIs will look like this:
public bool DefaultBoldOption
{
get { return m_properties.GetBoolean
("DEFAULTBOLD", true); }
set { m_properties.SetBoolean
("DEFAULTBOLD", value); }
}

www.code-magazine.com

CoDe_FocusLive.indd 59

Figure 6: How your plugins options are accessed in Live Writer.

Developing Plugins for Windows Live Writer

59

12.02.2008 23:49:31 Uhr

Each Get method requires an attribute name (in this


case DEFAULTBOLD) and a default value, so if its
the plugins first time being used it has something to
fall back on. Each Set method requires the attribute
name, like the Get method, and that then just sets the
attribute using the value passed. You will need to do
this for all settings you wish your plugin to have.
Once you are happy with your Settings class, you
need to initialize the settings from within the plugin
code. Back in the original plugin class, add a global
variable:

Back to the original plugin class, you now need to


override the EditOptions method to call your Options Form:
public override void EditOptions
(IWin32Window dialogOwner)
{
PluginSettings settings =
new PluginSettings(this.Options);
frmOptions op =
new frmOptions(settings);
op.ShowDialog();
}

PluginSettings m_defaultsettings;

You then need to assign some PluginSettings to


those default settings, so you need to override the
Initialize() method:

Figure 7: How the Options Form


looks for this sample plugin.

public override void Initialize


(IProperties pluginOptions)
{
base.Initialize(pluginOptions);
m_defaultsettings =
new PluginSettings(pluginOptions);
}

Having the base.Initialize(pluginOptions) tells


Writer to get the plugin settings from the registry for
this particular plugin and put them into an IProperties class, which you then pass to the PluginSettings class that you created so you can read/write
to them.
Now you have that done, you need to create your
Options Form. For this example, I created a Form
that looks like Figure 7. You will need to pass the
PluginSettings object to the Form itself:
PluginSettings m_settings;
public frmOptions(PluginSettings settings)
{
InitializeComponent();
m_settings = settings;
// This sets the check box to be
// whatever the default option was
chBoldOption.Checked =
m_settings.DefaultBoldOption;
}

The Save button will have the following action for


its Click event:
private void btnSave_Click
(object sender, EventArgs e)
{
// Sets the option to whatever
// the check box is currently at
m_settings.DefaultBoldOption =
chBoldOption.Checked;
this.Close();
}

This example only has one setting, but the principle


is the same for however many settings your plugin
has.

60

Developing Plugins for Windows Live Writer

CoDe_FocusLive.indd 60

All thats left to do now is apply that setting to what


the plugin actually does, so in the CreateContent
code, you need to change it to the following:
using (frmMain form = new frmMain())
{
DialogResult result = form.ShowDialog();
if (result == DialogResult.OK)
{
content = form.NewContent;
if (m_defaultsettings.DefaultBoldOption)
{
content =
string.Format("<b>{0}</b>",
content);
}
}
return result;
}

ContentSource plugins
are very basic plugins and will only
insert text into the blog entry.
You can edit SmartContentSource
plugins content again
at a later time.
SmartContentSource Plugins
SmartContentSource plugins have a lot more about
them than basic ContentSource plugins. The biggest
difference about the two types is that ContentSource
plugins insert HTML code into the blog entry and
this cannot be changed or edited using the plugin at
a later time. SmartContentSource plugins store as
much information about what code is inserted as the
developer wants it to, which allows the user to open
that blog entry in Writer at a later time and edit that
bit of their blog entry using the plugin without having
to go through the whole process again.

Planning Whats Needed


With SmartContentSource plugins, its often best
to plan out what you want internally for your

www.code-magazine.com

12.02.2008 23:49:32 Uhr

Listing 2: This is the code for the PluginSettings class in the SmartContentSource plugin.
using
using
using
using

return m_properties.GetString(PLACEHOLDER, "");

System;
System.Collections.Generic;
System.Text;
WindowsLive.Writer.Api;

}
set
{
m_properties.SetString(PLACEHOLDER, value);

namespace EditPublish
{
public class PluginSettings
{
IProperties m_properties;
private const string PLACEHOLDER = "PLACEHOLDER";
private const string ACTUALCODE = "ACTUALCODE";

}
}
public string FinalText
{
get
{
return m_properties.GetString(ACTUALCODE, "");
}
set
{
m_properties.SetString(ACTUALCODE, value);
}
}

public PluginSettings(IProperties properties)


{
m_properties = properties;
}
public string PlaceHolder
{
get
{

plugin, like settings and which bits of the content


you would like the end user to be able to edit if required. Knowing what parts you want them to edit
at a later date will help you determine what settings
you need for the plugin. These settings are held
within the IProperties property of the ISmartContent object, which gets passed to the plugin from
Live Writer.
You will also want to work out where you would
like the end user to edit the content, whether its a
Form similar to the original Form they used or its
done from the sidebar of Writer.
Listing 2 shows the code used in the example plugins PluginSettings class.
To write a SmartContentSource plugin, you must
inherit from SmartContentSource, rather than ContentSource:
public class HiddenText : SmartContentSource

Override CreateContent Method


Like ContentSource plugins, you need to override
the CreateContent method, but this time its slightly
different:
public override DialogResult CreateContent
(IWin32Window dialogOwner,
ISmartContent newContent)
{
PluginSettings settings =
new PluginSettings(newContent.Properties);
using (frmMain main = new frmMain(settings))
{
DialogResult result = main.ShowDialog();
return result;
}
}

www.code-magazine.com

CoDe_FocusLive.indd 61

}
}

This time, Writer does not pass you a string reference,


which means whatever is highlighted in the editor
gets ignored. Instead youre given an ISmartContent
object. ISmartContent objects contain everything
about an instance of a plugins usage, which includes
an IProperties property (as used when including settings). However, those properties are for that ISmartContent object and only that objectthey are not
global like you saw before.
From the code snippet, you can see that I have created a PluginSettings class, which takes in the IProperties property of the ISmartContent object; this then
gets passed to the Form, which makes it easier for the
Form to write the required settings to the PluginSettings class.

GeneratePublishHTML Method
In the main plugin class, there are three new methods that you can override: two of these are compulsory, the third is optional. The first of these is
the GeneratePublishHTML method, which is the
method where the HTML is what will be published
to your actual blog. This method is compulsory; you
have to have it there. This code snippet is a very
small example of what is required:
public override string GeneratePublishHtml
(ISmartContent content,
IPublishingContext publishingContext)
{
PluginSettings settings =
new PluginSettings(content.Properties);
return settings.FinalText;
}

In this snippet, the text that would actually be published comes from a setting that you would have
written to using the CreateContent method.
The IPublishingContext object that gets passed
holds information about the type of blog youre

Developing Plugins for Windows Live Writer

61

12.02.2008 23:49:33 Uhr

Listing 3: This is the code for the plugin class for the SmartContentSource plugin.
using System.Windows.Forms;
using WindowsLive.Writer.Api;

}
public override SmartContentEditor CreateEditor
(ISmartContentEditorSite editorSite)
{
return new ContextEditor();
}

namespace EditPublish
{
[WriterPlugin("18d43e01-4549-4fde-8ca6-c7b4b7385fac",
"Insert Placeholder",
PublisherUrl = "http://scottisafooldev.spaces.live.com",
Description =
"Lets you put in a placeholder for the editor, "+
"to be replaced with other text when published.",
ImagePath = "writer.png",
HasEditableOptions = false)]
[InsertableContentSource("Placeholder")]
public class HiddenText : SmartContentSource
{
public override DialogResult CreateContent
(IWin32Window dialogOwner,
ISmartContent newContent)
{
PluginSettings settings =
new PluginSettings(newContent.Properties);
using (frmMain main = new frmMain(settings))
{
DialogResult result = main.ShowDialog();
return result;
}

public override string GeneratePublishHtml


(ISmartContent content,
IPublishingContext publishingContext)
{
PluginSettings settings =
new PluginSettings(content.Properties);
return settings.FinalText;
}
public override string GenerateEditorHtml
(ISmartContent content,
IPublishingContext publishingContext)
{
PluginSettings settings =
new PluginSettings(content.Properties);
return settings.PlaceHolder;
}
}
}

writing to, which includes a GUID for the individual blog (this comes from Live Writer itself) and the Service Name, which is whatever
the current publishing service is (e.g., "Windows
Live Spaces", "LiveJournal", "WordPress.com",
etc.).

CreateEditor Method
This is the second compulsory method that you
need to override. This method creates the sidebar
that appears in Live Writer when a SmartContentSource object is selected in the Live Writer editor:
public override SmartContentEditor CreateEditor
(ISmartContentEditorSite editorSite)
{
return new ContextEditor();
}

This method is usually just as simple as that. The


ContextEditor class that I call in this snippet will be
explained later in the article.

GenerateEditorHTML
Sometimes in a plugin, what you want to display in
the blog entry isnt always something that you want
to appear in the editor of Live Writer, JavaScript
functions for example. So sometimes you might
need to have something else appear in the actual
Live Writer editing area. For this you need to override the GenerateEditorHTML method:

Figure 8: The sidebar in Live Writer appears on the right-hand side when a SmartContentSource is
selected.

62

Developing Plugins for Windows Live Writer

CoDe_FocusLive.indd 62

public override string GenerateEditorHtml


(ISmartContent content,
IPublishingContext publishingContext)
{
PluginSettings settings =
new PluginSettings(content.Properties);
return settings.PlaceHolder;
}

www.code-magazine.com

12.02.2008 23:49:33 Uhr

As you can see, you get passed the same objects as


the GeneratePublishHTML method, so you can use
the same information for putting your HTML code
into the editor.
This method is the optional method; your plugin
does not require it. If this isnt overridden, Live
Writer will simply use what is in the GeneratePublishHTML method.

Listing 3 shows the full code for the example plugins main class.

Using Forms
Using Forms is mostly the same as when doing a basic ContentSource plugin, the main difference being that instead of creating the final

Listing 4: The code for the main form in the SmartContentSource plugin.
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;

namespace EditPublish
{
public class frmMain : Form
{
PluginSettings m_settings;
public frmMain(PluginSettings settings)
{
m_settings = settings;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
m_settings.PlaceHolder = textBox1.Text;
}
else
{
MessageBox.Show("You need to set a placeholder",
"Big Fat Hairy Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
if (textBox2.Text != "")
{
m_settings.FinalText = textBox2.Text;
}
else
{
MessageBox.Show("Enter some text",
"Big Fat Hairy Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
this.DialogResult = DialogResult.OK;
this.Close();
}
/// <summary>
/// Required designer variable.
/// </summary>

www.code-magazine.com

CoDe_FocusLive.indd 63

private System.ComponentModel.IContainer components = null;


/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources
/// should be disposed; otherwise, false.</param>
protected override void Dispose
(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager
(typeof(frmMain));
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(13, 124);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(407, 48);
this.textBox1.TabIndex = 0;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(13, 203);
this.textBox2.Multiline = true;
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(407, 56);
this.textBox2.TabIndex = 1;
//
// label1

Developing Plugins for Windows Live Writer

63

12.02.2008 23:49:33 Uhr

Listing 4: Continued
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 105);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(168, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Text to appear in the Writer editor:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(13, 185);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(189, 13);
this.label2.TabIndex = 3;
this.label2.Text = "Text to appear in the actual blog entry:";
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)
(((System.Windows.Forms.AnchorStyles.Top |
System.Windows.Forms.AnchorStyles.Left) |
System.Windows.Forms.AnchorStyles.Right)));
this.label3.Location = new System.Drawing.Point(13, 9);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(407, 96);
this.label3.TabIndex = 4;
this.label3.Text = resources.GetString("label3.Text");
//
// button1
//
this.button1.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button1.Location = new System.Drawing.Point(264, 272);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 5;
this.button1.Text = "Insert";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button2.Location = new System.Drawing.Point(345, 272);

this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 6;
this.button2.Text = "Cancel";
this.button2.UseVisualStyleBackColor = true;
//
// frmMain
//
this.AcceptButton = this.button1;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.button2;
this.ClientSize = new System.Drawing.Size(432, 307);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "frmMain";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Insert Placeholder Plugin";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private
private
private
private
private
private
private
}
}

HTML and passing that back, you just save the settings into the PluginSettings class, which will then be
used in a later method in the plugins main class.

face, it needs to inherit from the SmartContentEditor interface (make sure youre using WindowsLive.Writer.API):

Listing 4 shows the full code for the main Form


used in this example plugin.

public partial class ContextEditor : SmartContentEditor

The Sidebar (ContextEditor)


When you select a SmartContentSource within
the Live Writer editor, the editor activates a sidebar on the right-hand side of the Live Writer window, as shown in Figure 8.
For this, you need to create a new User Control
to your plugin project. I call mine ContextEditor.
Now, rather than inherit the UserControl inter-

64

Developing Plugins for Windows Live Writer

CoDe_FocusLive.indd 64

System.Windows.Forms.TextBox textBox1;
System.Windows.Forms.TextBox textBox2;
System.Windows.Forms.Label label1;
System.Windows.Forms.Label label2;
System.Windows.Forms.Label label3;
System.Windows.Forms.Button button1;
System.Windows.Forms.Button button2;

The constructor for the editor has to be like the following or your plugin could end up with some strange
behavior:
PluginSettings m_settings;
ISmartContent m_content;
public ContextEditor()
{
InitializeComponent();
this.SelectedContentChanged +=
new EventHandler(
SelectedContentNowChanged);
}

www.code-magazine.com

12.02.2008 23:49:33 Uhr

Listing 5: The code for the ContextEditor in the SmartContentSource plugin.


using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Drawing;
System.Data;
System.Text;
System.Windows.Forms;
WindowsLive.Writer.Api;

namespace EditPublish
{
public class ContextEditor : SmartContentEditor
{
PluginSettings m_settings;
ISmartContent m_content;
public ContextEditor()
{
InitializeComponent();
this.SelectedContentChanged +=
new EventHandler(
SelectedContentNowChanged);
}
void SelectedContentNowChanged
(object sender, EventArgs e)
{
m_content = SelectedContent;
m_settings =
new PluginSettings(m_content.Properties);
textBox1.Text = m_settings.PlaceHolder;
textBox2.Text = m_settings.FinalText;
}
private void button1_Click
(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
m_settings.PlaceHolder = textBox1.Text;
}
else
{
MessageBox.Show("No placeholder",
"Big Fat Hairy Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
if (textBox2.Text != "")
{
m_settings.FinalText = textBox2.Text;
}
else
{
MessageBox.Show("No text",
"Big Fat Hairy Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
OnContentEdited();
}

www.code-magazine.com

CoDe_FocusLive.indd 65

/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources
/// should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(3, 91);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(178, 58);
this.textBox1.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(0, 73);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(168, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Text to appear in the Writer editor:";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(3, 182);
this.textBox2.Multiline = true;
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(178, 58);
this.textBox2.TabIndex = 4;
//
// label2

Developing Plugins for Windows Live Writer

65

12.02.2008 23:49:34 Uhr

Listing 5: Continued
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(0, 164);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(171, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Text to appear in actual blog entry:";
//
// button1
//
this.button1.Location = new System.Drawing.Point(3, 255);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 6;
this.button1.Text = "Apply";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)
(((System.Windows.Forms.AnchorStyles.Top | System.
Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label3.BackColor = System.Drawing.Color.White;
this.label3.Font = new System.Drawing.Font("Microsoft
Sans Serif", 14F, System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(0, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(190, 32);

this.label3.TabIndex = 7;
this.label3.Text = "Insert Placeholder";
//
// ContextEditor
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.label3);
this.Controls.Add(this.button1);
this.Controls.Add(this.label2);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox1);
this.Name = "ContextEditor";
this.Size = new System.Drawing.Size(190, 482);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private
private
private
private
private
private

System.Windows.Forms.TextBox textBox1;
System.Windows.Forms.Label label1;
System.Windows.Forms.TextBox textBox2;
System.Windows.Forms.Label label2;
System.Windows.Forms.Button button1;
System.Windows.Forms.Label label3;

}
}

Notice the EventHandler you have had to listen out


for. This is important as this is what detects that
you have selected a different instance of a SmartContentSource object (dont forget, your user could
have used your plugin to insert two separate objects
in their blog entry).

If the user makes a change to the content using the


sidebar, nothing will change in the editor until you
call the OnContentEdited() method. You can call
this from a single button after all changes or each
time anything is changed; it is up to you as the developer to decide when to update the editor.

The code for the EventHandler method is also important to get right:

Listing 5 shows you the code needed for the sample plugins ContextEditor.

void SelectedContentNowChanged
(object sender, EventArgs e)
{
m_content = SelectedContent;
m_settings =
new PluginSettings(m_content.Properties);
textBox1.Text = m_settings.PlaceHolder;
textBox2.Text = m_settings.FinalText;
}

Important: You must not use SelectedContent.


Properties if you wish to get the IProperties property of the ISmartContentthis will not work. This
is why I assign SelectedContent to a local variable,
and then use that local variable when passing the
IProperties object to the PluginSettings class.

Much Much More


If you look through the Live Writer APIs, you will
find so much more that you can do with your plugins, including an excellent screen-scraping method
that will take a screenshot of a given URL and return an image. I would highly recommend taking
a good look at the rest of the API documentation
on MSDN (http://msdn2.microsoft.com/en-us/library/
aa738852.aspx).
Sco
/ tt Lovegrove

As a best practice, you should also use this EventHandler method to either set the current settings
to what you have in your sidebar or call the method that applies these settings.

66

Developing Plugins for Windows Live Writer

CoDe_FocusLive.indd 66

www.code-magazine.com

12.02.2008 23:49:34 Uhr

ONLINE QUICK ID 0804122

Introduction to the Live


Search API
Have you ever wanted to implement search capabilities on your
own Web site but didnt want to implement the logic and deal
with issues such as storage and indexing?
The Live Search team now offers two different ways to utilize Search on your
site: using the Live Search Box or using the Windows Live Search API.

Bronwen Zande
f you arent familiar with Live Search, it is located at http://www.live.com. Figure 1 shows the
Live Search home page. In addition to a standard search service, Live Search offers searches in
various categories such as images, news, maps, and
more.

and non-commercial sites at no cost. The full business terms are located at http://dev.live.com.

The first thing you require when using the API is an


Application ID. You can register and manage your
Live Search Application IDs at
the Live Search Developer CenFast Facts
ter located at http://dev.live.
Live Search Web Service
com/search. Figure 2 shows the
allows for up to 25,000
Developer Center home page.

The Live Search Box allows a


user to harness the power of
Live Search without writing
any code. It provides a fast, cusqueries a day for
Once here, you may download
tomizable search for any Web
use in both commercial and
the SDK or Create and Manage
site. You can find details on
non-commercial sites
Application IDs. When creathow to get started with this opat no cost.
ing a new Application ID, give
tion at http://search.live.com/
your application a name and
siteowner. From this site, follow
make note of the assigned Application ID as you
the wizard and copy the HTML code provided into
will need to use it in your source code.
your site.
ne at
le onli s/wl
ic
t
r
This article focuses on the Live Search Web Service
a
e
ir
ocu
his ent agazine.com/f
and how it allows developers to create applications
Read t
-m
e
ww.cod
that return results from the Live Search Engine.
http://w

Bronwen@soulsolutions.com.au
+61 402 148 104
Bronwen Zande is a Director
of Soul Solutions, based in
Brisbane, Australia.
With over 10 years of software
development experience,
Bronwens primary focus
is Microsoft Live and .NET
development. She is a
Windows Live Services MVP
and part of the core team that
runs the ViaWindowsLive.com
community site for Windows
Live technologies.
When not working with
Windows Live, Bronwen helps
bring together GeekGirls
from around the globe at
http://www.geekgirlblogs.com.

Live Search Web Service


The Live Search Web Service is an Extensible
Markup Language (XML) service with a Simple
Object Access Protocol (SOAP) API that allows users to create a custom search engine that can query
for Web results, images, news, phonebook listings,
feeds, and meta tags. You should use this service
when you are a developer who is comfortable consuming Web Services and you want more programmatic control over what you are searching for and
how you want to display your results.
You can find the fully documented online SDK at
http://msdn2.microsoft.com/en-us/library/bb251794.
aspx. The documentation describes the requirements, class libraries for the Live Search Web Service, and the terms of use and contains sample code
demonstrating use of the Live Search Web Service.

Before You Start


One of the benefits of using the Live Search Web
Service is that the terms of use allow for up to
25,000 queries a day for use in both commercial

www.code-magazine.com

CoDe_FocusLive.indd 67

Figure 1:
Fi
1 Th
The Li
Live S
Search
h hhome page.

Introduction to the Live Search API

67

12.02.2008 23:49:34 Uhr

ONLINE QUICK ID 0804102

Getting Started with the


Windows Live Tools

Vikas Ahuja
Program Manager, Windows
Live Developer Platform,
Microsoft Corporation
With over ten years of
experience delivering IT
solutions, Vikas lives in
Redmond with his wife. He
previously worked with the
Microsoft.com Web site, held
different positions in quality
assurance, and is currently
handling program management
for the Windows Live
Developer Platform.

Windows Live Tools for Microsoft Visual Studio enables


developers to incorporate a set of Windows Live services into
their Web sites using Visual Studio and ASP.NET.
Using the Contacts ASP.NET Server Control, your users can easily share
their contacts between Windows Live and your Web site. With the
SilverlightStreamingMediaPlayer ASP.NET Server Control, you can show videos
on your Web site from your Silverlight Streaming account with just drag-anddrop. The IDLoginStatus and IDLoginView ASP.NET Server Controls provide
Windows Live ID authentication at your Web site for your users. Microsoft
released its second community technology preview (CTP) in December, 2007.
You can download this CTP from http://dev.live.com/tools.
hrough this CTP, Microsoft is releasing four
NET Windows Live Web Site project template in
ASP.NET Server Controls: Contacts, IDLothe File | New Web Site dialog box (Figure 1). Also,
ginStatus, IDLoginView,
you can find these controls listand
SilverlightStreamingMeed as Windows Live Tools in
Fast Facts
diaPlayer. To help you develop
the Toolbox.
Windows Live Tools brings a
Windows Live Web sites, Microsoft has created a project
set of Windows Live services
Creating Your First
template as well. This release
right into your Visual Studio
only works with Visual Studio
development environment.
Project with the
2008 and Visual Web DevelYou can start integrating
Windows Live Tools
oper 2008 Express Edition at
Windows Live Contacts,
this time.
Windows Live ID
To start your first project that
Authentication, and Silverlight
integrates Windows Live serInstallation of the Windows
vices, navigate to File | New
Live Tools is straightforward.
Streaming services
Web Site, and select the ASP.
After installation is complete,
into your Web site.
NET Windows Live Web
Visual Studio displays an ASP.
Site template. Fill out the details to proceed with project creation. Open the
Default.aspx Web page in designer mode by choosing View Designer from the context menu in the
Solution Explorer.

This article will drill down into each of the newly


introduced controls and what they offer for your
Web site.

Contacts

Figure 1: ASP.NET Windows Live Web Site template.

68

Getting Started with the Windows Live Tools

CoDe_FocusLive.indd 68

Have you ever wondered why you have to enter a


new shipping address for each Web site whenever
you buy a gift for a friend? What if you could share
the shipping address across multiple Web sites using a central address book? The Contacts control
is a solution that allows you to safely transfer your
contact information between Windows Live Contacts (a users single address book between Windows Live Messenger and Windows Live Hotmail)
and the shopping Web site. Also, the Contacts control can help a Web site build viral communication
channels where users can message one another the

www.code-magazine.com

12.02.2008 23:49:36 Uhr

context of the Web site. For example, a shopping


Web site can specify a promotion message that their
users can send one another from the Web site.
The Contacts control offers three different views
to best suit your needs: Tile, TileList, and List. In
Tile/TileList views, Web site users can start an IM
conversation or open an e-mail with a pre-defined
message/custom greeting from the Web site, such
as Lets discuss this topic. List view allows users
to select and share their Windows Live Contacts
across multiple Web sites and centralize address
book management in one place. Its an off-the-shelf
address book pre-filled with data for any Web site
on the Internet.
The user maintains control of the data and has the
authority to choose to share or not share their data
with your Web site.
Ill show you how easy it is to use Windows Live
Contacts in your Web site. Drag-and-drop the Contacts ASP.NET Server Control from the Toolbox
onto the Default.aspx Web page. The drag-anddrop operation adds the privacyPolicy.htm file to
your project (you can replace this file with your
own privacy policy statement). Run the Web site
by entering Ctrl+F5. Visual Studio, after compiling
the Web site, launches the browser and displays Default.aspx. You will need to sign in using your Windows Live ID. After you are signed-in, the Contacts
control renders your contacts from messenger and
Hotmail. Figure 2 shows the Contacts control with
its default settings.

Sharing Contacts Data


The Contacts control maintains secure data isolation between Windows Live Contacts and your Web
site.
The control fetches your users contacts data from
Windows Live servers via a secure HTTPS connection. The user selects the contacts that they want
to share with your Web site, initiates the sharing of
data, and reviews what data is being shared. Only
then is any data released to your Web site.
Another key aspect that requires special mention is
the privacy statement for your Web site. The Contacts control requires that you provide a privacy
statement URL. The Contacts control renders a
privacy statement URL to the user while transferring contact information to your Web site. In your
privacy statement, you must clearly state the usage
of the data being transferred. You can either discard this data after use or store it in your servers for
future usage. If you choose to store the data, you
should clearly state this in your privacy statement
and provide a means for the user to review or delete
the stored data.
To enable sharing contacts data for the shipping
address scenario as mentioned earlier, you would
need to:

www.code-magazine.com

CoDe_FocusLive.indd 69

Set the PrivacyStatementURL to a Web page/


link that describes the privacy statement for
your Web site.
Set the View property to List.
Set the DataDesired property to specify which
data elements need to be fetched from Windows Live Contacts.
Provide client/server-side event handlers to
receive the data and handle the shipping process for the purchased items.
Next, Ill show you how to modify the project
to allow users to share their contacts data on
Default.aspx. You can get the complete reference
to the data elements allowed for the DataDesired
property at http://dev.live.com/tools/contactsapi.
aspx. Set the following values for the DataDesired
property in the property grid for the Contacts control: firstname, lastname, personalstreet, personalcity, personalstate, personalcountry, and personalpostalcode.

Figure 2: The Contacts control


(TileList view).

Once data is transferred by the Contacts control,


you can process the data in the OnClientData or
OnServerData event handlers.
The event handler for OnClientData (in JavaScript)
can look like the following:

Figure 3: Alert message showing


contact details.

<script type="text/javascript">
function Contacts1_OnClientData(sender, args)
{
var s = args.contacts.length+ " records\r\n";
for (var i = 0; i < args.contacts.length; i++){
for (var j in args.contacts[i]){
s += j + ": " + args.contacts[i][j]+"\r\n";
}
s += "\r\n";
}
alert(s);
}
</script>

Once you execute this code, you will notice that


an alert comes up, which enumerates the data elements and their values (Figure 3). The OnClientData event handler receives the transferred contacts as an array of objects. Each object represents
one contact selected by the user for transfer. Each
contact object has data elements corresponding to
the DataDesired property. If a certain data element
does not exist for a contact, it will not be returned.

A key aspect to note


is that the user is in control
of their data.

You can also specify similar processing logic in


server-side code. The Contacts control offers a corresponding server-side event for processing data received from the transfer (Listing 1).

Getting Started with the Windows Live Tools

69

12.02.2008 23:49:37 Uhr

Writing Contacts Data

Listing 1: The OnServerData event handler.


protected void Contacts1_OnServerData(object sender,
ServerDataEventArgs e)
{
foreach (Microsoft.Live.ServerControls.Contact objContact in e.Contacts)
{
//Implement custom processing for the contacts received
CustomProcessingForContact(objContact.FirstName,
objContact.LastName,
objContact.PersonalStreet,
objContact.PersonalState,
objContact.PersonalPostalCode,
objContact.PersonalCountry);
}
}

The declaration for the Contacts control on the default.aspx Web page would look like:
<live:Contacts ID="Contacts1" runat="server"
DataDesired="rstname, lastname,
personalstreet, personalcity,
personalstate, personalcountry,
personalpostalcode"
Height="500px"
PrivacyStatementURL="~/privacyPolicy.htm"
View="List"
Width="250px"
OnClientData="Contacts1_OnClientData"
OnServerData="Contacts1_OnServerData" />

The Contacts control allows you to write into a users


address book. For example, a Web page may allow
users to transfer Contacts data from their Web site
to Windows Live Contacts. When modifications are
being attempted to a users address book, an alert is
raised notifying the user. Users are then required to
review the modification and approve. Once approved,
the modifications are transmitted to Windows Live
servers via a secure HTTPS connection. Again, the
user is in control of their data in this case as well.
For example, adding a contact to a signed-in users
address book is very simple. The Contacts control
provides the CreateContact method, which takes a
list of contacts (List<Contact>). The Microsoft.Live.
ServerControls namespace contains the definition
of the Contact class. The Contact class has member properties that represent a contacts data elements. A complete list of data elements is available at
http://dev.live.com/tools/contactsapi.aspx.
To demonstrate this, refer to Listing 2 and Listing 3.
Listing 2 shows Default.aspx and Listing 3 shows
Default.aspx.cs. Default.aspx has a Contacts control,
an update panel, a text box where users can input
e-mail for the contact to be added, and three button
controls: adding a contact, adding a list of contacts,
and deleting contacts.

Listing 2: Default.aspx.
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="Microsoft.Live.ServerControls"
Namespace="Microsoft.Live.ServerControls" TagPrex="live" %>
<html xmlns=http://www.w3.org/1999/xhtml
xmlns:devlive="http://dev.live.com">
<head runat="server">
<title>CoDe Magazine Article</title>
</head>
<body>
<form id="frmDemoArticle" runat="server">
<asp:ScriptManager ID="scmMgr" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
function Contacts1_OnClientData(sender, args)
{
var s = args.contacts.length+ " records\r\n";
for (var i = 0; i < args.contacts.length; i++){
for (var j in args.contacts[i]){
s += j + ": " + args.contacts[i][j]+"\r\n";
}
s += "\r\n";
}
alert(s);
}
function Contacts1_OnClientCommit(sender, args){
alert('Contacts1_OnClientCommit event signaled');
}
</script>
<div>
<live:Contacts ID="Contacts1" runat="server"
DataDesired="rstname, lastname, personalstreet,
personalcity, personalstate, personalcountry,
personalpostalcode"
Height="350px" Width="250px" View="List"

70

Getting Started with the Windows Live Tools

CoDe_FocusLive.indd 70

PrivacyStatementURL="~/privacyPolicy.htm"
OnClientData="Contacts1_OnClientData"
OnClientCommit="Contacts1_OnClientCommit"
OnServerData="Contacts1_OnServerData"
OnServerCommit="Contacts1_OnServerCommit" />
<br />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:TextBox ID="txtEmail" runat="server"
Height="26px" Width="160px">
</asp:TextBox>&nbsp;&nbsp;
<asp:Button ID="btnAdd" runat="server"
Height="26px" Text="Add Contact"
onclick="btnAdd_Click" />
<br /><br />
<asp:Button ID="btnAddList" runat="server"
Text="Add List of Contacts"
onclick="btnAddList_Click" />&nbsp; &nbsp;
<asp:Button ID="btnDeleteList" runat="server"
Text="Delete List of Contacts"
onclick="btnDeleteList_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd"
EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnAddList"
EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnDeleteList"
EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

www.code-magazine.com

12.02.2008 23:49:38 Uhr

Listing 3: Default.aspx.cs.
using
using
using
using
using
using
using
using
using
using
using
using
using
using

List<Contact> objContacts = new List<Contact>();


Contact objContact1 = new Contact();
objContact1.EmailPersonal = "devlivedemo_1@hotmail.com";
objContacts.Add(objContact1);

System;
System.Data;
System.Conguration;
System.Linq;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Web.UI.HtmlControls;
System.Xml.Linq;
Microsoft.Live.ServerControls;
System.Collections.Generic;
System.Diagnostics;

Contact objContact2 = new Contact();


objContact2.EmailPersonal = "devlivedemo_2@hotmail.com";
objContacts.Add(objContact2);
Contact objContact3 = new Contact();
objContact3.EmailPersonal = "devlivedemo_3@hotmail.com";
objContacts.Add(objContact3);
Contacts1.CreateContacts(objContacts);
Contacts1.CommitContacts();

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void Contacts1_OnServerData(object sender,


ServerDataEventArgs e)
{
foreach (Microsoft.Live.ServerControls.Contact objContact in
e.Contacts)
{
//Process the contacts received
}
}
//add contact to signed-in user's contacts
protected void btnAdd_Click(object sender, EventArgs e)
{
List<Contact> objContacts = new List<Contact>();
Contact objContact = new Contact();
objContact.EmailPersonal = txtEmail.ToString().Trim();
objContacts.Add(objContact);
Contacts1.CreateContacts(objContacts);
Contacts1.CommitContacts();
}
//add list of contacts to signed-in user's contacts
protected void btnAddList_Click(object sender, EventArgs e)
{

The event handler, btnAdd_Click (defined in


Listing 3), shows that it is very easy to add contacts
to a users contacts. You start with creating a Contact
objectset the data elements that you are interested
in, create a generic List of contacts, and then pass it
to the CreateContacts method. The Contacts control
can then either abort or commit the operation. The
following code snippet only shows how to set this
for e-mail; however, you can extend the code to set
whatever data elements your application desires:
//add contact to signed-in users' contacts
protected void btnAdd_Click(object sender,
EventArgs e)
{
List<Contact> objContacts = new
List<Contact>();
Contact objContact = new Contact();

www.code-magazine.com

CoDe_FocusLive.indd 71

//delete list of contacts from signed-in user's contacts


protected void btnDeleteList_Click(object sender, EventArgs e)
{
List<String> Emails = new List<string>();
Emails.Add("devlivedemo_1@hotmail.com");
Emails.Add("devlivedemo_1@hotmail.com");
Emails.Add("devlivedemo_1@hotmail.com");
Emails.Add("devlivedemo_1@hotmail.com");
Contacts1.DeleteContacts(Emails);
Contacts1.CommitContacts();
}
//OnServerCommit event handler
protected void Contacts1_OnServerCommit(object sender,
ServerCommitEventArgs e)
{
if (e.ServerCommitErrors.Count > 0)
{
foreach (ServerCommitError objError in
e.ServerCommitErrors)
{
Debug.WriteLine(objError.CommitError);
Debug.WriteLine(objError.Key);
Debug.WriteLine(objError.CommitActivity);
}
}
}
}

Registering Your
Application with
Windows Live ID

objContact.EmailPersonal =
txtEmail.ToString().Trim();
objContacts.Add(objContact);
Contacts1.CreateContacts(objContacts);
Contacts1.CommitContacts();
}

Listing 3 also has btnAddList_Click, which you use


to submit multiple contacts for addition. You can
submit a maximum of 30 contacts in one operation.
Use btnDeleteList_Click to perform batch deletions
of contacts. You will notice that you must call the
CommitContacts method after create or delete operations; otherwise, these operations wont be finalized.
btnDeleteList_Click also highlights how errors are reported back from create/delete operations. In btnDeleteList_Click, the code is attempting to delete four
contacts where the fourth contact was never added.
Once the CommitContacts method executes (after

Windows Live ID Web


Authentication requires no server
install; it simply needs you to
specify a return URL for your
Web site and encryption token
(application secret). Windows
Live ID provides you with an
application ID for your Web site.
You can use this application ID
and encryption token to identify
the Web site visitors when they
sign into your Web site. For more
details on provisioning your Web
site and getting an application ID,
please visit:
http://msdn2.microsoft.com/enus/library/bb676626.aspx

Getting Started with the Windows Live Tools

71

12.02.2008 23:49:38 Uhr

Figure 4: Client-side error reporting with the OnClientCommit event.

Microsoft Silverlight
Streaming Service
Microsoft Silverlight Streaming
Service by Windows Live offers
designers and Web developers
an easier and free solution for
hosting and streaming crossplatform, cross-browser media
experiences and rich interactive
applications (using Microsoft
Silverlight) that run on Windows
and Mac. To get a free Silverlight
Streaming service account,
please visit:
http://silverlight.live.com

DeleteContacts) and the user approves the operation, a delete request is posted to Windows Live servers. After the request completes, the OnClientCommit event is raised followed by the OnServerCommit
event. Figure 4 shows the event argument returned
on the client-side args, which reports an error for the
attempt to delete the nonexistent contact.
The Contacts control also offers other events for
sign-in/sign-out, error handling, and properties for
styling (text, color, height, and width). The reference for the Contacts control is available online at
http://dev.live.com/tools/contactsapi.aspx.

IDLoginStatus
IDLoginStatus provides Windows Live ID authentication, which can be used to identify visitors to
your Web site. IDLoginStatus provides a unique,
site-specific identifier for each Windows Live user.
This allows the Web site to personalize the experience for the visiting user.

Figure 5: IDLoginStatusyou
can get a new application ID from
within Visual Studio by clicking
Create new Application ID.

When a user clicks the Sign-in link, the IDLoginStatus control redirects to the sign-in Web page on
Windows Live servers (http://login.live.com) along
with an application ID. After the user enters their
credentials, the sign-in page redirects the user to the
page with the IDLoginStatus control.
To obtain an application ID for your Web site, you
need to register your application with the Windows
Live ID service. You can do so by visiting http://
msm.live.com/app (see sidebar: Registering Your
Application with Windows Live ID).
IDLoginStatus provides an easy workflow for developers within the Visual Studio development environment. After you drag-and-drop the IDLoginStatus control onto your Web page, you can get a
new application ID by clicking Create new Application ID from the IDLoginStatus tasks (Figure 5).
After you complete the registration of your application and close the form, the IDLoginStatus control
saves the application ID and application secret into
Web.Config and sets the ApplicationIDConfigKey
and ApplicationSecretConfigKey properties on the
IDLoginStatus control. The control adds wll_appid and wll_secret keys into the <appSettings> section of the Web.Config file. At run time, the control
checks the values of ApplicationIDConfigKey and

72

Getting Started with the Windows Live Tools

CoDe_FocusLive.indd 72

ApplicationSecretConfigKey properties and reads


the Web.Config keys.
The following snippet from Web.Config highlights
this:
<appSettings>
<add key="wll_appid" value="FF167FFE80FFF932" />
<add key="wll_secret" value="CoDeMagazine123" />
</appSettings>

The HTML declaration for IDLoginStatus looks


like the following:
<live:IDLoginStatus ID="IDLoginStatus1"
runat="server"
ApplicationIDCongKey="wll_appid"
ApplicationSecretCongKey="wll_secret" />

IDLoginStatus offers both client-side and server-side


events for sign-in/sign-out. IDLoginStatus also returns
AuthEventArgs, which contains the ApplicationUserID, TimeStamp (the time the user authenticated in
seconds measured from Jan 1, 1970 GMT), and ApplicationContext (a parameter to round trip your application state through the redirections to and from the
Windows Live servers). The ApplicationUserID is the
unique site-specific identifier for the signed-in user.

IDLoginView does
template switching and association
of Windows Live ID and ASP.NET
membership profiles.
If you are using ASP.NET membership, IDLoginStatus enables single-sign-on. You can set the AutomaticallyConvertAuthentication property to true.
When this property is set to true, the IDLoginStatus control verifies whether the current signed-in
user has previously associated with an ASP.NET
membership profile and automatically logs-in to
ASP.NET membership on existence of an association. Read more about this in IDLoginView.
You can find the complete reference for the IDLoginStatus control at http://dev.live.com/tools/idloginapi.aspx.

www.code-magazine.com

12.02.2008 23:49:38 Uhr

Listing 4: IDLoginView.aspx.
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="IDLoginView.aspx.cs" Inherits="IDLoginView" %>
<%@ Register Assembly="Microsoft.Live.ServerControls"
Namespace="Microsoft.Live.ServerControls"
TagPrex="live" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CoDe Magazine Article - IDLoginView</title>
</head>
<body>
<form id="frmIDLoginView" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<live:IDLoginStatus ID="IDLoginStatus1" runat="server" />
<br />
<live:IDLoginView ID="IDLoginView1" runat="server"
AutomaticallyAssociateAuthentication="True"
PromptOnAssociation="True">
<AnonymousTemplate>
<asp:Login ID="Login1" runat="server"></asp:Login>
<br />
This is anonymous template
</AnonymousTemplate>
<AssociatePromptTemplate>
Associate your user name for this Website
with your Windows Live ID?<br>
<asp:Button runat="server"
CommandName="associate_yes"
Text="Yes" Width="55px"

IDLoginView
The IDLoginView control extends ASP.NETs LoginView control. Where the LoginView control provides template switching based on a users logged-in
state in ASP.NET membership, IDLoginView provides switching based on a users logged-in state in
both ASP.NET membership and Windows Live ID.
IDLoginView adds three new templates in addition
to the two provided in the LoginView control:
AnonymousTemplate: Displayed to Web site
users who are not logged into the Web site (inherited from LoginView).

ID="IDLoginView1_livepromptyes">
</asp:Button>
<asp:Button runat="server"
CommandName="associate_no"
Text="No" Width="55px"
ID="IDLoginView1_livepromptno">
</asp:Button>
</AssociatePromptTemplate>
<LoggedInTemplate>
<asp:LoginStatus ID="LoginStatus1"
runat="server" />
This template is for ASP.NET logged in users
</LoggedInTemplate>
<LoggedInIDTemplate>
<asp:Login ID="Login1" runat="server">
</asp:Login><br />
This template is for Windows Live ID
signed in users
</LoggedInIDTemplate>
<LoggedInAllTemplate>
This template is for users logged in both
Windows Live ID and ASP.NET membership<br />
<asp:Button ID="btnRemove" runat="server"
Text="Remove Association"
onclick="btnRemove_Click" />
</LoggedInAllTemplate>
</live:IDLoginView>
</div>
</form>
</body>
</html>

LoggedInTemplate: Displayed to Web site


users who are logged into ASP.NET membership at the Web site (inherited from LoginView).
LoggedInIDTemplate: Displayed to Web site
users who are logged in with Windows Live ID
at the Web site.
LoggedInAllTemplate: Displayed to Web site
users who are logged into both ASP.NET
membership and Windows Live ID.
AssociatePromptTemplate: Displayed to Web
site users when they have logged in with both
ASP.NET membership and Windows Live
ID, but have not yet associated these two
identities.

Listing 5: IDLoginView.aspx.cs.
using
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections;
System.Conguration;
System.Data;
System.Linq;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.HtmlControls;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Xml.Linq;
Microsoft.Live.ServerControls;

www.code-magazine.com

CoDe_FocusLive.indd 73

public partial class IDLoginView : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
}
//Remove Association
protected void btnRemove_Click(object sender, EventArgs e)
{
AssociationManager.RemoveAssociation
(IDLoginStatus1.ApplicationUserID);
}
}

Getting Started with the Windows Live Tools

73

12.02.2008 23:49:39 Uhr

Figure 7: The SilverlightStreamingMediaPlayer control.

Not only does IDLoginView provide template


switching based on a users logged-in state, but it
also allows association of Windows Live ID and
ASP.NET membership identities. Based on your
choice, the AssociatePromptTemplate is presented
to the user asking whether they want to associate
their Windows Live ID and ASP.NET membership
for a single-sign-on experience.
Refer to Listing 4 (IDLoginView.aspx) and Listing 5
(IDLoginView.aspx.cs) for the following discussion.
After you drag and drop the IDLoginView control
onto your Web page, start by setting these two properties: AutomaticallyAssociateAuthentication and
PromptOnAssociation. Setting the AutomaticallyAssociateAuthentication property to true instructs
the IDLoginView control to associate ASP.NET
membership and Windows Live ID when the user is
logged in with both identities. IDLoginView calls AssociationManager.AssociateAuthentication passing
the ApplicationUserID (Windows Live IDs unique
identifier for the signed-in user at your Web site) and
the ASP.NET membership identity. If you chose to
set the PromptOnAssociation property to true, the
IDLoginView asks the user whether to associate their
Windows Live ID with their ASP.NET membership
before establishing an association (Figure 6).
If you havent yet, you need to launch the
ASP.NET Web Site Administration Tool from Website | ASP.NET Configuration. Please make sure
that you make the following changes:

74

You may be surprised to see that all of the template switching and association functionality can
be realized without you having to write a single
line of code.
When a Web site visitor signs-in to your Web page
using the IDLoginStatus control, IDLoginStatus
sets the webauth cookie, which contains the ApplicationUserID for the signed-in user. The IDLoginView detects the state change after the IDLoginStatus control sets this cookie. IDLoginView then
switches the template to the LoggedInIDTemplate
and renders the specified contents. You can provide the content applicable to users having Windows Live ID in this template. Then, if a user
signs-in to ASP.NET membership, IDLoginView
switches to the LoggedInAllTemplate. At this time,
if you had set the AutomaticallyAssociateAuthentication and PromptOnAssociation properties to
true, IDLoginView renders the AssociatePromptTemplate to the user. If the user chooses to associate the two identities, IDLoginStatus creates an
association between Windows Live ID and ASP.
NET membership.
The btnRemove_Click event handler (Listing 5)
shows how a developer can remove this association, if the user so chooses.

AssociationManager

Set Authentication type to From the Internet.


By default, this is not the case. You can access
this setting from the Security tab of ASP.NET
Web Site Administration, and then click Select the authentication type.
Set up a few users by choosing Create User.
This will create users for your Web site who
will be saved in the ASPNETDB.MDF database in the App_Data folder.

The AssociationManager allows a developer to


directly query, set, or remove associations for the
signed-in user. The Microsoft.Live.ServerControls
namespace contains this class. Include a using
statement for the Microsoft.Live.ServerControls
namespace in your program.

Having set up the users for the Web site, you can
test the template switching and association fea-

You can upload cool videos you created to your


Silverlight Streaming account (http://silverlight.

Getting Started with the Windows Live Tools

CoDe_FocusLive.indd 74

tures in IDLoginStatus and IDLoginView, as provided in Listing 4 and Listing 5.

SilverlightStreamingMediaPlayer

www.code-magazine.com

12.02.2008 23:49:39 Uhr

Figure 6: IDLoginView AssociatePromptTemplate (designer


view).

$nd("StreamingMediaPlayer1");
objSLSMPlayer.set_mediaSource("streaming:
/20709/VideoLibrary/Assets/Lake.wmv");
}
</script>

live.com) and play them on your Web site with


drag-and-drop.

Details about the underlying ASP.NET MediaPlayer are available at this link: http://quickstarts.asp.
net/3-5-extensions/silverlight/MediaPlayerControl.
aspx.

This control allows you to play your videos from


a Silverlight Streaming service account. It extends
the MediaPlayer control provided by the ASP.NET
3.5 Extensions Preview release.

Wrapping Up

Developers at design time can provide account


credentials for their Silverlight Streaming account
and choose the video that their Web page should
play. After you drag-and-drop this control onto
your Web page, you can specify the video to be
played through the Select Media File form. This
form is accessible through the controls tasks window or property grid (Figure 7). Developers dont
need to write code to make a connection to Silverlight Streaming servers and choose videos. All
this is encapsulated so that you can just specify the
credentials and choose a video.

I hope the above is helpful in getting you started


with the Windows Live Tools. I would love to hear
your feedback about Windows Live Tools and how
you are going to use it. You can leave your suggestions to improve the feature set or bugs you find
as you are using Windows Live Tools at http://dev.
live.com/tools.
Vikas Ahuja

After you choose the video you want to play, the


control saves this video URL in streaming:// format in the controls MediaSource property. Also,
it saves the Account and Key for your Silverlight Streaming account into Web.Configs <appSettings> section. The following snippet from
Web.Config highlights this. Ive used example values for the AccountID and AccountKey keys:
<appSettings>
<add key="AccountID" value="MyAccount" />
<add key="AccountKey" value="MyKey" />
</appSettings>

The controls declaration would look like the following snippet:


<live:SilverlightStreamingMediaPlayer
ID="SilverlightStreamingMediaPlayer1"
runat="server"
Height="240px"
Width="320px"
MediaSource="streaming:/20709/VideoLibrary
/Assets/Bear.wmv">
</live:SilverlightStreamingMediaPlayer>

At run time, the control converts streaming:// URLs


to HTTP URLs. You can also set the URL of the video from client-side JavaScript with the code snippet
belowyou need to hook this JavaScript function to
an action, say the click of a button:
<script type="text/javascript">
//set URL for Silverlight
//streaming media player
function SetMediaUrl()
{
var objSLSMPlayer =

www.code-magazine.com

CoDe_FocusLive.indd 75

Getting Started with the Windows Live Tools

75

12.02.2008 23:49:39 Uhr

ONLINE QUICK ID 0804112

Windows Live Admin Center

Jon Arking
Jonarking@hotmail.com
Jon Arking is an independent
systems architect, trainer, and
author working in the greater
Philadelphia region. He spends
his time consulting on large,
enterprise systems on both
Microsoft and non-Microsoft
platforms. His most recently
published work, Professional
Windows Live Programming
from Wrox Press, 2007, is
the definitive handbook for
developers looking to build
Live-powered applications and
understand the Windows Live
business life cycle. Jon lives
with his wife and children in
south Jersey where he also
consults regularly for the City
of Philadelphia.

76

Windows Live Admin Center

CoDe_FocusLive.indd 76

When developing with Windows Live services, you open your


application to a whole new world of software integration.
In this fascinating realm of mashup mania, developers can find tools for adding
maps, searches, video, chats, and even social networking services directly into
their applications and ultimately right into their users browsers. The benefit of
adding services like Virtual Earth and Silverlight Streaming are obviouscreating
dazzling content and facilitating rich user experiences. Yet services like these
are still limited to specific contexts within your program. They are perfectly
wonderful for beefing up the user experience in Web sites, but wouldnt it be
great if the folks at Microsoft provided a service that helps you administer user
accounts and customize services around your Web site? Well indeed they have,
and its name is Windows Live Admin Center (admincenter.live.com).
indows Live Admin Center (formerly known
is not only unique, but recognizable across all Liveas Custom Domains) is a service provided by
powered applications. Likewise, a Live ID account
Microsoft that allows users to create domainis a means of entry to other Live services. A single
specific Live ID accounts. Up until this point youve
Live ID account comes with all of the Windows Live
likely spent a lot of time reading
features, including a page on
about Live services that work
Live Spaces, an account on Live
Fast Facts
within your Web sites or WebExpo, search macros, personalThe latest version of Windows
enabled applications. Admin
ized alerts, a chat account, and
Live Admin Center is flush
Center marks a subtle shift from
lots of other tools and features of
these services, representing one
Live that compliment your onwith new features,
of the few features of Windows
line content.
including an enhanced SDK,
Live that works around your
support for e-mail optional
Still, Live ID has its limitations.
application. On the surface its
domains,
and the creation of
If your Web site requires users
purpose is simple: allow users to
up to 500 default
to have a Live ID to access your
create Live ID user names withmember accounts.
site the accounts arent entirely
in your sites URL. For example,
user friendly. They have the
if you are the owner of a domain
non-descriptive @hotmail.com
named coragi.com, you could
or @live.com domain suffix that prevents users from
register that domain name with Windows Live Adidentifying with your application. They have access
min Center and, through it, create Live ID accounts
to free e-mail, but of course the e-mail is branded as
with names such as BigJon@coragi.com or Sheila2388@
coragi.com. Once the domain is registered, WebmasHotmail, again preventing users from identifying with
ters have the ability to administer these accounts diyour service. And of course, there is the not-too-subrectly, adding names, removing users, and performing
tle separation of services that keeps a Webmaster at
basic account maintenance as they see fit.
arms length from account maintenance. Even though
you might be consuming Live ID and, with it, allowI know what youre thinkingso what?!! Most Webing people to log into your application, you have no
masters with only a moderate amount of experience
ability to administer the accounts themselves.
know how to create accounts like this on their own.
After all, most hosting services already provide the
Here is where Windows Live Admin Center shines.
administrative features and mail services needed to
Admin Center is a service that bridges those othercreate an almost limitless list of domain-specific acwise awkward disconnects between your application
counts. Who needs yet another service to do this for
and Windows Live, resulting in a powerful comproyou? At first, I thought the same thing. However I
mise that facilitates customization while allowing
soon learned that the power behind Windows Live
users to take full advantage of the Live ID model.
Admin Center lies not in the simple creation of acInstead of accounts with hotmail.com names, each
counts, but rather in the power that drives Windows
corresponds to whichever domain name you choose
Live ID and in the power of service integration and
to register. Instead of hosting your own mail services
site federation.
and authentication servers, Microsoft does it all for
you. Whats more, Live IDs created using Admin
Consider what a Live ID really is. It is a key that
Center arent subject to many of the expirations and
identifies a user to literally thousands of Live-powmaintenance rules that apply to a normal Live ID acered Web applications. Since Windows Live ID supcount. The accounts you create are yours to manage
ports a single sign-on model, each Live ID account
and control.

www.code-magazine.com

12.02.2008 23:49:40 Uhr

Figure 1: Enter your Domain Name or purchase a new one.

Figure 2: The Admin Center online administration page.

Online Registration and Account


Administration
The best way to familiarize oneself with Admin Center is to jump right in and register an account. The
administration site is located at http://admincenter.
live.com. First time users should begin by clicking the
Get started button located towards the bottom of
the page. This begins the wizard-like application that
helps guide users through the setup process. The first
thing youll need to have to begin using Admin Center is your own domain name. Thus, the first page
of the wizard allows you to either enter an existing
domain name (that you own) or select an option for
purchasing a new one (Figure 1). Managing a domain
name requires some understanding of registrars and
general Web concepts and falls outside of the scope
of this article. Microsoft has partnered with a handful
of public registrars, such as Melbourne IT and Register.com; however, developers should feel free to use
whatever registration service they prefer. If you click

www.code-magazine.com

CoDe_FocusLive.indd 77

the link labeled I need to purchase a domain youll


be given a choice of roughly four registration services
from which to choose (offered in English only, other
languages will not have this option), and then the
Admin Center registration process stops. Inevitably
youll be forwarded back to this initial page with a
valid domain name to continue.
In this example I have purchased the domain name
coragi.com, so I will enter that name into the text
field at the top of the page and click Continue.
Notice that I did not change the default mail setting
Set up Windows Live Hotmail for my domain. This
newer option that comes with later versions of Admin Center allows advanced Webmasters to forego
the automatic mail service that accompanies an Admin Center account. Since the e-mail that comes with
each account is a popular feature, lets leave this setting alone. The next few pages require users to sign
in with a valid Windows Live ID and to agree to the
terms of use. The Live ID you choose to associate

the power
behind Windows
Live Admin Center
lies not in the
simple creation
of accounts,
but rather in the
power that drives
Windows Live ID
and in the power of
service integration
and site federation.

Windows Live Admin Center

77

12.02.2008 23:49:41 Uhr

Figure 3: A Custom Address pointing to a specific location on maps.live.com.


with this account will be the same account youll use
when administering your accounts through the API.
Remember it because youll need it when sampling
the API. Be sure to read through each of the terms,
and then click the I Agree button to continue.
If this is the very first time you are logging in youll
likely see some warning messages indicating that your
account status is Pending DNS Configuration. Youll
need to go into your domain hosts administration
page (or wherever you keep your DNS records) and
add an MX DNS entry pointing to the MX address
listed with the status message. Once youve done that,
your Admin Center account should look like Figure 2.
There is a lot going on in this page. Headings like Administrator Status and Mail indicate the statuses of
the Admin Hotmail account and whether there is a
valid DNS entry for your Hotmail service.
In the upper left-hand side of the page youll find
a small navigation menu for accessing some of the
features of your account. Create a new member account by clicking the Member Accounts link, and
then clicking the +ADD button at the top of the
page. Enter the requested information. Remember
that each name you enter into the Account Name
field is appended with your domain name. Adding the
name Mike into your Add-Members page will create an account with a user name of Mike@coragi.com.
Each account you create is a valid Live ID account.
Experiment with them by going to other Windows
Live sites like Spaces.live.com and log in using the
new account name.
Adding and removing Live IDs from your domains is
one of a few cool features of Admin Center. If youre

78

Windows Live Admin Center

CoDe_FocusLive.indd 78

looking to take advantage of other services in the


Windows Live family but you dont want to give up
your own domain URLs, take a gander at the Custom Addresses section. This tool lets you map domain
friendly CNAME entries and subdomains to other
Live services such as Hotmail, Live Spaces, and Live
Maps. For example, say you want users to be able
to come to coragi.com and click a link that shows a
map of Philadelphia with a pushpin over 1500 Market Street. You want the link to read maps.coragi.
com, since its simple to remember, but you want
the user to be taken to Live maps directly. With Admin Center, its easy! Simply click the Custom Addresses link in the navigation menu, select maps
from the drop-down list, and then click the Add
button. In the subsequent pop-up window, enter the
CNAME entry that you would like your site to use (in
this case maps), and then enter the address as you
would have typed it into maps.live.com. Youll need
to go into the host site or where you administer DNS
entries and add a CNAME entry for maps.coragi.com
(should point to go.domains.live.com). Now enter
maps.coragi.com into a browser and a Windows
Live map appears with a focus right over Center City,
Philadelphia, as shown in Figure 3. You can use this
feature to create domain-friendly URLs that point to
individual Spaces pages, Search Macros, a collective
e-mail account, and more.
One more feature worth talking about is the co-branding link. Admin Center is all about integrating your
sites content seamlessly with the various services and
tools inherent to the Windows Live family. By utilizing Admin Centers e-mail services, you provide your
users with an almost limitless amount of mail space
while never having to worry about hosting or e-mail

www.code-magazine.com

12.02.2008 23:49:42 Uhr

account management. Of course, it might help if the


e-mail page users logged into bore some signet of your
site, am I right? Click the co-branding link and thats
precisely what youll get. Most basic users will be able
to see a link for customizing the header. This option
allows you to upload a small Web site image or logo
that will be visible on the headers of all co-brandable
headers in Windows Live. As Microsoft expands this
capability, youll be able to subtly layer in other elements of your Web sites look and feel to maintain the
semblance of a single-site user experience.
There are other features in Admin Center available
for Webmasters to customize. Some of these features
allow you to open your membership model to users
interested in creating their own Live IDs (see Sidebar
on Open Membership). Other features may only be
available to certain types of Admin Center memberships. Everything I have covered so far pertains to
those features available to any Web site interested in
federating with Windows Live Services. However,
other offer types within the Admin Center framework that cater to different interest groups may provide different features in addition to those discussed.
Live@edu is one such special offer, allowing schools
to outsource their e-mail and online services for
students and alumni. Interested parties should visit
http://www.liveatedu.com. Other offer types such as
Live@net allow network operators to offer enhanced
e-mail services to their broadband subscribers. In
fact, the Web site you just registered, coragi.com,
technically falls into the offer known as CommunityBuilder (see www.communitybuilder.com). My point
being that Admin Center comes in a few different
flavors, some of which might offer more features
and tools youll want to explore. For more information on special interest offers and features go to
http://partner.live.com.

Admin Center SDK


The online administrative site that accompanies your
account is nice to have, but falls short of delivering the
automation you really need to integrate Admin Center
accounts into your Web site. After all, if you want users
to register with your Web site and automatically receive
a sleek, new Live ID with your domain name in it, you
need a way of adding users and managing accounts
within your code. For this, youll need to access the Admin Center SDK. The Admin Center SDK comes with
API documentation and samples that you can download by clicking the Download the full SDK link at
http://msdn2.microsoft.com/en-us/library/bb259721.aspx
Since the scope of this article is necessarily limited,
refer to these documents for the full definitions of all
available API. The Admin Center API exposes a single
Web service endpoint containing a flush list of public methods available for all sorts of member service
administration. You can use some methods, such as
CreateMember and GetMemberNameState, for direct integration with your registration process. Other
methods, such as GetMemberCount and GetDomainInfo, are available for more comprehensive administration of your domains and accounts. The trick to

www.code-magazine.com

CoDe_FocusLive.indd 79

really understanding Admin Center is knowing which


method to use and when.
Consider a typical registration scenario. Youve got a
great new Web site that delivers triathlon information
and lets competitors enter their personal stats. Each
competitor needs to register with your Web site in order to access their personal stats and enter in data from
each of their races. Youd like to furnish users with Live
IDs so that they can also chat with one another, create
blogs and connect them with their Spaces accounts,
and maybe even post some flyers on Live Expo. Youve
already got all of the pieces you need to integrate Live
ID into your authentication process, but you need to
be able to automatically create Admin Center user
names each time the user clicks that register button
on your site. So the registration process really requires
three distinct steps in order to integrate:
1. Create an administrative session for authorized
management of accounts.
2. Check to see if an account name already exists.
3. If available, add a new account to your Admin
Center domain and activate the Live ID.
Thats a good start for this article. Youll dig in by setting up a small sample application that demonstrates
these tasks. In this example youll be using a Console application written in C# and created in Visual
Studio .NET 2008. Of course in the real world youll
more likely be using server code in an ASP.NET application; however, a console piece should prove sufficient for this article.

Setting up the Visual Studio .NET Console


Application

You can use


the Custom
Addresses feature
to create domainfriendly URLs that
point to individual
Spaces pages,
search macros,
a collective e-mail
account,
and more.

Youll need to first create a Visual Studio .NET Console Application project and create a reference to the
Admin Center Web service endpoint.
1.
2.

Open Visual Studio .NET 2008 and select the


New Project option from the File menu.
Find the option for creating a C# Console Application and enter a project name of MyAdminCenterSample, as shown in Figure 4. For

Figure 4: Select a C# Console application in


Visual Studio .NET 2008.

Windows Live Admin Center

79

12.02.2008 23:49:42 Uhr

Figure 5: Adding a Web reference to the Admin Center Web service endpoint.

Open Membership
One of the more interesting
features of Windows Live Admin
Center is the Open Membership
option. Using a prepared HTML
module that Webmasters can
customize in the Admin Center
administration pages, users can
create their own e-mail accounts
inside of your domain. Like all
Admin Center member accounts,
each name becomes its own Live
ID. That means that a user not
only gets an e-mail account with
your domain name, but also a
Live Spaces account, a Live Expo
account, and much more.
Open Membership is an ideal
way to generate more traffic to
your domain and each name
created helps to promote your
Web site. Whats more, Open
Membership takes a lot of the
hassle of account management
away from Webmasters and
places it squarely on the
shoulders of Windows Live.
However, the Open Membership
option may not be suitable for
Web sites that require a specific
registration process or those that
need to approve users before
their accounts can be activated.
Therefore, administrators can
choose to enable or disable this
option as they see fit.

80

Windows Live Admin Center

CoDe_FocusLive.indd 80

3.

4.

5.

6.

the purposes of simplicity, leave all other default settings alone.


Once loaded, add a Web reference to your application by right-clicking the References link
in the Solution Explorer and selecting Add
Web Reference from the pop-up menu.
Enter the following URL in the Web Reference
URL field: https://domains.live.com/service/managedomain2.asmx.
Then enter AdminCenterAPI as the Web reference name. Your screen should look something like Figure 5. NOTE: The Admin Center
service endpoint uses SSL encryption to ensure
that the user data sent to the service cannot be
read during transport. Click OK in response to
the digital certificate pop-up to continue loading the service endpoint.
Since you will be making calls to Web classes
not immediately available within the default applications scope, add the following using statements to the top of the Program.cs page:

using System.IO;
using System.Net;

ministrative session. This works similarly to the way


you might log into a secure administrative site, only
instead of creating a valid session cookie, youll be
creating an authorized ticket. This process uses three
API methods: GetLoginUrl, GetLoginDataTemplate,
and VerifyAuthData. The GetLoginUrl call simply
returns the specific Web address to which your application needs to post in order to create an authorized ticket. The address might change over time and
can be different for each application used; however,
by calling this method specifically, your code is abstracted from any unpredictable address changes.
GetLoginDataTemplate returns the string used specifically by the ticket-generating URL for passing in
your administrating Live ID account name and its
corresponding password. Note that the format for
this string is quite specific. You must make a call to
the GetLoginDataTemplate method each time you
authenticate to be sure youre conforming to the
expected standards. Once the template is obtained,
youll need to replace the Name and Password
placeholders with your own credentials. Youll then
pass this new string to the URL provided in the GetLoginUrl method using standard C# Web classes to
receive your valid session ticket. You then verify that
no errors occurred by passing the ticket to the VerifyAuthData method and, if valid, save the valid ticket
and associate it with your Web reference.

The Admin Center API exposes


a single Web service endpoint
containing a flush list of public
methods available for all sorts of
member service administration.

This may seem like a lot of work at first, but it becomes a no-brainer once you get used to it. In the
Program.cs file, add the following code directly below
your static void Main function:
private static string CreateAuthTicket()
{
}

Youll call this function from the Main method directly, isolating all of the requisite tasks for generating
the ticket from the Main functions code.

That should be enough to begin. Bear in mind that


everything you will be doing from here requires the
use of a fully registered, active Admin Center account.
While following along, assume that you can replace
any calls made to coragi.com or its supporting elements with your own account names and elements.

NOTE: Since I am trying to keep this sample simple


and easy to follow, I am going to place all code in
the Program.cs file. A stronger example would likely
separate most of the code into one or more classes.

Creating an Administrative Session

Since youll need a class-wide reference to the Admin


Center Web reference, go ahead and add the following declaration directly above the static void Main
method:

Before you can create user accounts and view domain information, youll need to create a valid ad-

static AdminCenterAPI.ManageDomain2 srvc;

www.code-magazine.com

12.02.2008 23:49:43 Uhr

Listing 1: Creating the Admin Center administrative session.


srvc = new MyAdminCenterSample.AdminCenterAPI.ManageDomain2();

srvcAuth.authorizationType = MyAdminCenterSample.AdminCenterAPI.
ManageDomain2AuthorizationType.PassportTicket;

string loginUrl = srvc.GetLoginUrl("[your Live ID here]");


srvcAuth.authorizationData = loginTicket;
string loginTemplate = srvc.GetLoginDataTemplate().
Replace("%NAME%", "[your Live ID here]").
Replace("%PASSWORD%", "[your password here]");

srvc.ManageDomain2AuthorizationValue = srvcAuth;
return loginTicket;

string loginTicket = PostWebData(loginUrl, loginTemplate);

if (srvc.VerifyAuthData(loginTicket))
{
AdminCenterAPI.ManageDomain2Authorization srvcAuth = new
AdminCenterAPI.ManageDomain2Authorization();

else
throw new ApplicationException("An error occurred while
attempting to create an authorization ticket");

Listing 2: Generic function for posting the loginTicket.


private static string PostWebData(string URL, string postContent)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] tmpBytes = encoding.GetBytes(postContent);

newStream.Write(tmpBytes, 0, tmpBytes.Length);
// Get the response
response = (HttpWebResponse)request.GetResponse();
// Return the result
string result =
new StreamReader(response.GetResponseStream()).
ReadToEnd();

request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "POST";
request.ContentLength = postContent.Length;
request.UserAgent = "Mozilla/4.0 (compatible;"+
"MSIE 6.0; Windows NT 5.2; .NET CLR 1.1.4322)";

newStream.Close();
return result;

Stream newStream = request.GetRequestStream();


request.AllowAutoRedirect = true;

Now youll need to add the code from Listing 1 to


the newly created CreateAuthTicket Method.
If you follow the code you should find that each step
reflects the process I just described. You first create
a Web object reference named srvc that gives access
to the Admin Center service endpoint. You then get
the login URL and store it in a local string variable
and get the login template as well. The code attempts
to replace the template placeholders with your own
account name and password, but youll need to enter
your own credentials where required. You then post
the data to the provided URL and verify that it is
valid. If valid, you create an instance of the ManageDomain2Authorization class, which is used by Admin
Center to hold the authenticated ticket and deliver
it to the Web reference endpoint. You set the appropriate type (see Admin Center documentation
about authentication types) and set the authentication value equal to your new ticket. Finally, you set
the Web references ManageDomain2AuthorizationValue property equal to the instance of ManageDomain2Authorization, which contains the valid ticket.
If you try and compile this code as is, youre going to get some errors. Thats because you havent
yet implemented the PostWebData method. This is
a standard C# method that accepts a URL and a
string template, posts the template to the URL, and
returns whatever might come back from said post.
Under the CreateAuthTicket method, add the C#
code from Listing 2.

www.code-magazine.com

CoDe_FocusLive.indd 81

Go ahead and compile the code now and everything should come through fine. Youre now ready
to start creating your user accounts.

Adding New User Accounts


Since youre creating a Console Application, it
might be best to provision some simple user I/O.
Add Listing 3 to the static void Main method.
Again, this seems like a lot of code, but a closer look
reveals this samples simplicity. The first few lines
writes out a welcome message to the user, waits for
them to click the Enter key to begin, and then obtains the authorization ticket using the method you
built in the last section. The sample then gives the
user a small menu of tasks from which to choose
and sets up an empty switch block to pass focus
to whichever function corresponds to the users
choice. The menu selection option is placed within
a large while loop, allowing the user to come back
and select other menu options once a previous selections task has been completed. This pattern allows you to create individual methods that wrap
your sample API calls without overlapping your applications control code.
Thinking back to your registration scenario, youll
want to tackle the Add a New User option first.
This method will require the use of two Admin Center API methods: GetMemberNameState and Create-

Windows Live Admin Center

81

12.02.2008 23:49:43 Uhr

Listing 3: Control code for the console interface.


Console.WriteLine("Welcome to your Admin Center" +
"API sample application. Press ENTER to begin...");

switch (response)
{
case "1":

Console.ReadLine();
break;
Console.WriteLine("Creating the"+
"authorization ticket...");

case "2":

Console.WriteLine();

break;
case "3":

string loginTicket = CreateAuthTicket();

break;

Console.WriteLine("Authentication completed.");

case "4":

bool blnContinue = true;

break;

while (blnContinue)
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();

case "5":
break;
case "6":

Console.WriteLine("Please select one" +


"of the following menu options and click Enter:");

break;
case "7":
blnContinue = false;
break;

Console.WriteLine();
Console.WriteLine("1. Add a New User");
Console.WriteLine("2. View Member List");
Console.WriteLine("3. Enumerate"+
" registered domains");
Console.WriteLine("4. Rename a Member");
Console.WriteLine("5. Reset Member Password");
Console.WriteLine("6. Delete a User");
Console.WriteLine("7. Exit");
string response = Console.ReadLine();

default:
Console.WriteLine("You have not"+
" entered a valid response.");
break;
}
}
}

Member. As discussed previously, a typical scenario


demands that a user enters a desired name, which
the system first checks for availability. If the name
is not available, the user is appropriately told so,
and then they are given the opportunity to try a different name. Upon finding an available user name,
the system can garner some additional account info
from the user and create the new account. Thus, the
GetMemberNameState method will be invoked each
time a user enters a new name and the CreateMember
method is called only when an available name has
been determined.

Replace the following code in the main switch block


for case 1:
case "1":
AddNewUser();
break;

Add Listing 4 to your class.


Similar to the code in the static void Main function, you begin with some simple text in the console
followed by the beginning of a while loop. You use
the loop to take the user back to the initial steps
in the event that the user provided an unavailable
name. Note that all of the code within the loop has
been enclosed with a Try block. There are a number
of different errors that can be thrown by Microsoft

82

Windows Live Admin Center

CoDe_FocusLive.indd 82

when attempting to make an API call. Since there is


no simple way to handle all of them gracefully, you
simply catch any exception when thrown, print the
contents of its message to the command line, and
then go back to the main menu.
You next present the user with the option of entering a user name they would like to register. They
MUST enter the name as the fully qualified domain
name. If a user wants to register the name Jake,
theyll need to enter Jake@[your domain]. Naturally you should feel free to tinker with the sample
code to append the name with your URL as you see
fit. Once entered, the system makes a call to GetMemberNameState, passing in the users desired name to
check for its availability. The return value from this
method is not a Boolean type as one might expect.
Rather, it is an Enumeration type with a value corresponding to the names specific state within Windows Live. Although this code is simply checking
for straight availability, users should keep in mind
that the GetMemberNameState function can actually
return one of five possible values:

ne at
le onli
e artic om/focus/wl
ir
t
n
e
.c
his
agazine
Read t
.code-m
w
w
/w
:/
http

www.code-magazine.com

12.02.2008 23:49:43 Uhr

Check dev.live.com for more information!

CoDe_FocusLive.indd 83

12.02.2008 23:49:43 Uhr

Have You Xiine It?

All You Can Read.


Digitally.
Experience the next generation
in digital reading FREE.
Go to www.xiine.com to read
CoDe Magazine and other
great publications.

CoDe_FocusLive.indd 84

12.02.2008 23:49:44 Uhr

S-ar putea să vă placă și