Windows Live Contacts API: Code Samples

转载自:http://msdn.microsoft.com/en-us/library/bb463974.aspx

This Console application demonstrates the basic functionality of the Windows Live™ Contacts Representational State Transfer (REST) API.

C# Code Sample


To set up the project in Microsoft Visual Studio 2005

  1. Open Microsoft Visual Studio® 2005.

  2. On the File menu, click New, and then click Project. The New Project dialog box appears.

  3. In the Project types pane, click Visual C#, and then click Windows.

  4. In the Templates pane, click Console Application.

  5. In the Name text box, type WLCDemo, and then click OK. Visual Studio 2005 creates a new project.

To add the source code to the project
  1. Replace the source code in the file Program.cs with the source code in the Example section for Program.cs. To do this, click Copy Code to place the code in the Windows Clipboard.

  2. Open Program.cs from Solution Explorer, place your cursor anywhere in the file, and press CTRL+A.

  3. Press CTRL+V to paste the code into the Visual Studio source file and overwrite the template-generated code.

To add the SamplePOST.xml and SamplePUT.xml files to the project
  1. Right-click anywhere in Solution Explorer, click Add, and then click New Item.

  2. Under Templates, click XML File.

  3. In the Name text box, type SamplePOST.xml, and then click Add.

  4. In Solution Explorer, double-click SamplePOST.xml.

  5. Replace the source code in the file with the source code in the Example section for SamplePOST.xml.

  6. In Solution Explorer, right-click SamplePOST.xml, and then click Properties.

  7. For the Copy to Output Directory property, click Copy Always.

  8. Repeat steps 1 to 7, but replace all instances of SamplePOST.xml with SamplePUT.xml.

  9. Press F5 to run the application in Debug mode.

Example


Program.cs

//THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF

//ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED

//TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A

//PARTICULAR PURPOSE.

//

//Copyright (C) 2007  Microsoft Corporation.  All rights reserved.



using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.Net.Security;

using System.Security.Cryptography.X509Certificates;

using System.Xml;

using System.Xml.XPath;

using System.IO;



namespace WLCDemo

{

    class Program

    {

        // Define account information.

        public const string strSampleWLID = "[email protected]";

        public const string strSampleLid = "8C06463EE2B3FBC5";

        public const string strSampleHostName = "livecontacts.services.live.com";



        // Authentication information

        public const string strSampleDelegatedToken = "";

        public const string strSampleAuthHeaderValue = "DelegatedToken dt=\"" + Program.strSampleDelegatedToken + "\"";



        // Define configuration information.

        public const int iSamplePort = 443;

        public const string strSamplePOSTDataFile = "SamplePOST.xml";

        public const string strSamplePUTDataFile = "SamplePUT.xml";

        public const string strSampleErrorDataFile = "ErrorResponse.xml";



        static void Main(string[] args)

        {

            bool bSuccess = true;

            bool bContactCreated = false;



            // Create starting point URI. This URI value changes after the contact

            // is created, modified, etc.

            UriBuilder uriBuilder = new UriBuilder();

            uriBuilder.Scheme = "HTTPS";

            uriBuilder.Path = "/users/@L@" + strSampleLid + "/REST/LiveContacts/Contacts";

            uriBuilder.Host = strSampleHostName;

            uriBuilder.Port = iSamplePort;

            string uriPath = uriBuilder.Uri.AbsoluteUri;



            // Create custom SSL handler

            ServicePointManager.ServerCertificateValidationCallback +=

                delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)

                {

                    bool validationResult = true;

                    return validationResult;

                };



            // Create the contact.

            if (bSuccess)

            {

                bSuccess = SendHttpRequest(ref uriPath, "POST", HttpStatusCode.Created, strSamplePOSTDataFile, "created", null);

                bContactCreated = bSuccess;

            }



            // Retrieve the contact.

            if (bSuccess)

            {

                bSuccess = SendHttpRequest(ref uriPath, "GET", HttpStatusCode.OK, "ResultBeforeUpdate.xml", "retrieved", null);

            }



            // Update the contact.

            if (bSuccess)

            {

                bSuccess = SendHttpRequest(ref uriPath, "PUT", HttpStatusCode.NoContent, strSamplePUTDataFile, "updated", null);

            }



            // Retrieve the contact.

            if (bSuccess)

            {

                bSuccess = SendHttpRequest(ref uriPath, "GET", HttpStatusCode.OK, "ResultAfterUpdate.xml", "retrieved", null);

            }



            // Filter the contact by using the MapPoint predefined filter.

            if (bSuccess)

            {

                SendHttpRequest(ref uriPath, "GET", HttpStatusCode.OK, "ResultAfterFilter.xml", "filtered", "MapPoint");

            }



            // Delete the contact.

            if (bContactCreated)

            {

                SendHttpRequest(ref uriPath, "DELETE", HttpStatusCode.NoContent, null, "deleted", null);

            }

        }



        // The SendHttpRequest method is the workhorse of this application. 

        // It determines which type of HTTP request to send (e.g. GET, POST, etc.), 

        // and how to handle the data it receives.

        //

        // The SendHttpRequest method uses the following parameters:

        //

        // ref string uriPath:

        //      Specifies the URI that is used in the HTTP request.

        // string strRequestMethod: 

        //      Specifies the type of HTTP request. For example, "GET" or "POST".

        // HttpStatusCode expectedStatusCode: 

        //      Specifies the expected status code to be returned from the server.

        // string strDataFile: 

        //      For a "POST" or "PUT" request, this parameter specifies the file to load data from. 

        //      This data is then added to the body of the HTTP request.

        //      For a "GET" request, this parameter specifies the file to write data to.

        // string strResultText:

        //      Specifies the text to display in the results on the Console.

        // string strFilter:

        //      Specifies the filter to use.

        //

        static bool SendHttpRequest(ref string uriPath, string strRequestMethod, HttpStatusCode expectedStatusCode, string strDataFile, string strResultText, string strFilter)

        {

            // Create HTTP request object.

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriPath);



            // Append the filter to query string if a filter value is passed.

            if (strFilter != null)

            {

                request = (HttpWebRequest)WebRequest.Create(uriPath + "?Filter=" + strFilter);

            }



            // Add the authentication header

            request.Headers["Authorization"] = Program.strSampleAuthHeaderValue;

            // Only add the following Header if you can unzip/inflate the response automatically

            // otherwise the response will be unparsable and non XML

            request.Headers["Accept-Encoding"] = "gzip, deflate";

            request.Headers["Pragma"] = "No-Cache";



            request.CookieContainer = new CookieContainer();



            // Set the HTTP request method. For example, this can be POST, GET, and so on.

            request.Method = strRequestMethod;



            // Set the HTTP content type - IMPORTANT - This must be exactly as written here and is REQUIRED

            request.ContentType = "application/xml; charset=utf-8";



            // For POST or PUT requests, load data from the .xml file and write it to the request stream after the header.

            if (strRequestMethod.Equals("POST") || strRequestMethod.Equals("PUT"))

            {

                // Load data from file.

                XPathDocument doc = new XPathDocument(strDataFile);

                XPathNavigator nav = doc.CreateNavigator();



                // Write data to request stream.

                XmlWriter writer = XmlWriter.Create(request.GetRequestStream());

                nav.WriteSubtree(writer);

                writer.Flush();



                // Close the request stream to release the resource.

                request.GetRequestStream().Close();

            }



            // Invoke the HTTP request and get the response.

            HttpWebResponse response;

            try

            {

                response = (HttpWebResponse)request.GetResponse();

            }

            catch (WebException wex)

            {

                OutputException(wex);

                return false;

            }



            // Check response result.

            if (response.StatusCode != expectedStatusCode)

            {

                OutputUnexpectedResponse(response);

                return false;

            }



            // If this is a contact created by POST, update uriPath.

            if (strRequestMethod.Equals("POST"))

                uriPath = response.Headers[HttpResponseHeader.Location];



            // If this is a GET request, write the data to an .xml file.

            if (strRequestMethod.Equals("GET"))

                OutputResponse(response, strDataFile);



            // Close the response to release the resource.

            response.Close();



            // Display the results.

            Console.WriteLine("Contact " + strResultText + " successfully at:");

            Console.WriteLine(uriPath);

            if (strRequestMethod.Equals("GET"))

                Console.WriteLine("Data written to " + strDataFile);

            Console.Write("Press any key to continue...");

            Console.ReadLine();

            Console.WriteLine();



            return true;

        }



        // Define utility method for handling exceptions.

        static void OutputException(WebException wex)

        {

            Console.WriteLine(wex.ToString());

            OutputUnexpectedResponse((HttpWebResponse)wex.Response);

        }



        // Define utility method for handling unexpected HTTP responses.

        static void OutputUnexpectedResponse(HttpWebResponse response)

        {

            if (response != null)

            {

                Console.WriteLine("Received an unexpected HTTP response");

                Console.WriteLine("StatusCode: " + response.StatusCode.ToString());

                OutputResponse(response, strSampleErrorDataFile);

                Console.WriteLine("OutputFile: " + strSampleErrorDataFile);

                Console.Write("Press any key to continue...");

                Console.ReadLine();

            }

        }



        // Define utility method for writing HTTP response to an .xml file.

        static void OutputResponse(HttpWebResponse response, string outputFileName)

        {

            if (response.ContentLength != 0)

            {

                FileStream outputStream = File.Create(outputFileName);



                XmlTextWriter writer = new XmlTextWriter(outputStream, Encoding.UTF8);

                writer.Formatting = Formatting.Indented;

                writer.Indentation = 4;

                writer.IndentChar = ' ';



                XPathDocument doc = new XPathDocument(response.GetResponseStream());

                XPathNavigator nav = doc.CreateNavigator();



                nav.WriteSubtree(writer);



                writer.Flush();

                writer.Close();

            }

        }

    }

}

SamplePost


SamplePost.xml

<?xml version="1.0" encoding="utf-8" ?> 

<Contact>

 <Comment>This is primary ABCH test account</Comment> 

 <Profiles>

  <Personal>

   <NameToFileAs>ABCH Int</NameToFileAs> 

   <NameTitle>Mr.</NameTitle> 

   <FirstName>Paul</FirstName> 

   <MiddleName>Alan</MiddleName> 

   <LastName>Roberts</LastName> 

   <Suffix>Jr.</Suffix> 

   <YomiFirstName>Aibiceiachi</YomiFirstName> 

   <YomiLastName>Ceshiban</YomiLastName> 

   <Birthdate>1986-12-01T12:30:33Z</Birthdate> 

   <Anniversary>May 8th</Anniversary> 

   <Gender>Male</Gender> 

   <TimeZone>GmtMinus8h</TimeZone> 

   <SpouseName>Storage</SpouseName> 

  </Personal>

  <Professional>

   <JobTitle>SDE</JobTitle> 

   <Profession>address books</Profession> 

   <Manager>WindowsLive</Manager> 

   <Assistant>Someone</Assistant> 

  </Professional>

 </Profiles>

 <Emails>

  <Email>

   <EmailType>Personal</EmailType> 

   <Address>[email protected]</Address> 

   <IsDefault>true</IsDefault> 

  </Email>

  <Email>

   <EmailType>Business</EmailType> 

   <Address>[email protected]</Address> 

  </Email>

 </Emails>

 <Phones>

  <Phone>

   <PhoneType>Personal</PhoneType> 

   <Number>+1(425)281-3700</Number> 

  </Phone>

  <Phone>

   <PhoneType>Business</PhoneType> 

   <Number>+1(425)705-1400</Number> 

   <IsDefault>true</IsDefault> 

  </Phone>

 </Phones>

 <Locations>

  <Location>

   <LocationType>Business</LocationType> 

   <Office>REDW-D2227</Office> 

   <Department>Windows Live</Department> 

   <CompanyName>Microsoft</CompanyName> 

   <YomiCompanyName>WeiRuanGongSi</YomiCompanyName> 

   <StreetLine>One Microsoft Way</StreetLine> 

   <StreetLine2>NE 148TH AVE</StreetLine2> 

   <PrimaryCity>Redmond</PrimaryCity> 

   <SecondaryCity>King</SecondaryCity> 

   <Subdivision>WA</Subdivision> 

   <PostalCode>98052</PostalCode> 

   <CountryRegion>USA</CountryRegion> 

   <Latitude>38.0</Latitude> 

   <Longitude>116.3</Longitude> 

   <IsDefault>false</IsDefault> 

  </Location>

  <Location>

   <LocationType>Personal</LocationType> 

   <StreetLine>10711 167TH PL NE</StreetLine> 

   <StreetLine2>APT 115</StreetLine2> 

   <PrimaryCity>Kirkland</PrimaryCity> 

   <SecondaryCity>King</SecondaryCity> 

   <Subdivision>WA</Subdivision> 

   <PostalCode>98123</PostalCode> 

   <CountryRegion>USA</CountryRegion> 

   <Latitude>39.0</Latitude> 

   <Longitude>126.3</Longitude> 

   <IsDefault>true</IsDefault> 

  </Location>

 </Locations>

 <URIs>

  <URI>

   <URIType>Personal</URIType> 

   <Name>Future Public Front End URL</Name> 

   <Address>http://contacts.live.com</Address> 

   </URI>

  <URI>

   <URIType>Business</URIType> 

   <Name>Public Front End URL</Name> 

   <Address>http://contacts.live.com</Address> 

  </URI>

 </URIs>

</Contact>

SamplePut


SamplePut.xml

<?xml version="1.0" encoding="utf-8" ?> 

<Contact>

 <Comment>This is updated primary test account</Comment> 

 <Profiles>

  <Personal>

   <NameToFileAs>Updated ABCH Int</NameToFileAs> 

   <NameTitle>UpdatedMr.</NameTitle> 

   <FirstName>UpdatedFirstName</FirstName> 

   <MiddleName>UpdatedMN</MiddleName> 

   <LastName>UpdatedLast</LastName> 

   <Suffix>UpdatedJr.</Suffix> 

   <YomiFirstName>UpdatedAibiceiachi</YomiFirstName> 

   <YomiLastName>UpdatedCeshiban</YomiLastName> 

   <Birthdate>1987-02-26</Birthdate> 

   <Anniversary>May 8th</Anniversary> 

   <Gender>Female</Gender> 

   <TimeZone>GmtMinus6h</TimeZone> 

   <SpouseName>UpdatedStorage</SpouseName> 

  </Personal>

  <Professional>

   <JobTitle>UpdatedSDE</JobTitle> 

   <Profession>Updatedaddress books</Profession> 

   <Manager>UpdatedWindowsLive</Manager> 

   <Assistant>UpdatedSomeone</Assistant> 

  </Professional>

 </Profiles>

</Contact>

你可能感兴趣的:(windows)