//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 = "WLCRest@hotmail.com";
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();
}
}
}
}