static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token50.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); //Needed parameter for the 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; // List events. Events events = request.Execute(); Console.WriteLine("Upcoming events:"); if (events.Items != null && events.Items.Count > 0) { foreach (var eventItem in events.Items) { string when = eventItem.Start.DateTime.ToString(); string end = eventItem.End.DateTime.ToString(); Console.WriteLine("{0} \n Starts on: {1} \n Ends: {2} \n Location: {3} \n", eventItem.Summary, when, end, eventItem.Location); } } else { Console.WriteLine("No upcoming events found."); } Console.ReadLine(); }
private async Task getAuthenticated(ClientSecrets cs) { log.Debug("Authenticating with Google calendar service..."); FileDataStore tokenStore = new FileDataStore(Program.UserFilePath); tokenFullPath = Path.Combine(tokenStore.FolderPath, TokenFile); log.Debug("Google credential file location: " + tokenFullPath); if (!tokenFileExists) { log.Info("No Google credentials file available - need user authorisation for OGCS to manage their calendar."); } //string[] scopes = new[] { "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/userinfo.email" }; string[] scopes = new[] { "https://www.googleapis.com/auth/calendar", "email" }; UserCredential credential = null; try { //This will open the authorisation process in a browser, if required credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(cs, scopes, "user", System.Threading.CancellationToken.None, tokenStore); if (!tokenFileExists) { log.Debug("User has provided authentication code and credential file saved."); } } catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { //OGCSexception.AnalyseTokenResponse(ex); if (ex.Error.Error == "access_denied") { String noAuthGiven = "Sorry, but this application will not work if you don't allow it access to your Google Calendar :("; log.Warn("User did not provide authorisation code. Sync will not be able to work."); MessageBox.Show(noAuthGiven, "Authorisation not given", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); throw new ApplicationException(noAuthGiven); } else { MainForm.Instance.AsyncLogboxout("Unable to authenticate with Google. The following error occurred:"); MainForm.Instance.AsyncLogboxout(ex.Message); } } catch (System.Exception ex) { OGCSexception.Analyse(ex); MainForm.Instance.AsyncLogboxout("Unable to authenticate with Google. The following error occurred:"); MainForm.Instance.AsyncLogboxout(ex.Message); } if (credential.Token.AccessToken != "" && credential.Token.RefreshToken != "") { log.Info("Refresh and Access token successfully retrieved."); log.Debug("Access token expires " + credential.Token.Issued.AddSeconds(credential.Token.ExpiresInSeconds.Value).ToLocalTime().ToString()); } GoogleOgcs.Calendar.Instance.Service = new CalendarService(new Google.Apis.Services.BaseClientService.Initializer() { HttpClientInitializer = credential }); if (credential.Token.Issued.AddSeconds(credential.Token.ExpiresInSeconds.Value) < DateTime.Now.AddMinutes(-1)) { log.Debug("Access token needs refreshing."); //This will happen automatically when using the calendar service //But we need a valid token before we call getGaccountEmail() which doesn't use the service GoogleOgcs.Calendar.Instance.Service.Settings.Get("useKeyboardShortcuts").Execute(); log.Debug("Access token refreshed."); } getGaccountEmail(credential.Token.AccessToken); }
public async Task <ActionResult> YouTubeViewUploads(CancellationToken cancellationToken) { UserCredential credential; string cs = System.Web.HttpContext.Current.Server.MapPath("~/client_secrets_testWebApplication.json"); using (var stream = new FileStream(cs, FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, // This OAuth 2.0 access scope allows an application to upload files to the // authenticated user's YouTube channel, but doesn't allow other types of access. new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload }, User.Identity.Name, CancellationToken.None ); } //check scope with this URL //https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={ACCESS-TOKEN} // This bit checks if the token is out of date, // and refreshes the access token using the refresh token. //if (credential.Token.IsExpired(SystemClock.Default)) //{ // if (!await credential.RefreshTokenAsync(CancellationToken.None)) // { // Console.WriteLine("No valid refresh token."); // } //} //var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken); //if (result.Credential != null) { var youTubeChannels = new List <YouTubeChannel>(); var service = new YouTubeService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = this.ApplicationName }); // Grab users owned channels var channelListRequest = service.Channels.List("snippet,contentDetails"); channelListRequest.Mine = true; var channelListResponse = await channelListRequest.ExecuteAsync(); foreach (var channel in channelListResponse.Items) { var youTubeChannel = new YouTubeChannel(channel); // Grab the ID of the Upload List from the channel var uploadListId = channel.ContentDetails.RelatedPlaylists.Uploads; // Fetch the videos belonging to the Upload List - We'll have to use paging here var nextPageToken = string.Empty; while (nextPageToken != null) { var playlistItemsListRequest = service.PlaylistItems.List("snippet"); playlistItemsListRequest.PlaylistId = uploadListId; playlistItemsListRequest.MaxResults = 50; playlistItemsListRequest.PageToken = nextPageToken; var playlistItemsResponse = await playlistItemsListRequest.ExecuteAsync(); foreach (var playlistItem in playlistItemsResponse.Items) { youTubeChannel.Videos.Add(new YouTubeVideo(playlistItem)); } nextPageToken = playlistItemsResponse.NextPageToken; } youTubeChannels.Add(youTubeChannel); } return(View(youTubeChannels)); } // else // { // return new RedirectResult(result.RedirectUri); // } }
static string ApplicationName = "MinuProjekt"; // KORREKTNE PROJEKTI NIMI PEAB OLEMA static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "*****@*****.**", // OMA GMAIL AADRESS SIIA!!! CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // FAILI UPLOAD var body = new Google.Apis.Drive.v3.Data.File(); body.Name = Path.GetFileName("blah.txt"); byte[] byteArray = System.IO.File.ReadAllBytes("blah.txt"); System.IO.MemoryStream uploadStream = new System.IO.MemoryStream(byteArray); try { FilesResource.CreateMediaUpload request = service.Files.Create(body, uploadStream, "text/plain"); var y = request.Upload(); var x = request.ResponseBody; // SIIA BREAKPOINT KUI VIGU ON JA KONTROLLI y VÄÄRTUST } catch (Exception e) { Console.WriteLine(e); } // FAILIDE LOEND FilesResource.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 10; listRequest.Fields = "nextPageToken, files(id, name)"; // List files. IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files; Console.WriteLine("Files:"); if (files != null && files.Count > 0) { foreach (var file in files) { Console.WriteLine("{0} ({1})", file.Name, file.Id); } } else { Console.WriteLine("No files found."); } Console.Read(); }
//private readonly IDataStore dataStore = new FileDataStore(GoogleWebAuthorizationBroker.Folder); //private async Task<UserCredential> GetCredentialForApiAsync() //{ // var initializer = new GoogleAuthorizationCodeFlow.Initializer // { // ClientSecrets = new ClientSecrets // { // ClientId = MyClientSecrets.ClientId, // ClientSecret = MyClientSecrets.ClientSecret, // }, // Scopes = CalendarScopes.Scopes, // }; // var flow = new GoogleAuthorizationCodeFlow(initializer); // var identity = await HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync( // DefaultAuthenticationTypes.ApplicationCookie); // var userId = identity.FindFirstValue(MyClaimTypes.GoogleUserId); // var token = await dataStore.GetAsync<TokenResponse>(userId); // return new UserCredential(flow, userId, token); //} public ActionResult UpcomingEvents() { UserCredential credential; string credPath1 = @"~\Documents\credentials.json"; using (var stream = new FileStream(Server.MapPath(credPath1), FileMode.Open, FileAccess.ReadWrite)) { string credPath = Server.MapPath(@"~\Documents\token.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, CalendarScopes.Scopes, "user", CancellationToken.None, new FileDataStore(credPath, false)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); //const int MaxEventsPerCalendar = 20; //const int MaxEventsOverall = 50; var model = new UpcomingEventsViewModel(); // Fetch the list of calendars. //var calendars = service.CalendarList.List().Execute(); //Fetch some events from each calendar. //var fetchTasks = new List<Task<Google.Apis.Calendar.v3.Data.Events>>(calendars.Items.Count); //foreach (var calendar in calendars.Items) //{ // var request = service.Events.List(calendar.Id); // request.MaxResults = MaxEventsPerCalendar; // request.SingleEvents = true; // request.TimeMin = DateTime.Now; // fetchTasks.Add(request.Execute()); //} //var fetchResults = fetchTasks; //Sort the events and put them in the model. //var upcomingEvents = from result in fetchResults // from evt in result.Items // where evt.Start != null // let date = evt.Start.DateTime.HasValue ? // evt.Start.DateTime.Value.Date : // DateTime.ParseExact(evt.Start.Date, "yyyy-MM-dd", null) // let sortKey = evt.Start.DateTimeRaw ?? evt.Start.Date // orderby sortKey // select new { evt, date }; //var eventsByDate = from result in upcomingEvents.Take(MaxEventsOverall) // group result.evt by result.date into g // orderby g.Key // select g; //var eventGroups = new List<CalendarEventGroup>(); //foreach (var grouping in eventsByDate) //{ // eventGroups.Add(new CalendarEventGroup // { // GroupTitle = grouping.Key.ToLongDateString(), // Events = grouping, // }); //} // model.EventGroups = eventGroups; return(View(model)); }
public async Task GetEmails(string emailAddr = "*****@*****.**", string label = "ARK/ArkTrading") { try { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, // This OAuth 2.0 access scope allows for read-only access to the authenticated // user's account, but not other types of account access. new[] { GmailService.Scope.GmailReadonly }, "user", CancellationToken.None, new FileDataStore(this.GetType().ToString()) ); } var gmailService = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = this.GetType().ToString() }); var emailListRequest = gmailService.Users.Messages.List(emailAddr); //emailListRequest.LabelIds = label; emailListRequest.IncludeSpamTrash = false; //emailListRequest.Q = "is:unread"; // This was added because I only wanted unread emails... // Get our emails var emailListResponse = await emailListRequest.ExecuteAsync(); if (emailListResponse != null && emailListResponse.Messages != null) { // Loop through each email and get what fields you want... foreach (var email in emailListResponse.Messages) { var emailInfoRequest = gmailService.Users.Messages.Get(emailAddr, email.Id); // Make another request for that email id... var emailInfoResponse = await emailInfoRequest.ExecuteAsync(); if (emailInfoResponse != null) { String from = ""; String date = ""; String subject = ""; String body = ""; // Loop through the headers and get the fields we need... foreach (var mParts in emailInfoResponse.Payload.Headers) { if (mParts.Name == "Date") { date = mParts.Value; } else if (mParts.Name == "From") { from = mParts.Value; } else if (mParts.Name == "Subject") { subject = mParts.Value; } if (date != "" && from != "") { if (emailInfoResponse.Payload.Parts == null && emailInfoResponse.Payload.Body != null) { body = emailInfoResponse.Payload.Body.Data; } else { body = getNestedParts(emailInfoResponse.Payload.Parts, ""); } // Need to replace some characters as the data for the email's body is base64 String codedBody = body.Replace("-", "+"); codedBody = codedBody.Replace("_", "/"); byte[] data = Convert.FromBase64String(codedBody); body = Encoding.UTF8.GetString(data); // Now you have the data you want... } } } } } } catch (Exception ex) { //MessageBox.Show("Failed to get messages!", "Failed Messages!", MessageBoxButtons.OK); } }
private void buttonDelVisits_Click(object sender, EventArgs e) { /// DELETE EVENTS WHERE DATE IS LOWER THAN TODAY DATE string[] files = Directory.GetFiles(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)); foreach (string file in files) { Match match = Regex.Match(file, @".mevent", RegexOptions.IgnoreCase); if (match.Success) { DateTime todayDate = DateTime.Now; int TDay = todayDate.Day; int TMonth = todayDate.Month; int TYear = todayDate.Year; TextReader Load = new StreamReader(file); Load.ReadLine(); string Eyear = Load.ReadLine(); int NYear = Convert.ToInt32(Eyear); Dictionary <string, int> Months = new Dictionary <string, int>(); Months.Add("January", 1); Months.Add("February", 2); Months.Add("March", 3); Months.Add("April", 4); Months.Add("May", 5); Months.Add("June", 6); Months.Add("July", 7); Months.Add("August", 8); Months.Add("September", 9); Months.Add("October", 10); Months.Add("November", 11); Months.Add("December", 12); string EMonth = Load.ReadLine(); string EDay = Load.ReadLine(); int NMonth = Months[EMonth]; int NDay = Convert.ToInt32(EDay); Load.ReadLine(); Load.ReadLine(); Load.ReadLine(); string Name = Load.ReadLine(); Load.Close(); string Npath = file; if (TYear >= NYear && TMonth >= NMonth && TDay >= NMonth) { /// DELETE EVENT FILE File.Delete(Npath); /// DELETE EVENT FROM GOOGLE CALENDAR string[] Scopes = { CalendarService.Scope.Calendar }; string ApplicationName = "MyCalendar Google Calendar API"; UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); String calendarId = "primary"; String eventId = Eyear + EMonth + EDay; service.Events.Delete(calendarId, eventId); SettingsMessageBox Message = new SettingsMessageBox(); Message.Text = "Outdated visits deleted!"; Message.Show(); } else { SettingsMessageBox Message = new SettingsMessageBox(); Message.Text = "No outdated visits to delete!"; Message.Show(); } } } }
static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); //credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Sheets API service. var service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define request parameters. String spreadsheetId = "14g46VAUsxqAkevmNDKdrc0c5R3L1cOfN6PsBYz_2zf0"; String range = "A2:D"; SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range); // Prints the names and majors of students in a sample spreadsheet: // https://docs.google.com/spreadsheets/d/14g46VAUsxqAkevmNDKdrc0c5R3L1cOfN6PsBYz_2zf0/edit ValueRange response = request.Execute(); IList <IList <Object> > values = response.Values; if (values != null && values.Count > 0) { foreach (var row in values) { // Print columns A and D, which correspond to indices 0 and 3. //Console.WriteLine("{0},{1},{2},{3}", row[0], row [1], row[2], row[3]); //Send data to sqlServer Database "InventoryTest" //change Data Source to name of server //use on desktop SqlConnection inv = new SqlConnection("Data Source=ALEX-PC; Initial Catalog=InventoryTest;Integrated Security=True;Pooling=False"); SqlConnection inv = new SqlConnection("Data Source=DESKTOP-VB076EU;Initial Catalog=InventoryTest;Integrated Security=True"); { //Attempt to get the EmployeeID //String that sets the employee name for current row string employeeName = row[3].ToString(); //opens connection to server inv.Open(); //sql command that selects the employeeID SqlCommand getEmployeeID = new SqlCommand("SELECT EmployeeID FROM Employees WHERE EmployeeName = '" + employeeName + "';", inv); //sets the employeeID to the ID that was grabbed from getEmployeeID command int employeeID = Convert.ToInt32(getEmployeeID.ExecuteScalar()); //closes connection inv.Close(); //Attempt to insert part from the Google Sheet SqlCommand insertPart = new SqlCommand("insert into PartsAdded(EntryTime, PartNumber, Quantity, EmployeeID, EmployeeName)" + "values(CURRENT_TIMESTAMP," + "@PartNumber," + "@Quantity," + "@EmployeeID," + "@EmployeeName)", inv); //inserts values within sql command insertPart.Parameters.AddWithValue("@PartNumber", row[1]); insertPart.Parameters.AddWithValue("@Quantity", row[2]); insertPart.Parameters.AddWithValue("@EmployeeID", employeeID); insertPart.Parameters.AddWithValue("@EmployeeName", row[3]); //verifies user the parameter is working Console.WriteLine("InsParams Working"); //opens the inv then executes nonquery then closes connection inv.Open(); Console.WriteLine("inv opened"); insertPart.ExecuteNonQuery(); Console.WriteLine("NonQuery Executed"); inv.Close(); Console.WriteLine("inv closed"); } } } else { Console.WriteLine("No data found."); } Console.Read(); }
private List <Treasure> GetTable(List <Treasure> treasure) { // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/sheets.googleapis.com-dotnet-quickstart.json string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly }; string ApplicationName = "Google Sheets API .NET Quickstart"; UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read) ) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = System.IO.Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Sheets API service. var service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define request parameters. String spreadsheetId = "1wkCt0YfEe7nPtCixij5zR66vZubmw7K21q7r07b1EBI"; String range = "Items!A2:K"; SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range); // Prints the names and majors of students in a sample spreadsheet: // https://docs.google.com/spreadsheets/d/1wkCt0YfEe7nPtCixij5zR66vZubmw7K21q7r07b1EBI/edit ValueRange response = request.Execute(); IList <IList <Object> > values = response.Values; treasure = new List <Treasure>(); if (values != null && values.Count > 0) { Console.WriteLine("Importing data"); foreach (var row in values) { if ((string)row[4] == "") { row[4] = 0; } switch (Convert.ToString(row[2])) { case "Weapon": treasure.Add(new Weapon(row)); break; case "Armor": treasure.Add(new Armor(row)); break; case "Trinket": treasure.Add(new Trinket(row)); break; default: break; } } } else { Console.WriteLine("No data found."); } return(treasure); }
static string scvAccountKey = "notasecret"; //default key by google static void Main(string[] args) { try { #region [ Google User Creds ] UserCredential userCredential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; userCredential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } #endregion // Create Google Calendar API service. var sservice = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = userCredential, ApplicationName = ApplicationName, }); var calendar = sservice.Events.List(publicCalendarId); //only get 2020 events calendar.TimeMin = new DateTime(2019, 12, 31); calendar.TimeMax = new DateTime(2021, 01, 01); var holidayCalendar = calendar.Execute(); var holidayData = holidayCalendar.Items.ToList(); #region [ Google Service Account Creds ] var certificate = new X509Certificate2(@"key.p12", scvAccountKey, X509KeyStorageFlags.Exportable); ServiceAccountCredential svcAccCredential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountName) { Scopes = Scopes }.FromCertificate(certificate)); var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = svcAccCredential, ApplicationName = ApplicationName, }); #endregion var defaultCalendar = service.CalendarList.List().Execute().Items.FirstOrDefault(); foreach (var day in holidayData) { var holidayEvent = service.Events.Insert(new Event() { Created = DateTime.UtcNow, Start = new EventDateTime() { Date = day.Start.Date }, End = new EventDateTime() { Date = day.End.Date }, Summary = "Holiday", Location = "TR", Description = day.Summary, }, defaultCalendar.Id); var eventResponse = holidayEvent.Execute(); } } catch (Exception ex) { throw; } }
private async Task AccessPlaylist() { UserCredential credential; using (var stream = new FileStream(@"C:\client_id.json", FileMode.Open, FileAccess.Read)) { credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, // This OAuth 2.0 access scope allows for read-only access to the authenticated // user's account, but not other types of account access. new[] { YouTubeService.Scope.YoutubeReadonly }, "psangat", CancellationToken.None, new FileDataStore(this.GetType().ToString()) ); } var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = this.GetType().ToString() }); var playlists = youtubeService.Playlists.List("snippet"); playlists.PageToken = ""; playlists.MaxResults = 50; playlists.Mine = true; PlaylistListResponse presponse = await playlists.ExecuteAsync(); foreach (var currentPlayList in presponse.Items) { if (currentPlayList.Snippet.Title.Equals("Songs")) { PlaylistItemsResource.ListRequest listRequest = youtubeService.PlaylistItems.List("contentDetails"); listRequest.MaxResults = 50; listRequest.PlaylistId = currentPlayList.Id; listRequest.PageToken = playlists.PageToken; var response = await listRequest.ExecuteAsync(); var index = 1; foreach (var playlistItem in response.Items) { VideosResource.ListRequest videoR = youtubeService.Videos.List("snippet, contentDetails, status"); videoR.Id = playlistItem.ContentDetails.VideoId; var responseV = await videoR.ExecuteAsync(); if (responseV.Items.Count > 0) { string link = String.Format("https://www.youtube.com/watch?v={0}&list={1}&index={2}", videoR.Id, currentPlayList.Id, index); IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link); try { VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 0 && !String.IsNullOrEmpty(info.Title)); Console.WriteLine("Downloading {0}", video.Title); if (video.RequiresDecryption) { DownloadUrlResolver.DecryptDownloadUrl(video); } using (var progress = new ProgressBar()) { for (int i = 0; i <= 100; i++) { progress.Report((double)i / 100); Thread.Sleep(20); } } var audioDownloader = new VideoDownloader(video, Path.Combine(@"C:\Users\prsangat\Desktop\Songs", video.Title + ".mp3")); using (var progress = new ProgressBar()) { audioDownloader.DownloadProgressChanged += (sender, args) => progress.Report(args.ProgressPercentage); } //audioDownloader.DownloadProgressChanged += (sender, args) => progre//Console.Write( "\r{0}% ", Math.Round(args.ProgressPercentage)); audioDownloader.Execute(); Console.WriteLine("Download Complete."); } catch (Exception ex) { Console.WriteLine(); Console.WriteLine(ex.ToString()); Console.WriteLine(); // throw; } index++; } } playlists.PageToken = response.NextPageToken; } } }
/// <summary> /// Čtení událostí z kalendáře /// https://developers.google.com/calendar/quickstart/dotnet /// </summary> public void ReadFutureCalendarItems() { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. var credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; //Console.WriteLine($"Credential file saved to: {credPath}"); } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. EventsResource.ListRequest request = service.Events.List("*****@*****.**"); request.TimeMin = DateTime.Now.Date; request.TimeMax = DateTime.Now.Date.AddDays(8); request.ShowDeleted = false; request.SingleEvents = true; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // List events. Events events = request.Execute(); logger.Info("Načtené události"); if (events.Items != null && events.Items.Count > 0) { var scheduledEvents = new List <ScheduledEvent>(); foreach (var eventItem in events.Items) { if (eventItem.Start.DateTime == null || eventItem.End.DateTime == null) { continue; } scheduledEvents.Add(new ScheduledEvent { Name = GetEventName(eventItem.Summary), TimeFrom = (DateTime)eventItem.Start.DateTime, TimeTo = (DateTime)eventItem.End.DateTime, EventType = GetEventType(eventItem.Summary) }); logger.Info($"{eventItem.Summary} ({eventItem.Start.DateTime.ToString()})"); } File.WriteAllText(_applicationConfig.EventsFilePath, JsonConvert.SerializeObject(scheduledEvents, Formatting.Indented), Encoding.UTF8); } else { logger.Info("V rezervačním systému nebyly nalezeny žádné budoucí události"); } }
static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("creds.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. FilesResource.ListRequest listRequest = service.Files.List(); listRequest.PageSize = 10; //listRequest.Fields = "nextPageToken, files(id, name)"; listRequest.Fields = "nextPageToken, files(*)"; //listRequest.Q = "'1SCrpFATrqiw6V59tE4CSlBX_KMwxypG3' in parents"; //listRequest.Spaces = "photos"; //listRequest.Q = "mimeType='application/vnd.google-apps.folder' and '1SCrpFATrqiw6V59tE4CSlBX_KMwxypG3' in parents"; Console.WriteLine("Files:"); do { // List files. IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute() .Files; if (files != null && files.Count > 0) { foreach (var file in files) { //if (file.MimeType.Equals("application/vnd.google-apps.folder")) { Console.WriteLine("{0} -- ({1})", file.Name, file.Id); } } } else { Console.WriteLine("No files found."); } listRequest.PageToken = listRequest.Execute().NextPageToken; }while (!string.IsNullOrEmpty(listRequest.PageToken)); Console.WriteLine("Any key to exit..."); Console.Read(); }
private void Invio_DoWork(object sender, DoWorkEventArgs e) { string utente, passwordUtente, id; string cartella = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); StreamReader sr = new StreamReader(cartella + "\\LibroSoci\\sms.ini"); try { string tmp = sr.ReadLine(); sr.Close(); string[] parti = tmp.Split(';'); id = parti[0]; utente = parti[1]; passwordUtente = parti[2]; int contaInviati = 1; info.Text = "Richiesta autorizzazione Gmail..."; UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } if (credential.Token.IsExpired(credential.Flow.Clock)) { if (credential.RefreshTokenAsync(CancellationToken.None).Result) { info.Text = "Accesso a Gmail ottenuto"; } else { info.Text = "Accesso a Gmail negato"; } } else { info.Text = "Accesso a Gmail ottenuto"; } var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); Google.Apis.Oauth2.v2.Oauth2Service oauthService = new Google.Apis.Oauth2.v2.Oauth2Service(new BaseClientService.Initializer() { HttpClientInitializer = credential }); Google.Apis.Oauth2.v2.Data.Userinfoplus userInfo = oauthService.Userinfo.Get().ExecuteAsync().Result; string userMail = userInfo.Email; string userName = userInfo.Name; info.Text = "Invio sms in corso..."; try { MailMessage mail = new MailMessage(); mail.From = new MailAddress(userMail); mail.To.Add("*****@*****.**"); StringBuilder st = new StringBuilder(); st.AppendLine("api_id:" + id); st.AppendLine("user:"******"password:"******"to:+39" + cellulari[i]); } st.AppendLine("text:" + txtMessaggio.Text); st.AppendLine("reply:" + userMail); mail.Body = st.ToString(); MimeMessage message = MimeMessage.CreateFromMailMessage(mail); var result = service.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message { Raw = Base64UrlEncode(message.ToString()) }, "me").Execute(); info.Text = "SMS inviati"; contaInviati++; MessageBox.Show("SMS inviati correttamente"); } catch { MessageBox.Show("Errore durante l'invio"); info.Text = ""; } } catch (Exception ex) { MessageBox.Show("Errore " + ex.Message + ex.Data, "Errore invio", MessageBoxButtons.OK, MessageBoxIcon.Error); }; }
static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Get all calendar IDs List <string> calendarIds = new List <string>(); CalendarList calendars = service.CalendarList.List().Execute(); foreach (var calendar in calendars.Items) { calendarIds.Add(calendar.Id); } // Get events of IDs List <Event> eventItems = new List <Event>(); foreach (var id in calendarIds) { // Define parameters of request. EventsResource.ListRequest request = service.Events.List(id); request.TimeMin = DateTime.Now; request.MaxResults = resultsCount; request.ShowDeleted = false; request.SingleEvents = true; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // List events. Events events = request.Execute(); eventItems.AddRange(events.Items); } // Get correct count of events in order eventItems = eventItems.OrderBy(eventItem => { string startDate = eventItem.Start.Date; string startDateTimeRaw = eventItem.Start.DateTimeRaw; return(DateTime.Parse(string.IsNullOrEmpty(startDate) ? startDateTimeRaw : startDate)); }).ToList(); eventItems.RemoveRange(resultsCount, eventItems.Count - resultsCount); // Show events if (eventItems != null && eventItems.Count > 0) { string currentDate = null; foreach (var eventItem in eventItems) { bool isAllDay = true; string startDate = eventItem.Start.Date; // Date only available in DateTimeRaw if not all day if (String.IsNullOrEmpty(startDate)) { startDate = eventItem.Start.DateTimeRaw; isAllDay = false; } startDate = DateTime.Parse(startDate).ToString("dddd, dd MMMM yyyy"); if (startDate != currentDate) { if (currentDate != null) { Console.WriteLine(""); } currentDate = startDate; Console.WriteLine(currentDate); } string time = ""; if (!isAllDay) { DateTime?startTime = eventItem.Start.DateTime; DateTime?endTime = eventItem.End.DateTime; time = string.Format( "({0} - {1})", startTime.Value.ToShortTimeString(), endTime.Value.ToShortTimeString() ); } Console.WriteLine(" {0} {1}", eventItem.Summary, time); } } else { Console.WriteLine("No upcoming events found."); } Console.Read(); }
public async System.Threading.Tasks.Task eMailForLocalTimeAsync() { String localTimeNowFormatted = getFormattedTime(DateTime.Now); TimeTeller.GetResult(TimeZones.LOCAL, TimeFormatting.NUMERIC, true); Boolean foundEmailSent = false; // Shamelessly Using code samples from https://developers.google.com/gmail/api/quickstart/dotnet // and https://stackoverflow.com/questions/36448193/how-to-retrieve-my-gmail-messages-using-gmail-api // If modifying these scopes, delete your previously saved credentials // at ~/.credentials/gmail-dotnet-quickstart.json string[] Scopes = { GmailService.Scope.GmailReadonly }; string ApplicationName = "Gmail API .NET Quickstart"; UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Gmail API service. var gmailService = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); var emailListRequest = gmailService.Users.Messages.List("*****@*****.**"); emailListRequest.LabelIds = "INBOX"; emailListRequest.IncludeSpamTrash = false; //emailListRequest.Q = "is:unread"; //this was added because I only wanted undread email's... //get our emails var emailListResponse = await emailListRequest.ExecuteAsync(); if (emailListResponse != null && emailListResponse.Messages != null) { //loop through each email and get what fields you want... foreach (var email in emailListResponse.Messages) { var emailInfoRequest = gmailService.Users.Messages.Get("*****@*****.**", email.Id); //make another request for that email id... var emailInfoResponse = await emailInfoRequest.ExecuteAsync(); if (emailInfoResponse != null) { String from = ""; String date = ""; String subject = ""; String body = ""; //loop through the headers and get the fields we need... foreach (var mParts in emailInfoResponse.Payload.Headers) { if (mParts.Name == "Date") { date = mParts.Value; } else if (mParts.Name == "From") { from = mParts.Value; } else if (mParts.Name == "Subject") { subject = mParts.Value; } if (date != "" && from != "") { if (emailInfoResponse.Payload.Parts == null && emailInfoResponse.Payload.Body != null) { body = emailInfoResponse.Payload.Body.Data; } else { body = getNestedParts(emailInfoResponse.Payload.Parts, ""); } //need to replace some characters as the data for the email's body is base64 String codedBody = body.Replace("-", "+"); codedBody = codedBody.Replace("_", "/"); byte[] data = Convert.FromBase64String(codedBody); body = Encoding.UTF8.GetString(data); if (body.Equals("The time is now " + localTimeNowFormatted + "\r\n\r\n")) { foundEmailSent = true; } } } } } } Assert.True(foundEmailSent); }
// 구글 캘린더 스레드 함수 public void GoogleCalendar() { while (!isArClientConnected || !isArServerConnected) { Thread.Sleep(1000); // 캘린더 스레드는 AR 프로그램의 연결을 기다린다. } int loopCount = 0; while (true) { // 구글 캘린더 계정 인증 UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/calendar-dotnot-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; //WriteTextBox2("Credential file saved to: " + credPath); } // 구글 캘린더 API 서비스 생성 var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // 리퀘스트 생성 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; // 이벤트 수신 Events events = request.Execute(); //WriteTextBox2("Upcoming events >>"); if (events.Items != null && events.Items.Count > 0) // 이벤트(일정)이 있을 경우 { foreach (var eventItem in events.Items) { string when = eventItem.Start.DateTime.ToString(); if (String.IsNullOrEmpty(when)) // 일정 시간이 종일로 설정되어 있을 경우 { when = eventItem.Start.Date; DateTime dateTime; // 일정 시간 파싱 if (DateTime.TryParse(when, out dateTime)) { TimeSpan timeDiff = dateTime - DateTime.Now; //WriteTextBox2(eventItem.Id + " _ " + eventItem.Summary + " // Min diff: " + timeDiff.TotalMinutes); // 남은 시간이 1시간 이내일 경우 if (0 <= timeDiff.TotalMinutes && timeDiff.TotalMinutes <= 60) { bool isItemExist = false; foreach (string eventIdItem in eventIdList) // 이미 전송한 알림인지 확인 { if (eventItem.Id.Equals(eventIdItem)) { isItemExist = true; break; } } if (isItemExist) // 이미 전송한 알림이라면 { // Pass } else // 아직 전송하지 않은 알림이라면 { eventIdList.Add(eventItem.Id); // 전송한 알림으로 등록하고 SendCalendarAlarmToAr(eventItem.Summary, when); // 캘린더 알림 AR로 전송 } } } else { WriteTextBox2("Date Error"); } } else // 일정이 정확한 시간이 설정되어 있을 경우 { DateTime dateTime = eventItem.Start.DateTime.Value; TimeSpan timeDiff = dateTime - DateTime.Now; //WriteTextBox2(eventItem.Id + " _ " + eventItem.Summary + " // Min diff: " + timeDiff.TotalMinutes); // 남은 시간이 1시간 이내일 경우 if (0 <= timeDiff.TotalMinutes && timeDiff.TotalMinutes <= 60) { bool isItemExist = false; foreach (string eventIdItem in eventIdList) // 이미 전송한 알림인지 확인 { if (eventItem.Id.Equals(eventIdItem)) { isItemExist = true; break; } } if (isItemExist) // 이미 전송한 알림이라면 { // Pass } else // 아직 전송하지 않은 알림이라면 { eventIdList.Add(eventItem.Id); // 전송한 알림으로 등록하고 SendCalendarAlarmToAr(eventItem.Summary, when); // 캘린더 알림 AR로 전송 } } } } } else // 일정이 없을 경우 { //MessageBox.Show("No upcoming events found."); } loopCount++; // 저장된 이벤트 id 리스트를 검사해서 쓸모없어진 것들을 제거 if (loopCount >= 60) // 1시간에 1번씩 검사 { if (events.Items != null && events.Items.Count > 0) { foreach (string idItem in eventIdList) { bool isIdExist = false; foreach (var eventItem in events.Items) { if (idItem.Equals(eventItem.Id)) { isIdExist = true; break; } } // id가 더 이상 존재하지 않으면 삭제 if (!isIdExist) { eventIdList.Remove(idItem); } } } loopCount = 0; } Thread.Sleep(60000); // 1분에 한번씩 캘린더 일정을 검사 } }
private async Task <bool> getAuthenticated(ClientSecrets cs) { log.Debug("Authenticating with Google calendar service..."); FileDataStore tokenStore = new FileDataStore(Program.UserFilePath); tokenFullPath = Path.Combine(tokenStore.FolderPath, TokenFile); log.Debug("Google credential file location: " + tokenFullPath); if (!tokenFileExists) { log.Info("No Google credentials file available - need user authorisation for OGCS to manage their calendar."); } string[] scopes = new[] { "https://www.googleapis.com/auth/calendar", "email" }; UserCredential credential = null; try { //This will open the authorisation process in a browser, if required credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(cs, scopes, "user", CancelTokenSource.Token, tokenStore); if (tokenFileExists) { log.Debug("User has provided authorisation and credential file saved."); } } catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException ex) { //OGCSexception.AnalyseTokenResponse(ex); if (ex.Error.Error == "access_denied") { String noAuthGiven = "Sorry, but this application will not work if you don't allow it access to your Google Calendar :("; log.Warn("User did not provide authorisation code. Sync will not be able to work."); OgcsMessageBox.Show(noAuthGiven, "Authorisation not given", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); throw new ApplicationException(noAuthGiven); } else { Forms.Main.Instance.Console.UpdateWithError("Unable to authenticate with Google. The following error occurred:", ex); } } catch (OperationCanceledException) { Forms.Main.Instance.Console.Update("Unable to authenticate with Google. The operation was cancelled.", Console.Markup.warning); } catch (System.Exception ex) { OGCSexception.Analyse(ex); Forms.Main.Instance.Console.UpdateWithError("Unable to authenticate with Google. The following error occurred:", ex); } if (credential.Token.AccessToken != "" && credential.Token.RefreshToken != "") { log.Info("Refresh and Access token successfully retrieved."); log.Debug("Access token expires " + credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value).ToLocalTime().ToString()); } GoogleOgcs.Calendar.Instance.Service = new CalendarService(new Google.Apis.Services.BaseClientService.Initializer() { HttpClientInitializer = credential }); if (Settings.Instance.Proxy.Type == "Custom") { GoogleOgcs.Calendar.Instance.Service.HttpClient.DefaultRequestHeaders.Add("user-agent", Settings.Instance.Proxy.BrowserUserAgent); } if (credential.Token.IssuedUtc.AddSeconds(credential.Token.ExpiresInSeconds.Value) < DateTime.UtcNow.AddMinutes(-1)) { log.Debug("Access token needs refreshing."); //This will happen automatically when using the calendar service //But we need a valid token before we call getGaccountEmail() which doesn't use the service int backoff = 0; while (backoff < Calendar.BackoffLimit) { try { GoogleOgcs.Calendar.Instance.Service.Settings.Get("useKeyboardShortcuts").Execute(); break; } catch (Google.GoogleApiException ex) { switch (Calendar.HandleAPIlimits(ref ex, null)) { case Calendar.ApiException.throwException: throw; case Calendar.ApiException.freeAPIexhausted: OGCSexception.LogAsFail(ref ex); OGCSexception.Analyse(ex); System.ApplicationException aex = new System.ApplicationException(Calendar.Instance.SubscriptionInvite, ex); OGCSexception.LogAsFail(ref aex); authenticated = false; return(authenticated); case Calendar.ApiException.backoffThenRetry: backoff++; if (backoff == Calendar.BackoffLimit) { log.Fail("API limit backoff was not successful. Retrieving useKeyboardShortcuts setting failed."); authenticated = false; return(authenticated); } else { log.Warn("API rate limit reached. Backing off " + backoff + "sec before retry."); System.Threading.Thread.Sleep(backoff * 1000); } break; } } catch (System.Exception ex) { if (ex is Google.Apis.Auth.OAuth2.Responses.TokenResponseException) { OGCSexception.AnalyseTokenResponse(ex as Google.Apis.Auth.OAuth2.Responses.TokenResponseException, false); } else { OGCSexception.Analyse(ex); Forms.Main.Instance.Console.Update("Unable to communicate with Google services. " + (ex.InnerException != null ? ex.InnerException.Message : ex.Message), Console.Markup.warning); } authenticated = false; return(authenticated); } } log.Debug("Access token refreshed."); } getGaccountEmail(credential.Token.AccessToken); authenticated = true; Forms.Main.Instance.Console.Update("Handshake successful.", verbose: true); return(authenticated); }
public static SheetsService CreateGoogleSheets(string sheetName) { UserCredential credential; string[] Scopes = { SheetsService.Scope.Spreadsheets }; string ApplicationName = "Google Sheets API Quickstart"; try { using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/sheets.googleapis.com-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Sheets API service. var service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); String range = "Class Data!A2:E"; #region Add sheet into existing spreadsheet // Add new Sheet //sheetName = sheetName; //var addSheetRequest = new AddSheetRequest(); //addSheetRequest.Properties = new SheetProperties(); //addSheetRequest.Properties.Title = sheetName; //BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest(); //batchUpdateSpreadsheetRequest.Requests = new List<Request>(); //batchUpdateSpreadsheetRequest.Requests.Add(new Request //{ // AddSheet = addSheetRequest //}); //var batchUpdateRequest = // service.Spreadsheets.BatchUpdate(batchUpdateSpreadsheetRequest, spreadsheetId); //batchUpdateRequest.Execute(); #endregion SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadSheetId, range); return(service); //This code (Below 4 lines) creates new spreadsheets //var myNewSheet = new Google.Apis.Sheets.v4.Data.Spreadsheet(); //myNewSheet.Properties = new SpreadsheetProperties(); //myNewSheet.Properties.Title = "Pool Data Sheet"; //var awsomNewSheet = service.Spreadsheets.Create(myNewSheet).Execute(); } catch (Exception ex) { return(null); } }
static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Gmail API service. var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); //==================================================================================== //[1] GET LABELS OF EMAIL #region // Define parameters of request. //UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me"); //// List labels. //IList<Label> labels = request.Execute().Labels; //Console.WriteLine("Labels:"); //if (labels != null && labels.Count > 0) //{ // foreach (var labelItem in labels) // { // Console.WriteLine("{0}", labelItem.Name); // } //} //else //{ // Console.WriteLine("No labels found."); //} ////Console.Read(); #endregion //==================================================================================== //[2] GET TOP 100 EMAILS #region //var inboxlistRequest = service.Users.Messages.List("me"); //inboxlistRequest.LabelIds = "INBOX"; //inboxlistRequest.IncludeSpamTrash = false; ////get our emails //var emailListResponse = inboxlistRequest.Execute(); //if (emailListResponse != null && emailListResponse.Messages != null) //{ // //loop through each email and get what fields you want... // foreach (var email in emailListResponse.Messages) // { // var emailInfoRequest = service.Users.Messages.Get("me", email.Id); // var emailInfoResponse = emailInfoRequest.Execute(); // if (emailInfoResponse != null) // { // String from = ""; // String date = ""; // String subject = ""; // //loop through the headers to get from,date,subject, body // foreach (var mParts in emailInfoResponse.Payload.Headers) // { // if (mParts.Name == "Date") // { // date = mParts.Value; // } // else if (mParts.Name == "From") // { // from = mParts.Value; // } // else if (mParts.Name == "Subject") // { // subject = mParts.Value; // } // if (date != "" && from != "") // { // foreach (MessagePart p in emailInfoResponse.Payload.Parts) // { // if (p.MimeType == "text/html") // { // byte[] data = FromBase64ForUrlString(p.Body.Data); // string decodedString = Encoding.UTF8.GetString(data); // } // } // } // } // } // } //} //Console.ReadLine(); #endregion //==================================================================================== //[3] GET LABELS OF EMAIL SendHTMLmessage(service); Console.ReadLine(); }
static void Main(string[] args) { string searchFor = string.Empty; string beforeDate = string.Empty; int batchSize = 100; bool promptMsg = false; if (args.Length == 0) { Console.WriteLine("Usage: [size] [from] [before] [prompt] e.g.: 100 facebook 2014/12/31 true"); return; } try { // call example: 100 facebook 2011/12/31 if (args.Length > 0 && args[0] != null) { Int32.TryParse(args[0], out int newbatchSize); batchSize = newbatchSize > 0 ? newbatchSize : batchSize; } if (args.Length > 1 && (args[1] != null && !string.IsNullOrEmpty(args[1]))) { searchFor = args[1]; } if (args.Length > 2 && args[2] != null && !string.IsNullOrEmpty(args[2]) && DateTime.TryParse(args[2], out DateTime selectedDate)) { beforeDate = args[2]; } if (args.Length > 3 && args[3] != null) { Boolean.TryParse(args[3], out promptMsg); } UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/GMTool.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } string query = string.Empty;//$"is:unread"; if (!string.IsNullOrEmpty(searchFor)) { query += $" from:{searchFor}"; } if (!string.IsNullOrEmpty(beforeDate)) { query += $" before:{beforeDate}"; } Console.WriteLine($"The query is: {query}"); Console.WriteLine("Proceed? (Y/N)"); var readedKey = Console.ReadKey(); if (readedKey.KeyChar.ToString().ToLower() == "n") { return; } // Create Gmail API service. var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); IList <Message> messages; bool doWork = true; int iterator = 0; int batchnum = 0; while (doWork) { batchnum++; UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me"); request.Q = query; // "from:facebook before:2011/12/31"; #if DEBUG request.Q = "from:facebook before:2013/12/31"; #endif request.MaxResults = batchSize; messages = request.Execute().Messages; if (messages != null && messages.Count > 0 && iterator <= batchSize) { Console.WriteLine($"Found: {messages.Count} messages in batch num #{batchnum}."); if (promptMsg) { foreach (var msg in messages) { iterator++; var getRequest = service.Users.Messages.Get("me", msg.Id); var sentMsg = getRequest.Execute(); Console.WriteLine($"{iterator}/{messages.Count} - Msg: {sentMsg.Snippet}"); //UsersResource.MessagesResource.TrashRequest trashRequest = service.Users.Messages.Trash("me", msg.Id); //var result = trashRequest.Execute(); } } else { iterator += messages.Count; } Console.WriteLine($"DELETE ALL {messages.Count} MESSAGES IN CURRENT BATCH? (Y/N) -- !!! WARNING! YOU CANNOT UNDO THIS! !!!"); readedKey = Console.ReadKey(); if (readedKey.KeyChar.ToString().ToLower() == "n") { return; } var batchDeleteReq = new BatchDeleteMessagesRequest { Ids = messages.Select(e => e.Id).ToList() }; var req = service.Users.Messages.BatchDelete(batchDeleteReq, "me"); var batchDeleteResult = req.Execute(); Console.WriteLine($"Deleted {messages.Count} messages in batch num# {batchnum}"); } else { doWork = false; } } Console.WriteLine($"TOTAL Deleted {iterator} messages."); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine($"Exception occured: {ex.Message}"); } }
private async Task PizzaFormComplete(IDialogContext context, IAwaitable <PizzaOrder> result) { PizzaOrder order = null; try { order = await result; } catch (OperationCanceledException) { await context.PostAsync("You canceled the form!"); return; } if (order != null) { await context.PostAsync("Agendamento: " + order.dia.ToString() + " " + order.horario.ToString()); UserCredential credential; string[] Scopes = { CalendarService.Scope.Calendar }; string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; string ApplicationName = "Google Calendar API .NET Quickstart"; var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); Event newEvent = new Event() { //Summary = assuntoAgendamento, Summary = "Cabeleleiro", Location = order.Address, Description = "blablalbalb", Start = new EventDateTime() { DateTime = order.dia.AddHours(1), TimeZone = "America/Los_Angeles", }, End = new EventDateTime() { //DateTime = DateTime.Parse("2017-07-20T17:00:00-07:00"), DateTime = order.dia.AddHours(2), TimeZone = "America/Los_Angeles", }, Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=2" }, Attendees = new EventAttendee[] { new EventAttendee() { Email = "*****@*****.**" }, new EventAttendee() { Email = "*****@*****.**" }, }, Reminders = new Event.RemindersData() { UseDefault = false, Overrides = new EventReminder[] { new EventReminder() { Method = "email", Minutes = 24 * 60 }, new EventReminder() { Method = "sms", Minutes = 10 }, } } }; String calendarId = "primary"; EventsResource.InsertRequest request1 = service.Events.Insert(newEvent, calendarId); Event createdEvent = request1.Execute(); Console.WriteLine("Event created: {0}", createdEvent.HtmlLink); // 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; // List events. Events events = request.Execute(); Console.WriteLine("Upcoming events:"); if (events.Items != null && events.Items.Count > 0) { foreach (var eventItem in events.Items) { string when = eventItem.Start.DateTime.ToString(); if (String.IsNullOrEmpty(when)) { when = eventItem.Start.Date; } Console.WriteLine("{0} ({1})", eventItem.Summary, when); } } else { Console.WriteLine("No upcoming events found."); } Console.Read(); } }
public ActionResult AddEvent(UpcomingEventsViewModel model) { UserCredential credential; string credPath1 = @"~\Documents\credentials.json"; using (var stream = new FileStream(Server.MapPath(credPath1), FileMode.Open, FileAccess.ReadWrite)) { string credPath = Server.MapPath(@"~\Documents\token.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, CalendarScopes.Scopes, "user", CancellationToken.None, new FileDataStore(credPath, false)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); var _event = new Event(); _event.Start = new EventDateTime() { DateTime = DateTime.Parse(model.NewEvent.EventStart.Value.ToLongDateString()), TimeZone = "Asia/Kolkata" }; _event.End = new EventDateTime() { DateTime = DateTime.Parse(model.NewEvent.EventEnd.Value.ToLongDateString()), TimeZone = "Asia/Kolkata" }; var _list = new List <EventAttendee>(); if (model.NewEvent.Attendees[0] == "") { var att = new EventAttendee() { Email = "*****@*****.**" }; _list.Add(att); } else { foreach (var item in model.NewEvent.Attendees[0].Split(',')) { var attendee = new EventAttendee(); attendee.Email = item; _list.Add(attendee); } } _event.Attendees = _list; _event.Description = model.NewEvent.Description; _event.GuestsCanSeeOtherGuests = true; //_event.Location = model.NewEvent.Location; _event.Kind = "calendar#event"; _event.Summary = model.NewEvent.EventName; _event.ColorId = "4"; _event.Reminders = new Event.RemindersData() { UseDefault = false, Overrides = new EventReminder[] { new EventReminder() { Method = "email", Minutes = 24 * 60 } } }; //var result = service.Events.Insert(_event, "*****@*****.**"); EventsResource.InsertRequest request = service.Events.Insert(_event, "*****@*****.**"); Event createdEvent = request.Execute(); db.EventCalendar.Add(model.NewEvent); db.SaveChanges(); return(View("UpcomingEvents")); }
static void Main(string[] args) { System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("cs-CZ");; System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("cs-CZ"); UserCredential credential; //credentials.json created as described in https://developers.google.com/sheets/api/quickstart/dotnet?authuser=2 using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Sheets API service. var service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Podpora-COVID-Update", }); var ds = HlidacStatu.Api.V2.Dataset.Typed.Dataset <pomoc> .OpenDataset(System.Configuration.ConfigurationManager.AppSettings["apikey"], DatasetNameId); //ds.SetDeveleperUrl("http://local.hlidacstatu.cz/api/v1"); // // Define request parameters. String spreadsheetId = "1MtsFm3W8PXkNQ1y0JWYQfb7cl_usCK87nz57uOeI3RM"; String range = "Data!A2:J100"; SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range); ValueRange response = request.Execute(); IList <IList <Object> > values = response.Values; if (values != null && values.Count > 0) { foreach (var row in values .Where(r => r.Count > 6) ) { var p = new pomoc(); if (row[0].ToString().Length > 0) { p.Id = row[0].ToString(); p.ministerstvo = row[1].ToString(); p.typ_pomoci = row[2].ToString(); p.program = row[3].ToString(); p.odhadovana_celkova_vyse_v_mld_kc = decimal.TryParse(row[4].ToString(), out var dd) ? decimal.Parse(row[4].ToString()) : 0; p.vyplacena = decimal.TryParse(row[5].ToString(), out var dd1) ? decimal.Parse(row[5].ToString()) : 0; p.pocet_subjektu = int.Parse(row[6].ToString().Replace(" ", "").Replace(((char)160).ToString(), string.Empty)); p.udaj_ke_dni = DateTime.ParseExact(row[7].ToString(), "d.M.yyyy", System.Globalization.CultureInfo.GetCultureInfo("cs-CZ")); if (row.Count > 8) { p.poznamka = row[8].ToString(); } if (row.Count > 9) { p.url = row[9].ToString(); } if (p.typ_pomoci.Length > 5) { Console.WriteLine(p.Id); var id = ds.AddOrUpdateItem(p, HlidacStatu.Api.V2.Dataset.Typed.ItemInsertMode.rewrite); } } } } else { Console.WriteLine("No data found."); } //Console.Read(); }
static void Main(string[] args) { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Sheets API service. var service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define request parameters. String spreadsheetId = "1xeRwJHbs4T10akqx5LNRQHobx7CQe1_C4PTv_mb3I_E"; String range = "Sheet1!A2:G"; SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range); // Prints the names and majors of students in a sample spreadsheet: // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit ValueRange response = request.Execute(); IList <IList <Object> > values = response.Values; if (values != null && values.Count > 0) { List <DriverModel> drivers = DriverModel.Convert(values); using (var conn = new SqlConnection("Data Source=localhost;Initial Catalog=playground;Integrated Security=True")) { foreach (var driver in drivers) { SqlCommand insert = new SqlCommand("insert into Drivers(DriverID, PayPeriod, Qualify, PaperWork, Expiration, Complaint, UpdateTime) " + "values(@driverId, @payPeriod, @qualify, @paperWork, @expiration, @complaint, @updateTime)", conn); insert.Parameters.AddWithValue("@driverId", driver.DriverID); insert.Parameters.AddWithValue("@payPeriod", driver.PayPeriod); insert.Parameters.AddWithValue("@qualify", driver.Qualify); insert.Parameters.AddWithValue("@paperWork", driver.PaperWork); insert.Parameters.AddWithValue("@expiration", driver.Expiration); insert.Parameters.AddWithValue("@complaint", driver.Complaint); insert.Parameters.AddWithValue("@updateTime", driver.UpdateTime); try { conn.Open(); insert.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine($"Error inserting record for {driver.DriverID} - {ex.Message}"); } finally { conn.Close(); } } } } else { Console.WriteLine("No data found."); } Console.Read(); }
public IActionResult Index() { UserCredential credential; using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "caledemo", }); // 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; // List events. Events events = request.Execute(); // Google calendar data List <AppointmentData> appData = new List <AppointmentData>(); if (events.Items != null && events.Items.Count > 0) { var i = 0; foreach (var eventItem in events.Items) { appData.Add(new AppointmentData { Id = i++, Subject = eventItem.Summary, StartTime = Convert.ToDateTime(eventItem.Start.DateTime), EndTime = Convert.ToDateTime(eventItem.End.DateTime) }); } } //Schedule data List <AppointmentData> scheduleData = new List <AppointmentData>(); scheduleData.Add(new AppointmentData { Id = 100, Subject = "Paris", StartTime = new DateTime(2020, 07, 23, 10, 0, 0), EndTime = new DateTime(2020, 07, 23, 12, 30, 0), }); // Merge both schedule and google calendar data and assign it to the datasource of schedule List <AppointmentData> resultData = new List <AppointmentData>(); resultData = appData.Concat(scheduleData).ToList(); ViewBag.appointments = resultData; return(View()); }
static void Main(string[] args) { UserCredential credential; // If modifying these scopes, delete previously saved token.json string[] Scopes = { DriveService.Scope.DriveReadonly }; string ApplicationName = "########"; string fileId = "########"; string path = @"########"; //Include filename & extension i.e. C:\stuff\sheet001.xlsx var jetStream = new System.IO.MemoryStream(); using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = "token.json"; credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); FilesResource.ExportRequest request = new FilesResource.ExportRequest(service, fileId, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); request.MediaDownloader.ProgressChanged += (Google.Apis.Download.IDownloadProgress progress) => { switch (progress.Status) { case Google.Apis.Download.DownloadStatus.Downloading: { Console.WriteLine(progress.BytesDownloaded); break; } case Google.Apis.Download.DownloadStatus.Completed: { Console.WriteLine("Download complete."); using (System.IO.FileStream file = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { jetStream.WriteTo(file); } break; } case Google.Apis.Download.DownloadStatus.Failed: { Console.WriteLine("Download failed."); break; } } }; request.DownloadWithStatus(jetStream); }
public async Task <ActionResult> CreateActivite(EventsModel eventsModel, int?id, int?idgroupe, bool GAC) { Activites activites = new Activites(); activites.Nom_activ = eventsModel.Title; activites.Objectif_activ = eventsModel.Description; activites.Type_ActiviteID = eventsModel.Type_ActiviteID; activites.Emplacement = eventsModel.Location; activites.AgendaID = eventsModel.AgendaId; activites.DateStart = eventsModel.DateStart; activites.DateEnd = eventsModel.DateEnd; activites.statu = false; db.Activites.Add(activites); try { await db.SaveChangesAsync(); }catch (DbEntityValidationException DbExc) { string error = ""; foreach (var er in DbExc.EntityValidationErrors) { foreach (var ve in er.ValidationErrors) { error += " - " + ve.ErrorMessage; } } TempData["Message"] = error; } IList <EventAttendee> AttList = new List <EventAttendee>(); var MemL = db.Membre_group.Where(mg => mg.GroupId == idgroupe); Membre_group membre_Group = new Membre_group(); foreach (var item in MemL) { EventAttendee eventAttendee = new EventAttendee(); eventAttendee.Email = item.Utilisateur.Email; AttList.Add(eventAttendee); //new EventAttendee() { Email = item.Utilisateur.Email }; } ///// Email Send ////////////////////////////// GetMailData(); EMail mail = new EMail(); dynamic MailMessage = new MailMessage(); MailMessage.From = new MailAddress(FromAddress); foreach (var item in MemL) { MailMessage.To.Add(item.Utilisateur.Email); } MailMessage.Subject = "Espace MEFRA Notification"; MailMessage.IsBodyHtml = true; MailMessage.Body = "Nouveau Activité"; SmtpClient SmtpClient = new SmtpClient(); SmtpClient.Host = strSmtpClient; SmtpClient.EnableSsl = bEnableSSL; SmtpClient.Port = Int32.Parse(SMTPPort); SmtpClient.Credentials = new System.Net.NetworkCredential(UserID, Password); try { try { SmtpClient.Send(MailMessage); } catch (Exception ex) { } } catch (SmtpFailedRecipientsException ex) { for (int i = 0; i <= ex.InnerExceptions.Length; i++) { SmtpStatusCode status = ex.StatusCode; if ((status == SmtpStatusCode.MailboxBusy) | (status == SmtpStatusCode.MailboxUnavailable)) { System.Threading.Thread.Sleep(5000); SmtpClient.Send(MailMessage); } } } if (GAC) { UserCredential credential; using (var stream = new FileStream(Path.Combine(Server.MapPath("~/Credentials"), "credentials-MinFin.json"), FileMode.Open, FileAccess.Read)) { // The file token.json stores the user's access and refresh tokens, and is created // automatically when the authorization flow completes for the first time. string credPath = Path.Combine(Server.MapPath("~/Credentials"), "token" + id + ".json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; } // Create Google Calendar API service. var 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; Event newEvent = new Event() { Summary = eventsModel.Title, Location = eventsModel.Location, Description = eventsModel.Description, Start = new EventDateTime() { DateTime = DateTime.Parse(string.Format("{0:s}", eventsModel.DateStart)), TimeZone = "Africa/Casablanca", }, End = new EventDateTime() { DateTime = DateTime.Parse(string.Format("{0:s}", eventsModel.DateEnd)), TimeZone = "Africa/Casablanca", }, Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=2" }, Attendees = AttList, Reminders = new Event.RemindersData() { UseDefault = false, Overrides = new EventReminder[] { new EventReminder() { Method = "email", Minutes = 24 * 60 }, new EventReminder() { Method = "sms", Minutes = 10 }, } } }; EventsResource.InsertRequest request2 = service.Events.Insert(newEvent, eventsModel.GoogleCalendarID); request2.Execute(); } ViewBag.Type_ActiviteID = new SelectList(db.Type_Activite, "ID", "Nom_type"); ViewData["idagenda"] = id; ViewData["idgroupe"] = idgroupe; ViewData["GAC"] = GAC; return(RedirectToAction("TestApi", "Agenda", new { id })); }
private async void insertevent() { UserData user = (UserData)Session["User"]; UserCredential credential; using (var stream = new FileStream(Server.MapPath("client_secret.json"), FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal);; credPath = Path.Combine(credPath, ".credentials/calendarinsert-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Google Calendar API service. var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); CalendarService cs = service; DateTime d = Convert.ToDateTime(txtdom.Value); DateTime t = Convert.ToDateTime(txttime.Value); DateTime dt = new DateTime(d.Year, d.Month, d.Day, t.Hour, t.Minute, t.Second); Event newEvent = new Event() { Summary = "Project: " + Projchoose.Items[Projchoose.SelectedIndex].Text.ToString(), Location = "On Fincal", Description = txtmeetd.Value.ToString(), Start = new EventDateTime() { DateTime = DateTime.Parse(XmlConvert.ToString(dt, XmlDateTimeSerializationMode.Utc)),//DateTime.pr dt.ToUniversalTime().ToString("YYYY-MM-DD'T'HH:mm:ssZ"), TimeZone = "Europe/Paris", }, End = new EventDateTime() { DateTime = DateTime.Parse(XmlConvert.ToString(dt, XmlDateTimeSerializationMode.Utc)), TimeZone = "Europe/Paris", }, }; String calendarId = "primary"; EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId); Event newevent = await request.ExecuteAsync(); }
private SheetsService AuthorizeGoogleApp() { UserCredential credential; #if UNITY_ANDROID && !UNITY_EDITOR if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead)) { Permission.RequestUserPermission(Permission.ExternalStorageRead); } if (Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite)) { Permission.RequestUserPermission(Permission.ExternalStorageWrite); } var credFileName = Path.GetFileNameWithoutExtension(credentials); var tokenFileName = Path.GetFileNameWithoutExtension(tokenResponse); var objCred = Resources.Load <TextAsset>(credFileName); // The file must be saved as json or unity can't load it var verf = Resources.Load <TextAsset>(tokenFileName); var partPath = Path.Combine(Application.persistentDataPath, "credentials"); var pathCred = Path.Combine(partPath, "credentials.json"); var pathVerf = Path.Combine(partPath, "Google.Apis.Auth.OAuth2.Responses.TokenResponse-user"); if (!Directory.Exists(partPath)) { Directory.CreateDirectory(partPath); } if (File.Exists(pathCred) && File.Exists(pathVerf)) { credentials = pathCred; print(Application.persistentDataPath); } // We are doing this because authorizing thorigh web causes unexpected bugs on android else { File.WriteAllText(pathCred, objCred.text); File.WriteAllText(pathVerf, verf.text); credentials = pathCred; } using (var stream = new StreamReader(credentials)) { var credPath = Path.Combine(Application.persistentDataPath, "credentials"); FileDataStore store = new FileDataStore(credPath, true); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream.BaseStream).Secrets, _scopes, "user", CancellationToken.None, store).Result; } #else using (var stream = new FileStream(credentials, FileMode.Open, FileAccess.Read)) { string credPath = Path.Combine(Application.dataPath, "Google Sheets", "Resources"); var store = new FileDataStore(credPath, true); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, _scopes, "user", CancellationToken.None, store).Result; var f = Directory.GetFiles(credPath).Where(fi => fi.Contains("Google.Apis")).ToArray()[0]; var tokenPath = Path.Combine(Application.dataPath, "Google Sheets", "Resources", "TokenResponse.json"); if (!File.Exists(tokenPath)) { File.Move(f, tokenPath); } print("Credential file saved to: " + tokenPath); } #endif // Create Google Sheets API service. var service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); return(service); }