protected void Page_Load(object sender, EventArgs e)
        {
            this.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct =>
                    {
                        var vitaDock = new VitaDockConsumer();
                        if (vitaDock.ConsumerKey != null)
                        {
                            this.MultiView1.ActiveViewIndex = 1;

                            if (!IsPostBack)
                            {
                                // Is VitaDock calling back with authorization?
                                var accessTokenResponse = await vitaDock.ProcessUserAuthorizationAsync(this.Request.Url);
                                if (accessTokenResponse != null)
                                {
                                    this.AccessToken = accessTokenResponse.AccessToken;
                                }
                                else
                                {
                                    // If we don't yet have access, immediately request it.
                                    Uri redirectUri = await vitaDock.RequestUserAuthorizationAsync();

                                    this.Response.Redirect(redirectUri.AbsoluteUri);
                                }
                            }
                        }
                    }));
        }
Example #2
0
		public static void Clear() {
			ProfileFields = null;
			FetchResponse = null;
			FriendlyLoginName = null;
			PapePolicies = null;
			GoogleAccessToken = new AccessToken();
		}
Example #3
0
        private async void beginAuthorizationButton_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.google.ConsumerKey))
            {
                MessageBox.Show(this, "You must modify the App.config or OAuthConsumerWpf.exe.config file for this application to include your Google OAuth consumer key first.", "Configuration required", MessageBoxButton.OK, MessageBoxImage.Stop);
                return;
            }

            var auth = new Authorize(
                this.google,
                consumer =>
                ((GoogleConsumer)consumer).RequestUserAuthorizationAsync(GoogleConsumer.Applications.Contacts | GoogleConsumer.Applications.Blogger));
            bool?result = auth.ShowDialog();

            if (result.HasValue && result.Value)
            {
                this.googleAccessToken    = auth.AccessToken;
                this.postButton.IsEnabled = true;

                XDocument contactsDocument = await this.google.GetContactsAsync(this.googleAccessToken);

                var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom"))
                               select new { Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value };
                this.contactsGrid.Children.Clear();
                foreach (var contact in contacts)
                {
                    this.contactsGrid.RowDefinitions.Add(new RowDefinition());
                    TextBlock name = new TextBlock {
                        Text = contact.Name
                    };
                    TextBlock email = new TextBlock {
                        Text = contact.Email
                    };
                    Grid.SetRow(name, this.contactsGrid.RowDefinitions.Count - 1);
                    Grid.SetRow(email, this.contactsGrid.RowDefinitions.Count - 1);
                    Grid.SetColumn(email, 1);
                    this.contactsGrid.Children.Add(name);
                    this.contactsGrid.Children.Add(email);
                }
            }
        }
Example #4
0
		protected void Page_Load(object sender, EventArgs e) {
			this.RegisterAsyncTask(
				new PageAsyncTask(
					async ct => {
						var twitter = new TwitterConsumer();
						if (twitter.ConsumerKey != null) {
							this.MultiView1.ActiveViewIndex = 1;

							if (!IsPostBack) {
								// Is Twitter calling back with authorization?
								var accessTokenResponse = await twitter.ProcessUserAuthorizationAsync(this.Request.Url);
								if (accessTokenResponse != null) {
									this.AccessToken = accessTokenResponse.AccessToken;
								} else {
									// If we don't yet have access, immediately request it.
									Uri redirectUri = await twitter.RequestUserAuthorizationAsync(MessagingUtilities.GetPublicFacingUrl());
									this.Response.Redirect(redirectUri.AbsoluteUri);
								}
							}
						}
					}));
		}
		protected void Page_Load(object sender, EventArgs e) {
			this.RegisterAsyncTask(
				new PageAsyncTask(
					async ct => {
						var google = new GoogleConsumer();
						if (google.ConsumerKey != null) {
							this.MultiView1.ActiveViewIndex = 1;

							if (!IsPostBack) {
								// Is Google calling back with authorization?
								var accessTokenResponse = await google.ProcessUserAuthorizationAsync(this.Request.Url);
								if (accessTokenResponse != null) {
									this.AccessToken = accessTokenResponse.AccessToken;
								} else if (this.AccessToken.Token == null) {
									// If we don't yet have access, immediately request it.
									Uri redirectUri = await google.RequestUserAuthorizationAsync(GoogleConsumer.Applications.Contacts);
									this.Response.Redirect(redirectUri.AbsoluteUri);
								}
							}
						}
					}));
		}
Example #6
0
		/// <summary>
		/// Creates the HTTP client.
		/// </summary>
		/// <param name="accessToken">The access token to authorize outbound HTTP requests with.</param>
		/// <param name="innerHandler">The inner handler that actually sends the HTTP message on the network.</param>
		/// <returns>The HttpClient to use.</returns>
		public HttpClient CreateHttpClient(AccessToken accessToken, HttpMessageHandler innerHandler = null) {
			var handler = this.CreateMessageHandler(accessToken, innerHandler);
			var client = this.HostFactories.CreateHttpClient(handler);
			return client;
		}
Example #7
0
		/// <summary>
		/// Creates a message handler that signs outbound requests with a previously obtained authorization.
		/// </summary>
		/// <param name="accessToken">The access token to authorize outbound HTTP requests with.</param>
		/// <param name="innerHandler">The inner handler that actually sends the HTTP message on the network.</param>
		/// <returns>
		/// A message handler.
		/// </returns>
		/// <remarks>
		/// Overrides of this method may allow various derived types of handlers to be returned,
		/// enabling consumers that use RSA or other signing methods.
		/// </remarks>
		public virtual OAuth1HttpMessageHandlerBase CreateMessageHandler(AccessToken accessToken = default(AccessToken), HttpMessageHandler innerHandler = null) {
			Verify.Operation(this.ConsumerKey != null, Strings.RequiredPropertyNotYetPreset, "ConsumerKey");

			innerHandler = innerHandler ?? this.HostFactories.CreateHttpMessageHandler();
			OAuth1HttpMessageHandlerBase handler;
			if (this.ConsumerCertificate != null) {
				handler = new OAuth1RsaSha1HttpMessageHandler(innerHandler) {
					SigningCertificate = this.ConsumerCertificate,
				};
			} else {
				handler = new OAuth1HmacSha1HttpMessageHandler(innerHandler);
			}

			handler.ConsumerKey = this.ConsumerKey;
			handler.ConsumerSecret = this.ConsumerSecret;
			handler.AccessToken = accessToken.Token;
			handler.AccessTokenSecret = accessToken.Secret;

			return handler;
		}
		public async Task<XDocument> GetFavorites(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) {
			if (string.IsNullOrEmpty(accessToken.Token)) {
				throw new ArgumentNullException("accessToken.Token");
			}

			using (var httpClient = this.CreateHttpClient(accessToken)) {
				using (HttpResponseMessage response = await httpClient.GetAsync(GetFavoritesEndpoint, cancellationToken)) {
					response.EnsureSuccessStatusCode();
					return XDocument.Parse(await response.Content.ReadAsStringAsync());
				}
			}
		}
Example #9
0
		public async Task PostBlogEntryAsync(AccessToken accessToken, string blogUrl, string title, XElement body, CancellationToken cancellationToken = default(CancellationToken)) {
			string feedUrl;
			var getBlogHome = WebRequest.Create(blogUrl);
			using (var blogHomeResponse = getBlogHome.GetResponse()) {
				using (StreamReader sr = new StreamReader(blogHomeResponse.GetResponseStream())) {
					string homePageHtml = sr.ReadToEnd();
					Match m = Regex.Match(homePageHtml, @"http://www.blogger.com/feeds/\d+/posts/default");
					Debug.Assert(m.Success, "Posting operation failed.");
					feedUrl = m.Value;
				}
			}
			const string Atom = "http://www.w3.org/2005/Atom";
			XElement entry = new XElement(
				XName.Get("entry", Atom),
				new XElement(XName.Get("title", Atom), new XAttribute("type", "text"), title),
				new XElement(XName.Get("content", Atom), new XAttribute("type", "xhtml"), body),
				new XElement(XName.Get("category", Atom), new XAttribute("scheme", "http://www.blogger.com/atom/ns#"), new XAttribute("term", "oauthdemo")));

			MemoryStream ms = new MemoryStream();
			XmlWriterSettings xws = new XmlWriterSettings() {
				Encoding = Encoding.UTF8,
			};
			XmlWriter xw = XmlWriter.Create(ms, xws);
			entry.WriteTo(xw);
			xw.Flush();
			ms.Seek(0, SeekOrigin.Begin);

			var request = new HttpRequestMessage(HttpMethod.Post, feedUrl);
			request.Content = new StreamContent(ms);
			request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/atom+xml");
			using (var httpClient = this.CreateHttpClient(accessToken)) {
				using (var response = await httpClient.SendAsync(request, cancellationToken)) {
					if (response.StatusCode == HttpStatusCode.Created) {
						// Success
					} else {
						// Error!
						response.EnsureSuccessStatusCode(); // throw some meaningful exception.
					}
				}
			}
		}
Example #10
0
		/// <summary>
		/// Gets the Gmail address book's contents.
		/// </summary>
		/// <param name="accessToken">The access token previously retrieved.</param>
		/// <param name="maxResults">The maximum number of entries to return. If you want to receive all of the contacts, rather than only the default maximum, you can specify a very large number here.</param>
		/// <param name="startIndex">The 1-based index of the first result to be retrieved (for paging).</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// An XML document returned by Google.
		/// </returns>
		public async Task<XDocument> GetContactsAsync(AccessToken accessToken, int maxResults = 25, int startIndex = 1, CancellationToken cancellationToken = default(CancellationToken)) {
			// Enable gzip compression.  Google only compresses the response for recognized user agent headers. - Mike Lim
			var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip };
			using (var httpClient = this.CreateHttpClient(accessToken, handler)) {
				var request = new HttpRequestMessage(HttpMethod.Get, GetContactsEndpoint);
				request.Content = new FormUrlEncodedContent(
					new Dictionary<string, string>() {
						{ "start-index", startIndex.ToString(CultureInfo.InvariantCulture) },
						{ "max-results", maxResults.ToString(CultureInfo.InvariantCulture) },
					});
				request.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.151 Safari/534.16"));
				using (var response = await httpClient.SendAsync(request, cancellationToken)) {
					string body = await response.Content.ReadAsStringAsync();
					XDocument result = XDocument.Parse(body);
					return result;
				}
			}
		}
		public async Task<string> LogBloodSugarTestData(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (string.IsNullOrEmpty(accessToken.Token))
			{
				throw new ArgumentNullException("accessToken.Token");
			}

			using (var httpClient = this.CreateHttpClient(accessToken))
			{
				var request = new HttpRequestMessage();
				request.Method = HttpMethod.Post;
				request.RequestUri = new Uri(VitaDockBaseAuthUrl + VitaDockThermoString + "/generate");

				using (var response = await httpClient.SendAsync(request, cancellationToken))
				{
					response.EnsureSuccessStatusCode();
					string guid = await response.Content.ReadAsStringAsync();
					return guid;
				}
			}
		}
Example #12
0
		public Task<XDocument> UpdateProfileImageAsync(AccessToken accessToken, string pathToImage, CancellationToken cancellationToken = default(CancellationToken)) {
			string contentType = "image/" + Path.GetExtension(pathToImage).Substring(1).ToLowerInvariant();
			return this.UpdateProfileImageAsync(accessToken, File.OpenRead(pathToImage), contentType, cancellationToken);
		}
		/// <summary>
		/// Creates a message handler that conforms to the VitaDock API and which can
		/// sign outbound requests with a previously obtained authorization.
		/// </summary>
		/// <param name="accessToken">The access token to authorize outbound HTTP requests with.</param>
		/// <param name="innerHandler">The inner handler that actually sends the HTTP message on the network.</param>
		/// <returns>
		/// A message handler.
		/// </returns>
		/// <remarks>
		/// Use this to Creates a messagehandler that conforms that
		/// 1) uses HMAC-SHA256 for signing messages
		/// 2) which signs with a Nonce of 36 characters.
		/// 3) which does not send the oauth realm parameter
		/// 4) which does not include the oauth callback parameter
		/// 5) which does not require the oauth calbackconfirm parameter in response
		/// 6) and which uses timestamps that are specifying millisecond rather than seconds
		/// </remarks>
		public override OAuth1HttpMessageHandlerBase CreateMessageHandler(AccessToken accessToken = default(AccessToken), HttpMessageHandler innerHandler = null)
		{
			Verify.Operation(this.ConsumerKey != null, "Required Property ConsumerKey Not Yet Preset", "ConsumerKey");

			innerHandler = innerHandler ?? this.HostFactories.CreateHttpMessageHandler();
			VitaDockMessageHandler handler = new VitaDockMessageHandler(innerHandler);

			handler.ConsumerKey = this.ConsumerKey;
			handler.ConsumerSecret = this.ConsumerSecret;
			handler.AccessToken = accessToken.Token;
			handler.AccessTokenSecret = accessToken.Secret;

			return handler;
		}
Example #14
0
		public async Task<JArray> GetUpdatesAsync(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) {
			if (string.IsNullOrEmpty(accessToken.Token)) {
				throw new ArgumentNullException("accessToken.Token");
			}

			using (var httpClient = this.CreateHttpClient(accessToken)) {
				using (var response = await httpClient.GetAsync(GetFriendTimelineStatusEndpoint, cancellationToken)) {
					response.EnsureSuccessStatusCode();
					string jsonString = await response.Content.ReadAsStringAsync();
					var json = JArray.Parse(jsonString);
					return json;
				}
			}
		}
Example #15
0
		private async void finishButton_Click(object sender, RoutedEventArgs e) {
			var grantedAccess = await this.consumer.ProcessUserAuthorizationAsync(this.verifierBox.Text);
			this.AccessToken = grantedAccess.AccessToken;
			DialogResult = true;
			Close();
		}
Example #16
0
		public async Task<string> GetUsername(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) {
			XDocument xml = await this.VerifyCredentialsAsync(accessToken, cancellationToken);
			XPathNavigator nav = xml.CreateNavigator();
			return nav.SelectSingleNode("/user/screen_name").Value;
		}
Example #17
0
		public async Task<XDocument> VerifyCredentialsAsync(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) {
			using (var httpClient = this.CreateHttpClient(accessToken)) {
				using (var response = await httpClient.GetAsync(VerifyCredentialsEndpoint, cancellationToken)) {
					response.EnsureSuccessStatusCode();
					using (var stream = await response.Content.ReadAsStreamAsync()) {
						return XDocument.Load(XmlReader.Create(stream));
					}
				}
			}
		}
Example #18
0
		public async Task<XDocument> UpdateProfileImageAsync(AccessToken accessToken, Stream image, string contentType, CancellationToken cancellationToken = default(CancellationToken)) {
			var imageAttachment = new StreamContent(image);
			imageAttachment.Headers.ContentType = new MediaTypeHeaderValue(contentType);
			HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileImageEndpoint);
			var content = new MultipartFormDataContent();
			content.Add(imageAttachment, "image", "twitterPhoto");
			request.Content = content;
			using (var httpClient = this.CreateHttpClient(accessToken)) {
				using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) {
					response.EnsureSuccessStatusCode();
					string responseString = await response.Content.ReadAsStringAsync();
					return XDocument.Parse(responseString);
				}
			}
		}
		/// <summary>
		/// Creates an HTTP message handler that authorizes outgoing web requests.
		/// </summary>
		/// <param name="accessToken">The access token.</param>
		/// <returns>An <see cref="HttpMessageHandler"/> that applies the access token to all outgoing requests.</returns>
		public HttpMessageHandler CreateMessageHandler(AccessToken accessToken) {
			Requires.NotNullOrEmpty(accessToken.Token, "accessToken");

			return this.Consumer.CreateMessageHandler(accessToken);
		}
		public async Task<List<Thermodock>> GetLast10DaysOfThermoDocksDataAsync(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (string.IsNullOrEmpty(accessToken.Token))
			{
				throw new ArgumentNullException("accessToken.Token");
			}

			using (var httpClient = this.CreateHttpClient(accessToken))
			{
				httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

				using (var response = await httpClient.GetAsync(
					VitaDockBaseAuthUrl + VitaDockThermoString
					+ "?max=50&date_since=" + System.DateTime.UtcNow.AddDays(-10).ToString("yyyy-MM-dd"),
					cancellationToken))
				{
					response.EnsureSuccessStatusCode();
					string jsonString = await response.Content.ReadAsStringAsync();
					var json = JArray.Parse(jsonString);
					var ser = JsonSerializer.Create();

					var result = new List<Thermodock>();
					ser.Populate(json.CreateReader(), result);

					return result;
				}
			}
		}
Example #21
0
		public async Task<XDocument> UpdateProfileBackgroundImageAsync(AccessToken accessToken, string image, bool tile, CancellationToken cancellationToken) {
			var imageAttachment = new StreamContent(File.OpenRead(image));
			imageAttachment.Headers.ContentType = new MediaTypeHeaderValue("image/" + Path.GetExtension(image).Substring(1).ToLowerInvariant());
			HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileBackgroundImageEndpoint);
			var content = new MultipartFormDataContent();
			content.Add(imageAttachment, "image");
			content.Add(new StringContent(tile.ToString().ToLowerInvariant()), "tile");
			request.Content = content;
			request.Headers.ExpectContinue = false;
			using (var httpClient = this.CreateHttpClient(accessToken)) {
				using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) {
					response.EnsureSuccessStatusCode();
					string responseString = await response.Content.ReadAsStringAsync();
					return XDocument.Parse(responseString);
				}
			}
		}