Posts OAUTH2.0 to access Google Calendar
Post
Cancel

OAUTH2.0 to access Google Calendar

Google providers you huge list of API’S to access the google resources . This resources can be accesses only after passing the authentication layer successfully.Google APIs use the OAuth 2.0 protocol for authentication and authorization. Google supports common OAuth 2.0 scenarios such as those for web server, installed, and client-side applications.

What is OAuth Protocol?

OAuth is an open-source authorization protocol - or set of rules for authorization that allows a third-party application to access a user’s data without the user needing to share login credentials. It purely works on token-based authorization mechanism.

http://www.hakimshabir.blogspot.com/2016/02/using-oauth20-to-access-google-calendar.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace DotNetGoogleCalendarIntegration
{
    class Program
    {
//I just include calendar scope here because i want to access 
//user calendar for event retrieval and insertion
static string[] Scopes = { CalendarService.Scope.Calendar };
static string Applicationname = "Faith Application";
static void Main(string[] args)
{
UserCredential credential;
CalendarService service;
//JSON File created in Google console and added to application folder
using (var stream = new FileStream("..\\..\\googleclient_secret.json",
 FileMode.Open, FileAccess.Read))
{  
    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
      Scopes,
      Environment.UserName,
      CancellationToken.None,
      new DatabaseStore(@"Database Server Name", "database username",
 "password", "databasename", "tablename")).Result;
 //oauth sucks need to get refresh token and save it for persistence and
     to avoid popup dialog every time for ACCEPT and DENY
    // Console.WriteLine(credential);      

}
// Create Calendar Service.
service = new CalendarService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = Applicationname ,
});

// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Console.WriteLine("Upcoming events for Shabir:");
Console.WriteLine("====================================================");
Events events = request.Execute();
if (events.Items.Count > 0)
{
    foreach (var eventItem in events.Items)
    {
string when = eventItem.Start.DateTime.ToString();
string title = eventItem.Description.ToString();
string organizer = eventItem.Organizer.Email.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0}" + Environment.NewLine + "{1}" + Environment.NewLine + " 
 {2}" + Environment.NewLine + "   {3}", eventItem.Summary, when, title, organizer);
Console.WriteLine("------------------------------------------------------");
    }

}
else
{
    Console.WriteLine("No upcoming events found.");
}

//ADDING EVENT
Event newEvent = new Event();
newEvent.Summary = "Shabir Meeting";
newEvent.Description = "Today going to discuss regarding OAuth Protocol";
newEvent.Start = new EventDateTime();
newEvent.Start.DateTime = DateTime.Now.AddHours(5);
newEvent.End = new EventDateTime();
newEvent.End.DateTime = DateTime.Now.AddHours(8);
service.Events.Insert(newEvent, "primary").ExecuteAsync();
Console.Read();
}
    }
}

//Note: In Case you are looking for saving in local file, i mean implementing IFileDataDtore change above function code snippet with
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
      Scopes,
      Environment.UserName,
      CancellationToken.None,
          CancellationToken.None,
          new FileDataStore(@"D:\CalendarCsharp")).Result;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
//DatabaseStore.cs
using Google.Apis.Json;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DotNetGoogleCalendarIntegration
{
    public class DatabaseStore : IDataStore
    {

//database parameters
readonly string tableName;
readonly string serverName;
readonly string loginName;
readonly string passWord;
readonly string databaseName; 
private Boolean _IsConnected { get; set; }
public Boolean connectionAlive { get { return _IsConnected; } }

/// <param name="database">database name
public DatabaseStore(String server, string login, string password, string databasename, string tablename)
{
tableName = tablename;
serverName = server;
loginName = login;
passWord = password;
databaseName = databasename;
SqlConnection myConnection = this.connectdb();   // Opens a connection to the database.
if (_IsConnected)
{
    // check if the Table Exists;
    try
    {
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select 1 from GoogleOAuthUser where 1 = 0",myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{var hold = myReader["Column1"];}
    }
    catch
    {
// table doesn't exist we create it
SqlCommand myCommand = new SqlCommand("CREATE TABLE [dbo].GoogleOAuthUser( " +
  " username [nvarchar](100) NOT NULL," +
  " RefreshToken [nvarchar](4000) NOT NULL," +
  " Userid [nvarchar](50) NOT NULL" +
   " ) ON [PRIMARY]", myConnection);
myCommand.ExecuteNonQuery();
    }
}

myConnection.Close();
}
/// Stores the given value for the given key. It creates a new 
    ///file (named <see cref="GenerateStoredKey"></see>) in 
<typeparam name="T">///type to store in the data store</typeparam>
/// <param name="key">The key
/// <param name="value">The value to store in the data store
public Task StoreAsync<t>(string key, T value)
{
if (string.IsNullOrEmpty(key))
{
    throw new ArgumentException("Key MUST have a value");
}
var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
SqlConnection myConnection = this.connectdb();
if (!_IsConnected)
{
    throw new Exception("Not connected to the database");
}
// Try and find the Row in the DB.
using (SqlCommand command = new SqlCommand
    ("select Userid from GoogleOAuthUser where UserName = @username", myConnection))
{
    command.Parameters.AddWithValue("@username", key);
    string hold = null;
    SqlDataReader myReader = command.ExecuteReader();
    while (myReader.Read())
    {
hold = myReader["Userid"].ToString();
    }
    myReader.Close();
    if (hold == null)
    {
try
{
// New User we insert it into the database
string insertString = "INSERT INTO [dbo].GoogleOAuthUser  (username,RefreshToken,Userid) " +
  " VALUES (@key,@value,'1' )";
SqlCommand commandins = new SqlCommand(insertString, myConnection);
commandins.Parameters.AddWithValue("@key", key);
commandins.Parameters.AddWithValue("@value", serialized);
commandins.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Error inserting new row: " + ex.Message);
}
    }
    else
    {
try
{
// Existing User We update it
string insertString = "update GoogleOAuthUser " +
  " set  RefreshToken= @value  " +
  " where username = @key";
SqlCommand commandins = new SqlCommand(insertString, myConnection);
commandins.Parameters.AddWithValue("@key", key);
commandins.Parameters.AddWithValue("@value", serialized);
commandins.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Error updating user: " + ex.Message);
}
    }
}
   myConnection.Close();
return TaskEx.Delay(0);
}
/// <summary>
/// Deletes the given key. It deletes the <see cref="GenerateStoredKey"></see>
 /// named file in <see cref="FolderPath"></see>.
/// </summary>
/// <param name="key">The key to delete from the data store
public Task DeleteAsync<t>(string key)
{
if (string.IsNullOrEmpty(key))
{
    throw new ArgumentException("Key MUST have a value");
}
SqlConnection myConnection = this.connectdb();
if (!_IsConnected)
{
    throw new Exception("Not connected to the database");
}
// Deletes the users data.
string deleteString = "delete GoogleOAuthUser from " +
  " where username = @key";
SqlCommand commandins = new SqlCommand(deleteString, myConnection);
commandins.Parameters.AddWithValue("@key", key);
commandins.ExecuteNonQuery();
myConnection.Close();
return TaskEx.Delay(0);
}
public Task<t> GetAsync<t>(string key)
{
//Key is the user string sent with AuthorizeAsync
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");}
TaskCompletionSource<t> tcs = new TaskCompletionSource<t>();
ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["strSqlConnection"];
if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
    throw new Exception("Fatal error: missing connecting string in web.config file");
string connString = mySetting.ConnectionString;
   SqlConnection objConn = new SqlConnection(connString);
objConn.Open();
// Try and find the Row in the DB.
using (SqlCommand command = new SqlCommand("select RefreshToken from GoogleOAuthUser 
    where UserName = @username;", objConn))
{
    command.Parameters.AddWithValue("@username", key);
    string RefreshToken = null;
    SqlDataReader myReader = command.ExecuteReader();
    while (myReader.Read())    {
RefreshToken = myReader["RefreshToken"].ToString();
    }
    if (RefreshToken == null)
    {
// we don't have a record so we request it of the user.
tcs.SetResult(default(T));
    }
    else
    {
try
{
// we have it we use that.
tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<t>(RefreshToken));
}
catch (Exception ex)
{
tcs.SetException(ex);
}
    }
}
return tcs.Task;
}
/// <summary>
/// Clears all values in the data store. 
///This method deletes all files in <see cref="FolderPath"></see>.
/// </summary>
public Task ClearAsync()
{
SqlConnection myConnection = this.connectdb();
if (!_IsConnected)
{
    throw new Exception("Not connected to the database");
}
// Removes all data from the Table.
string truncateString = "truncate table [dbo].GoogleOAuthUser ";
SqlCommand commandins = new SqlCommand(truncateString, myConnection);
commandins.ExecuteNonQuery();
myConnection.Close();
return TaskEx.Delay(0);
}

/// <summary>Creates a unique stored key based on the key and the class type.</summary>
/// <param name="key">The object key
/// <param name="t">The type to store or retrieve
public static string GenerateStoredKey(string key, Type t)
{
return string.Format("{0}-{1}", t.FullName, key);
}
//Handel's creating the connection to the database
private SqlConnection connectdb()
{
ConnectionStringSettings mySetting = ConfigurationManager.ConnectionStrings["strSqlConnection"];
if (mySetting == null || string.IsNullOrEmpty(mySetting.ConnectionString))
    throw new Exception("Fatal error: missing connecting string in web.config file");
string connString = mySetting.ConnectionString;
SqlConnection myConnection = null;
try
{
    myConnection = new SqlConnection(connString);
    try
    {
myConnection.Open();  
if (myConnection.State == System.Data.ConnectionState.Open)
{
_IsConnected = true;
}
else
{
throw new ArgumentException("Error unable to open connection to the database.");
}
    }
    catch (Exception ex)
    {
throw new ArgumentException("Error opening Connection to the database: " + ex.Message);
    }

}
catch (Exception ex)
{
    throw new ArgumentException("Error creating Database Connection: " + ex.Message);
}

return myConnection;
}

    }
}

Retrieve Events from GCalendar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 //   // Create Calendar Service.
service = new CalendarService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = ApplicationName,
});

// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("primary");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Console.WriteLine("Upcoming events for Shabir:");
Console.WriteLine("====================================================");
Events events = request.Execute();
if (events.Items.Count > 0)
{
    foreach (var eventItem in events.Items)
    {
string when = eventItem.Start.DateTime.ToString();
string title = eventItem.Description.ToString();
string organizer = eventItem.Organizer.Email.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
Console.WriteLine("{0}" + Environment.NewLine + "{1}" + Environment.NewLine + "  
     {2}" + Environment.NewLine + "   {3}", eventItem.Summary, when, title, organizer);
Console.WriteLine("------------------------------------------------------");
    }

}
else
{
    Console.WriteLine("No upcoming events found.");
}

Insert Event to GCalendar

js Event newEvent = new Event(); newEvent.Summary = "Shabir Meeting"; newEvent.Description = "Today going to discuss regarding OAuth Protocol"; newEvent.Start = new EventDateTime(); newEvent.Start.DateTime = DateTime.Now.AddHours(5); newEvent.End = new EventDateTime(); newEvent.End.DateTime = DateTime.Now.AddHours(8); service.Events.Insert(newEvent, "primary").ExecuteAsync(); Console.Read(); </t></t></t></t></t></t></t>

origin - http://www.pipiscrew.com/?p=3753 net-oauth2-0-to-access-google-calendar-2

This post is licensed under CC BY 4.0 by the author.
Contents

Trending Tags