Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Data;
- using System.Linq;
- using System.Threading;
- using System.Web;
- using DotNetOpenAuth.Messaging;
- using DotNetOpenAuth.OAuth2;
- using Google.Apis.Authentication.OAuth2;
- using Google.Apis.Calendar.v3;
- using Google.Apis.Calendar.v3.Data;
- using Google.Apis.Util;
- namespace GoogleCalendar
- {
- public partial class _Default : System.Web.UI.Page
- {
- private static CalendarService _service; // We don't need individual service instances for each client.
- private static OAuth2Authenticator<WebServerClient> _authenticator;
- private DataSet dsCalendars = new DataSet("Calendars");
- protected void Page_Load(object sender, EventArgs e)
- {
- // Create the Tasks-Service if it is null.
- if (_service == null)
- {
- _service = new CalendarService(_authenticator = CreateAuthenticator());
- }
- var state = _authenticator.State;
- }
- protected void listButton_Click(object sender, EventArgs e)
- {
- FetchCalendarlists();
- }
- public void FetchCalendarlists()
- {
- try
- {
- // Fetch all TasksLists of the user asynchronously.
- CalendarList response = _service.CalendarList.List().Fetch();
- ShowCalendarslists(response);
- }
- catch (ThreadAbortException)
- {
- // User was not yet authenticated and is being forwarded to the authorization page.
- throw;
- }
- catch (Exception ex)
- {
- output.Text = ex.Message.ToString();
- }
- }
- private void ShowCalendarslists(CalendarList response)
- {
- if (response.Items == null) // If no item is in the response, .Items will be null.
- {
- return;
- }
- foreach (CalendarListEntry list in response.Items)
- {
- var events = _service.Events.List(list.Id).Fetch();
- var table = events.Items.OfType<Event>().ToDataTable(list.Id);
- dsCalendars.Tables.Add(table);
- }
- }
- private OAuth2Authenticator<WebServerClient> CreateAuthenticator()
- {
- // Register the authenticator.
- var provider = new WebServerClient(GoogleAuthenticationServer.Description);
- provider.ClientIdentifier = ClientCredentials.ClientID;
- provider.ClientSecret = ClientCredentials.ClientSecret;
- var authenticator =
- new OAuth2Authenticator<WebServerClient>(provider, GetAuthorization) { NoCaching = false };
- return authenticator;
- }
- private static IAuthorizationState GetAuthorization(WebServerClient client)
- {
- // If this user is already authenticated, then just return the auth state.
- IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
- string refreshToken = LoadRefreshToken();
- if (!String.IsNullOrWhiteSpace(refreshToken))
- {
- state.RefreshToken = refreshToken;
- if (client.RefreshToken(state))
- return state;
- }
- // Check if an authorization request already is in progress.
- state = client.ProcessUserAuthorization(new HttpRequestInfo(HttpContext.Current.Request));
- if (state != null && (!string.IsNullOrEmpty(state.AccessToken) || !string.IsNullOrEmpty(state.RefreshToken)))
- {
- // Store and return the credentials.
- StoreRefreshToken(state);
- return state;
- }
- // Otherwise do a new authorization request.
- string scope = CalendarService.Scopes.Calendar.GetStringValue();
- OutgoingWebResponse response = client.PrepareRequestUserAuthorization(new[] { scope });
- response.Send(); // Will throw a ThreadAbortException to prevent sending another response.
- return null;
- }
- private static string LoadRefreshToken()
- {
- DBDataContext db = new DBDataContext();
- var token = string.Empty;
- var userToken = db.UserTokens.SingleOrDefault(o => o.UserName == HttpContext.Current.User.Identity.Name);
- if (userToken != null)
- {
- token = userToken.Token;
- }
- return token;
- }
- private static void StoreRefreshToken(IAuthorizationState state)
- {
- DBDataContext db = new DBDataContext();
- UserToken userToken = db.UserTokens.SingleOrDefault(o => o.UserName == HttpContext.Current.User.Identity.Name);
- if (userToken == null)
- {
- userToken = new UserToken()
- {
- UserName = HttpContext.Current.User.Identity.Name
- };
- db.UserTokens.InsertOnSubmit(userToken);
- }
- userToken.Token = state.RefreshToken;
- db.SubmitChanges();
- }
- }
- internal static class ClientCredentials
- {
- /// <summary>
- /// The OAuth2.0 Client ID of your project.
- /// </summary>
- public static readonly string ClientID = "Your Client ID";
- /// <summary>
- /// The OAuth2.0 Client secret of your project.
- /// </summary>
- public static readonly string ClientSecret = "Your Client Secret";
- /// <summary>
- /// Your Api/Developer key.
- /// </summary>
- public static readonly string ApiKey = "Your API Key";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment