Added Consumer WPF and ASP.NET WebForms samples.
[dotnetoauth.git] / samples / Consumer / GoogleAddressBook.aspx.cs
blob5197b668c755b1fb57313c2ea236ff104a49d57c
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Web;
6 using System.Web.UI;
7 using System.Web.UI.WebControls;
8 using System.Xml.Linq;
9 using DotNetOAuth;
10 using DotNetOAuth.ChannelElements;
11 using DotNetOAuth.Messaging;
13 /// <summary>
14 /// A page to demonstrate downloading a Gmail address book using OAuth.
15 /// </summary>
16 public partial class GoogleAddressBook : System.Web.UI.Page {
17 protected void Page_Load(object sender, EventArgs e) {
18 if (!IsPostBack) {
19 if (Session["TokenManager"] != null) {
20 InMemoryTokenManager tokenManager = (InMemoryTokenManager)Session["TokenManager"];
21 Consumer google = new Consumer(Constants.GoogleDescription, tokenManager) {
22 ConsumerKey = tokenManager.ConsumerKey,
23 ConsumerSecret = tokenManager.ConsumerSecret,
26 var accessTokenMessage = google.ProcessUserAuthorization();
27 if (accessTokenMessage != null) {
28 // User has approved access
29 MultiView1.ActiveViewIndex = 1;
30 resultsPlaceholder.Controls.Add(new Label { Text = accessTokenMessage.AccessToken });
32 Response contactsResponse = google.SendAuthorizedRequest(Constants.GoogleScopes.GetContacts, accessTokenMessage.AccessToken);
33 XDocument contactsDocument = XDocument.Parse(contactsResponse.Body);
34 var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom"))
35 select new {
36 Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value,
37 Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value,
39 StringBuilder tableBuilder = new StringBuilder();
40 tableBuilder.Append("<table><tr><td>Name</td><td>Email</td></tr>");
41 foreach (var contact in contacts) {
42 tableBuilder.AppendFormat(
43 "<tr><td>{0}</td><td>{1}</td></tr>",
44 HttpUtility.HtmlEncode(contact.Name),
45 HttpUtility.HtmlEncode(contact.Email));
47 tableBuilder.Append("</table>");
48 resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() });
54 protected void authorizeButton_Click(object sender, EventArgs e) {
55 if (!Page.IsValid) {
56 return;
59 InMemoryTokenManager tokenManager = new InMemoryTokenManager(consumerKeyBox.Text, consumerSecretBox.Text);
60 Session["TokenManager"] = tokenManager;
61 Consumer google = new Consumer(Constants.GoogleDescription, tokenManager);
62 google.ConsumerKey = consumerKeyBox.Text;
63 google.ConsumerSecret = consumerSecretBox.Text;
65 var extraParameters = new Dictionary<string, string> {
66 { "scope", Constants.GoogleScopes.Contacts },
68 google.RequestUserAuthorization(new Uri(Request.Url, Request.RawUrl), extraParameters, null).Send();