Click to Rate and Give Feedback
MSDN
MSDN Library
Collapse All/Expand All Collapse All
Windows Live
Sample Application: Display Photos and Albums

This sample application demonstrates how to create a simple ASP.NET Web site, and use the Windows Live Spaces Photos API to access a user's Photos account.

Create a New Project in Visual Studio
  1. From the File menu, click New, then click New Web Site.

  2. In the New Web Site dialog, select ASP.NET Web Site.

  3. Create a new Web Site named SPSample.

  4. Add a new Generic Handler named LoadImageHandler.ashx.

  5. Copy and paste the code from this topic into the respecive project files, overwriting all of the original contents.

  6. Right-click Default.aspx, and select Set As Start Page.

  7. Press CTRL+SHIFT+F, and search the entire solution for the following string: [domain authentication token]

  8. Replace the string with your domain authentication token.

  9. Press CTRL+SHIFT+F, and search the entire solution for the following string: [owner handle]

  10. Replace all occurrences of this string with your actual user handle (for example, someone@hotmail.com).

  11. Press F5 to build and run the project.

Note:
If you access the Internet through a proxy server, add the following code to the <configuration> section of the web.config file for the project:
<!--Bypass the proxy server on the request call.-->
<system.net>
   <defaultProxy>
      <proxy usesystemdefault="False" proxyaddress="[proxy URL]" bypassonlocal="True"/>
   </defaultProxy>
</system.net>

The source code for the complete application is shown below.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SPSample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html >
<head runat="server">
   <title>Untitled Page</title>
</head>
<body style="font-family: Tahoma">
   <form id="form1" runat="server">
   <div style="padding: 30px">
     <h1>Spaces Photo API Sample</h1>
     <p>This sample demonstrates how to:</p>
     <ul>
       <li>List the photo albums for an account.</li>
       <li>List the photos for an album.</li>
       <li>Display a photo.</li>
     </ul>
     <asp:Label ID="lblRootUrl" runat="server"></asp:Label><br />
     <asp:Label ID="lblResponse" runat="server"></asp:Label><br />
     <asp:Label ID="lblError" runat="server"></asp:Label>
   <table>  
       <tr>
         <td>       
         <asp:ListBox ID="photoAlbums" Width="259px" Height="100px" runat="server" 
            onselectedindexchanged="photoAlbums_SelectedIndexChanged" AutoPostBack="true"></asp:ListBox>     </td>
         <td>
            <asp:ListBox ID="photos" Width="259px" Height="100px" runat="server" 
              onselectedindexchanged="photos_SelectedIndexChanged" AutoPostBack="true"></asp:ListBox>
         </td> 
       </tr>
   </table>
   <asp:LinkButton ID="btnListAll" runat="server" Text="List All Photo Albums" 
            onclick="btnListAll_Click" /><br />
   <asp:Image ID="Image1" runat="server" />
   </div>
   </form>
   
</body>
</html>

Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.SessionState;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Text;

public partial class SPSample : System.Web.UI.Page
{
   string ownerHandle = "";
   string domainAuthToken = "";
   string strRoot = "";
   NameTable nt = new NameTable();
   XmlDocument xmld = new XmlDocument();
   XmlNamespaceManager xmlnsm = null;
   
   protected void Page_Load(object sender, EventArgs e)
   {
      // Paste Windows Live ID here.
      ownerHandle = "user@hotmail.com";
      
      // Paste in the domain authentication token.
      domainAuthToken = "[domain authentication token]";
      Session["OwnerHandle"] = ownerHandle;
      Session["DomainAuthToken"] = domainAuthToken;
      strRoot = "https://cumulus.services.live.com/" + ownerHandle + "/SpacesPhotos/";

      lblRootUrl.Text = strRoot;
      xmlnsm = new XmlNamespaceManager(nt);
      xmlnsm.AddNamespace("D", "DAV:");
      xmlnsm.AddNamespace("c", "http://storage.msn.com/DAV/");
   }

   protected void listAlbums()
   {
      string path = strRoot;      
      HttpWebRequest request = MakeRequest(path, "PROPFIND");
      request.Headers.Add("Depth", "1");
      try
      {
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         xmld.LoadXml((new StreamReader(response.GetResponseStream()).ReadToEnd()).ToString());
         response.Close();
      }
      catch (WebException ex)
      {
         //The parsing failed, display what happened.
         lblError.Text = ex.Message;
      }
      catch (Exception ex)
      {
         //The parsing failed, display what happened.
         lblError.Text = ex.Message;
      }

      photoAlbums.Items.Clear();

      if (null != xmld)
      {
         XmlNodeList xmlnl = xmld.SelectNodes("/D:multistatus/D:response/D:propstat/D:prop", xmlnsm);
         bool first = true;
         foreach (XmlNode xmlnode in xmlnl)
         {
            if (first)
            {
               // Ignore first item
               first = false;
               continue;
            }

            XmlNode href = xmlnode.SelectSingleNode("D:href", xmlnsm);
            XmlNode name = xmlnode.SelectSingleNode("D:displayname", xmlnsm);
            photoAlbums.Items.Add(new ListItem(name.LastChild.Value, href.LastChild.Value));
         }
      }

      if (0 != photoAlbums.Items.Count)
      {
         Session["PhotoAlbum"] = photoAlbums.Items[0].Value;
      }
      else
      {
         Session["PhotoAlbum"] = null;
      }
   }
   
   protected void photoAlbums_SelectedIndexChanged(object sender, EventArgs e)
   {
      string path = photoAlbums.Items[photoAlbums.SelectedIndex].Value;
      lblRootUrl.Text = path;
      Session["PhotoAlbum"] = path;
      HttpWebRequest request = MakeRequest(path, "PROPFIND");
      request.Headers.Add("Depth", "1");
      try
      {
         HttpWebResponse response = (HttpWebResponse)request.GetResponse();
         xmld.LoadXml((new StreamReader(response.GetResponseStream()).ReadToEnd()).ToString());
         response.Close();
      }
      catch (WebException ex)
      {
         //The parsing failed, so handle the error, or at least display what happened.
         lblError.Text = ex.Message;
      }
      catch (Exception ex)
      {
         //The parsing failed, so handle the error, or at least display what happened.
         lblError.Text = ex.Message;
      }

      photos.Items.Clear();

      if (null != xmld)
      {
         XmlNodeList xmlnl = xmld.SelectNodes("/D:multistatus/D:response/D:propstat/D:prop", xmlnsm);
         bool first = true;
         foreach (XmlNode xmlnode in xmlnl)
         {
            if (first)
            {
               // Ignore first item
               first = false;
               continue;
            }

            XmlNode href = xmlnode.SelectSingleNode("D:href", xmlnsm);
            XmlNode name = xmlnode.SelectSingleNode("D:displayname", xmlnsm);
            photos.Items.Add(new ListItem(name.LastChild.Value, href.LastChild.Value));
         }
      }
   }
   
   protected void photos_SelectedIndexChanged(object sender, EventArgs e)
   {
      string path = photos.Items[photos.SelectedIndex].Value;
      lblRootUrl.Text = path;
      Image1.ImageUrl = "./LoadImageHandler.ashx?" + "url=" + photos.Items[photos.SelectedIndex].Value + "&oh=" + ownerHandle;
      Image1.Visible = true;
   }
   
   protected void btnListAll_Click(object sender, EventArgs e)
   {
      listAlbums();
   }
   
   private HttpWebRequest MakeRequest(string reqPath, string method)
   {
         HttpWebRequest request = (HttpWebRequest)WebRequest.Create(reqPath);
         request.UserAgent = "Microsoft Windows Live Photo Demo";
         request.Method = method;
         request.Headers.Add("Authorization", "DomainAuthToken at=\"" + domainAuthToken + "\"");
         return request;
   }
}

LoadImageHandler.ashx

<%@ WebHandler Language="C#" Class="LoadImageHandler" %>
using System;
using System.IO;
using System.Net;
using System.Web;
public class LoadImageHandler : IHttpHandler 
{
   private string path = null;
   private string dat = null;
   private string oh = null;
   
   public void ProcessRequest (HttpContext context) 
   {
      foreach (string key in context.Request.QueryString)
      {
         if ("url" == key)
         {
            path = context.Request.QueryString[key];
         }
         else
         {
            if ("oh" == key)
            {
               oh = HttpUtility.UrlDecode(context.Request.QueryString[key]);
            }
            else
            {
               context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
               return;
            }
         }
      }

      dat = "[domain authentication token]";
      
      if ((path == null) || (dat == null))
      {
         context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
         return;
      }
      // Get Photo
      HttpWebRequest serviceRequest = (HttpWebRequest)WebRequest.Create(path);
      serviceRequest.UserAgent = "Microsoft Windows Live Photo Demo";
      serviceRequest.Method = "GET";
      serviceRequest.Headers.Add("Authorization", "DomainAuthToken at=\"" + dat + "\"");
      
      try
      {
         HttpWebResponse serviceResponse = (HttpWebResponse)serviceRequest.GetResponse();
         context.Response.ContentType = serviceResponse.ContentType;  
         Stream s = serviceResponse.GetResponseStream();
         
         int b = s.ReadByte();
         while (b != -1)
         {
            context.Response.OutputStream.WriteByte((byte)b);
            b = s.ReadByte();
         }   
      }
      catch (WebException ex)
      {   //The HTTP request failed, so handle the error, or at least display what happened.
         context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
      }
      catch (Exception ex)
      {   //The parsing failed, so handle the error, or at least display what happened.
         context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
      }
   }
   public bool IsReusable {
      get {
         return true;
      }
   }
}
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker