public void GoogleCalendar() { GoogleCalendarEnabled = false; // //// check the file exists // //if (!File.Exists(keyFilePath)) // //{ // // Console.WriteLine("An Error occurred - Key file does not exist"); // // return null; // //} // string[] scopes = new string[] { // CalendarService.Scope.Calendar, // Manage your calendars // CalendarService.Scope.CalendarReadonly // View your Calendars //}; // var certificate = new X509Certificate2(@"C:\Users\Shive\Desktop\2-2-15\GoogleCalendar-4bcb43f58d2a.p12", "notasecret", X509KeyStorageFlags.Exportable); ClientSecrets secrets = new ClientSecrets { ClientId = "1057841883430-ml0bjcua59arakl74l57jouq38ul64dm.apps.googleusercontent.com", ClientSecret = "HcI89lr3AiWbhUa8spNNjxtZ" }; /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// // string keyFilePath = @"C:\Users\Shive\Desktop\10-2-15\GoogleCalendar-4bcb43f58d2a.p12"; // string serviceAccountEmail = "*****@*****.**"; // string[] scopes = new string[] { // CalendarService.Scope.Calendar, // Manage your calendars // CalendarService.Scope.CalendarReadonly // View your Calendars // }; // var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); //ServiceAccountCredential credential = new ServiceAccountCredential( // new ServiceAccountCredential.Initializer(serviceAccountEmail) { // Scopes = scopes // }.FromCertificate(certificate)); /////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////// try { // ServiceAccountCredential credential = new ServiceAccountCredential // (new ServiceAccountCredential.Initializer("*****@*****.**") // { // Scopes = scopes // }.FromCertificate(certificate)); // // Create the service. // CalendarService service = new CalendarService(new BaseClientService.Initializer() // { // HttpClientInitializer = credential, // ApplicationName = "test", // }); // //return service; // /* // // BaseClientService.Initializer initializer = new BaseClientService.Initializer(); // IList<CalendarListEntry> list = service.CalendarList.List().Execute().Items;//new List<CalendarListEntry>(); // DisplayList(list); // foreach (Google.Apis.Calendar.v3.Data.CalendarListEntry calendar in list) // { // MessageBox.Show(calendar +""); // } // ///////////////////////////////// // var calendars = service.CalendarList.List().Execute().Items; // foreach (CalendarListEntry entry in calendars) // { // MessageBox.Show(entry.Summary + " - " + entry.Id); // } // Events request = null; // // ListRequest lr = service.Events.List("calendar id (email)"); // //lr.TimeMin = DateTime.Now.AddDays(-5); //five days in the past // //lr.TimeMax = DateTime.Now.AddDays(5); //five days in the future // //request = lr.Execute(); // ////////////////////////////////// // */ UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( secrets, new string[] { CalendarService.Scope.Calendar }, "user", CancellationToken.None) .Result; var initializer = new BaseClientService.Initializer(); initializer.HttpClientInitializer = credential; initializer.ApplicationName = "MyProject"; calendarConnection = new CalendarService(initializer); var calendars = calendarConnection.CalendarList.List().Execute().Items; /* * foreach (CalendarListEntry entry in calendars) * { * MessageBox.Show(entry.Summary + " - " + entry.Id); * } */ Google.Apis.Calendar.v3.EventsResource.ListRequest lr = calendarConnection.Events.List("*****@*****.**"); lr.TimeMin = DateTime.Now.AddDays(-5); //five days in the past lr.TimeMax = DateTime.Now.AddDays(5); //five days in the future request = lr.Execute(); items = (List <Event>)request.Items; GoogleCalendarEnabled = true; //"*****@*****.**" /* IMPORTANT!!!WRITE EVENT * { * Event googleCalendarEvent = new Event(); * * googleCalendarEvent.Start = new EventDateTime(); * googleCalendarEvent.End = new EventDateTime(); * * //if (AllDay) * //{ * //If you want to create an all day event you don't need * //to provide the time, only the date * * * //googleCalendarEvent.Start.Date = DateTime.Now.ToString("2015-2-2"); * //googleCalendarEvent.End.Date = DateTime.Now.ToString("2015-2-10"); * * //} * //else * //{ * * googleCalendarEvent.Start.DateTime = new DateTime(2015,2,12,13,3,0); * //googleCalendarEvent.Start.DateTime = DateTime.Now; * googleCalendarEvent.End.DateTime = new DateTime(2015, 2, 12, 15, 0, 0); * //} * * googleCalendarEvent.Summary = "Its my birthday"; * googleCalendarEvent.Description = "I'm becoming one year older"; * googleCalendarEvent.Location = "at home"; * * //Set Remainder * googleCalendarEvent.Reminders = new Event.RemindersData(); * googleCalendarEvent.Reminders.UseDefault = false; * EventReminder reminder = new EventReminder(); * reminder.Method = "popup"; * reminder.Minutes = 6; * * // * * * * * //googleCalendarEvent.Reminders.Overrides = new List(); * * //googleCalendarEvent.Reminders.Overrides.Add(reminder); * * //Attendees * //googleCalendarEvent.Attendees.Add(new EventAttendee() * //{ * // DisplayName = "Sebastian", * // Email = "*****@*****.**", * // ResponseStatus = "accepted" * //}); * //googleCalendarEvent.Attendees.Add(new EventAttendee() * //{ * // DisplayName = "Fiona", * // Email = "*****@*****.**", * // ResponseStatus = "needsAction" * //}); * * calendarConnection.Events.Insert(googleCalendarEvent, "*****@*****.**").Execute(); * } */ } catch (Exception ex) { //MessageBox.Show(ex.InnerException + ""); //return null; } }
public static List <UserDateProgrammingPojo> getDataFromGoogleSheetAPI() { List <UserDateProgrammingPojo> extractedData = null; try { // 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(FileUtil.credentialsJSONPath, FileMode.Open, FileAccess.Read)) { string credPath = FileUtil.credPathForGoogleSheetApi; 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 = "1CXbZGgYEiUqolQgACSFocOqWoC1kGn_0FadAE35r4Q4"; StringBuilder range = new StringBuilder(); range.Append(getSheetName()); range.Append("!B4:K7"); SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range.ToString()); // Prints the names and majors of students in a sample spreadsheet: // https://docs.google.com/spreadsheets/d/1CXbZGgYEiUqolQgACSFocOqWoC1kGn_0FadAE35r4Q4/edit ValueRange response = request.Execute(); IList <IList <Object> > values = response.Values; if (values != null && values.Count > 0) { int count = 0; extractedData = new List <UserDateProgrammingPojo>(); foreach (var row in values) { count = 0; UserDateProgrammingPojo currentUser = new UserDateProgrammingPojo(); foreach (var currentValue in row) { count++; if (count % 2 == 0) { Console.WriteLine("User="******"Data=" + currentValue); currentUser.Date = currentValue.ToString(); } } } } return(extractedData); } catch (Exception ex) { HandlerErrorsUtil.handlerErrorFromGoogleAPI(ex.Message); return(null); } }
private void button1_Click(object sender, EventArgs e) { Cursor.Current = Cursors.WaitCursor; if (radBacon.Checked) { string sqlinsert = " insert into dbo.goo_spend_tool_bom(CM_part_number,google_part_number,parent_google_part_number,manf_part_number,manufacturer,description,quantity,unit_price,ext_price,moq,lead_time,neog_by_google,assm_by_google,tran_id) SELECT CM_part_number,google_part_number,parent_google_part_number,manf_part_number,manufacturer,description,quantity,unit_price,ext_price,moq,lead_time,neog_by_google,assm_by_google,tran_id FROM [MIMDIST].[dbo].[BaconBOM_for_SpendTool] "; string sql = ""; //for (int i = 0; i < ultraGridBOM.Rows.Count; i++) //{ // string CM_part_number = ultraGridBOM.Rows[i].Cells["CM_part_number"].Value.ToString(); // string google_part_number = ultraGridBOM.Rows[i].Cells["google_part_number"].Value.ToString(); // string parent_google_part_number = ultraGridBOM.Rows[i].Cells["parent_google_part_number"].Value.ToString(); // string manf_part_number = ultraGridBOM.Rows[i].Cells["manf_part_number"].Value.ToString(); // string manufacturer = ultraGridBOM.Rows[i].Cells["manufacturer"].Value.ToString(); // string description = ultraGridBOM.Rows[i].Cells["description"].Value.ToString(); // string quantity = Convert.ToDecimal(ultraGridBOM.Rows[i].Cells["quantity"].Value).ToString(); // string unit_price = Convert.ToDecimal(ultraGridBOM.Rows[i].Cells["unit_price"].Value).ToString(); // string ext_price = Convert.ToDecimal(ultraGridBOM.Rows[i].Cells["ext_price"].Value).ToString(); // string moq = ultraGridBOM.Rows[i].Cells["moq"].Value.ToString(); // string lead_time = ultraGridBOM.Rows[i].Cells["lead_time"].Value.ToString(); // string neog_by_google = ultraGridBOM.Rows[i].Cells["neog_by_google"].Value.ToString(); // string assm_by_google = ultraGridBOM.Rows[i].Cells["assm_by_google"].Value.ToString(); // sql = sql + sqlinsert + " values ('" + CM_part_number + "','" + google_part_number + "','" + parent_google_part_number + "','" + manf_part_number + "','" + manufacturer + "','" + description + "','" + quantity + "','" + unit_price + "','" + ext_price + "','" + moq + "','" + lead_time + "','" + neog_by_google + "','" + assm_by_google + "')"; //} sql = " delete from dbo.[goo_spend_tool_bom] " + sqlinsert; SqlConnection cn = new SqlConnection(constr); cn.Open(); SqlTransaction tran = cn.BeginTransaction(); try { SqlCommand cmd = new SqlCommand(sql, cn); cmd.CommandTimeout = 0; cmd.Transaction = tran; cmd.ExecuteNonQuery(); tran.Commit(); MessageBox.Show("Spend tool table has been poplulated successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); runJob(); //Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application(); ////string pkgLocation; //// DTSExecResult pkgResults; //string pkgLocation = @"\\mverp\f$\Integration\SupplierIntegration\SpendTool.dtsx"; //Package pkg = app.LoadPackage(pkgLocation, null); //Microsoft.SqlServer.Dts.Runtime.DTSExecResult results = pkg.Execute(); //if (results == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure) //{ // string err = ""; // foreach (Microsoft.SqlServer.Dts.Runtime.DtsError local_DtsError in pkg.Errors) // { // string error = local_DtsError.Description.ToString(); // err = err + error; // } //} //else if (results == Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success) //{ // MessageBox.Show("Package Executed Successfully...."); //} } catch (Exception exp) { tran.Rollback(); MessageBox.Show("Not Saved. Please check the error" + exp.Message.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } cn.Close(); } else if (radShareDoc.Checked) { create_file(); 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/drive-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive } , "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MIM Project", }); FilesResource.ListRequest lstreq = service.Files.List(); string Parentid = ""; Parentid = getGIDByName(Collection); string pageToken = null; if (Parentid == "") { MessageBox.Show("Parent not found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } string fileid = ""; do { var result = getFilesByParentId(Parentid, pageToken); foreach (var file in result.Files) { if (file.Name == TLA_PartNum) { fileid = file.Id; break; } } pageToken = result.NextPageToken; } while (pageToken != null); // string fileid = getchildInFolder(service, Parentid); try { Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File(); body.Name = TLA_PartNum; body.Description = TLA_PartNum; body.MimeType = "application/vnd.google-apps.spreadsheet"; body.Parents = new List <string> { Parentid }; // string newTitle = System.IO.Path.GetFileName("Rack Delivery Plan" + DateTime.Now.Month.ToString("00") + DateTime.Now.Day.ToString("00") + DateTime.Now.Year.ToString("00") + ".xlsx"); // if (!String.IsNullOrEmpty(Parentid)) // { // body.Parents = new List<ParentReference>() { new ParentReference() { Id = Parentid } }; // } // filename = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\MIM_Menlo Demand TrackerTemplate.xlsx";// "E:\\Ruchi\\b2bdevMaintainGoogleDoc\\MaintainGoogleDoc\\MaintainGoogleDoc\\bin\\Debug\\MIM_Menlo Demand TrackerTemplate.xlsx"; filename = filename1.Replace("file:\\", " "); // MessageBox.Show("filename=" + filename); System.IO.Stream fileStream = System.IO.File.Open(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] byteArray = new byte[fileStream.Length]; fileStream.Read(byteArray, 0, (int)fileStream.Length); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); if (fileid != "") { FilesResource.UpdateMediaUpload request1 = service.Files.Update(body, fileid, stream, "application/x-vnd.oasis.opendocument.spreadsheet"); //request1.Convert = true; request1.Upload(); } else { FilesResource.CreateMediaUpload request2 = service.Files.Create(body, stream, "application/x-vnd.oasis.opendocument.spreadsheet"); // request2.Convert = true; request2.Upload(); } MessageBox.Show("File has been uploaded in shared doc"); fileStream.Close(); fileStream.Dispose(); } catch (Exception exp) { MessageBox.Show("Exception to upload file"); } finally { } } Cursor.Current = Cursors.Default; }
public void AddToCalendar(bool update) { // Making this a boolean for reasons. Dont remember what they are right now, but I remember thinking this was better for some reason. if (update == 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-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, }); // Grabbing the hours ParseHours hours = new ParseHours(); hours.HoursWorked(); DateTime dateValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); MainForm listbox = new MainForm(); string calendarDate = "1/1/2017 "; // Making one event with 'default' settings. So if something goes wrong it posts it to your current day between 8 and 10 AM Event newEvent = new Event() { Summary = "Working", Location = "7000 Dandini BLVD Reno NV 89512", Description = "Working during this time", Start = new EventDateTime() { DateTime = DateTime.Parse(calendarDate + "8:00 AM"), TimeZone = "America/Los_Angeles", }, End = new EventDateTime() { DateTime = DateTime.Parse(calendarDate + "10:00 AM"), TimeZone = "America/Los_Angeles", }, Recurrence = new String[] { "RRULE:FREQ=WEEKLY;COUNT=2" }, Reminders = new Event.RemindersData() { UseDefault = true, } }; String calendarId = "primary"; EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId); string dateText; // We're adding dates for the first five days of the week, and then we're letting google handle the second repeat of the event // We're running the loop ~7 times, but only posting on Mon-Fri int i = 0; int x = 0; if (dateRange == "1st - 15th") { i = 1; x = i + 7; } else if (dateRange == "16th - 30th") { i = 16; x = i + 7; } else if (dateRange == "16th - 31st") { i = 16; x = i + 8; } while (i < x) { if (dateValue.AddDays(i - 1).ToString("ddd") == "Mon" && hours.mondayStart != " 0") { dateText = string.Format("{0}/{1}/{2} ", DateTime.Now.Month, i, DateTime.Now.Year); newEvent.Start.DateTime = DateTime.Parse(dateText + hours.mondayStart); newEvent.End.DateTime = DateTime.Parse(dateText + hours.mondayEnd); Event createdEvent = request.Execute(); } else if (dateValue.AddDays(i - 1).ToString("ddd") == "Tue" && hours.tuesdayStart != " 0") { dateText = string.Format("{0}/{1}/{2} ", DateTime.Now.Month, i, DateTime.Now.Year); newEvent.Start.DateTime = DateTime.Parse(dateText + hours.tuesdayStart); newEvent.End.DateTime = DateTime.Parse(dateText + hours.tuesdayEnd); Event createdEvent = request.Execute(); } else if (dateValue.AddDays(i - 1).ToString("ddd") == "Wed" && hours.wednesdayStart != " 0") { dateText = string.Format("{0}/{1}/{2} ", DateTime.Now.Month, i, DateTime.Now.Year); newEvent.Start.DateTime = DateTime.Parse(dateText + hours.wednesdayStart); newEvent.End.DateTime = DateTime.Parse(dateText + hours.wednesdayEnd); Event createdEvent = request.Execute(); } else if (dateValue.AddDays(i - 1).ToString("ddd") == "Thu" && hours.thursdayStart != " 0") { dateText = string.Format("{0}/{1}/{2} ", DateTime.Now.Month, i, DateTime.Now.Year); newEvent.Start.DateTime = DateTime.Parse(dateText + hours.thursdayStart); newEvent.End.DateTime = DateTime.Parse(dateText + hours.thursdayEnd); Event createdEvent = request.Execute(); } else if (dateValue.AddDays(i - 1).ToString("ddd") == "Fri" && hours.fridayStart != " 0") { dateText = string.Format("{0}/{1}/{2} ", DateTime.Now.Month, i, DateTime.Now.Year); newEvent.Start.DateTime = DateTime.Parse(dateText + hours.fridayStart); newEvent.End.DateTime = DateTime.Parse(dateText + hours.fridayEnd); Event createdEvent = request.Execute(); } ++i; } //Console.WriteLine("Event created: {0}", createdEvent.HtmlLink); } }
/// <summary> /// Sends a message using Gmail API /// </summary> /// <param name="msg">Message to send</param> /// <returns>JSON serialized string of a result object</returns> public string Send(EmailMessage msg) { string emailTemplate = GetMsgTemplate(msg.template.templateId); if (null == emailTemplate) { _logger.LogError($"Unable to load Email template with id {msg.template.templateId}"); return(null); } string htmlBody = null; string subject = null; ServiceCollection services = new ServiceCollection(); services.AddNodeServices(); using (ServiceProvider serviceProvider = services.BuildServiceProvider()) { NodeServicesOptions options = new NodeServicesOptions(serviceProvider) /* Assign/override any other options here */ } { ; using (INodeServices nodeServices = NodeServicesFactory.CreateNodeServices(options)) { htmlBody = nodeServices.InvokeAsync <string>("pugcompile", emailTemplate, null == msg.bodyModel ? null: JsonConvert.DeserializeObject(msg.bodyModel)).Result; subject = nodeServices.InvokeAsync <string>("pugcompile", msg.template.subjectTemplate, null == msg.subjectModel ? null : JsonConvert.DeserializeObject(msg.subjectModel)).Result; } } services.Clear(); if (null == subject) { _logger.LogError($"Unable to load email subject"); return(null); } if (null == emailTemplate) { _logger.LogError($"Unable to load Email template with id {msg.template.templateId}"); return(null); } UserCredential credential; string[] scopes = { GmailService.Scope.GmailSend }; using (FileStream 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; _logger.LogInformation("Google credential file saved to: " + credPath); } // Create Gmail API service. using (GmailService service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MailGmail", })) { Google.Apis.Gmail.v1.Data.Message message = CreateGmailMessage(msg.from, msg.to, subject, htmlBody); Google.Apis.Gmail.v1.Data.Message messageResult = service.Users.Messages.Send(message, "me").Execute(); return(JsonConvert.SerializeObject(messageResult)); } }
private async System.Threading.Tasks.Task <bool> UploadVideo(string title, string desc, string[] tags, string categoryId, PrivacyStatus ps, string filePath) { try { InfoFormat("Uploading the video file {0} to YouTube started...", filePath); Info("Authentication started..."); UserCredential credential; using (var stream = new FileStream(ClientSecrets, 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.YoutubeUpload }, User, CancellationToken.None ); } Info("Authentication succeeded."); var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); var video = new Video { Snippet = new VideoSnippet() }; video.Snippet.Title = title; video.Snippet.Description = desc; video.Snippet.Tags = tags; video.Snippet.CategoryId = categoryId; // See https://developers.google.com/youtube/v3/docs/videoCategories/list video.Status = new VideoStatus { PrivacyStatus = ps.ToString().ToLower() // "unlisted" or "private" or "public" }; using (var fileStream = new FileStream(filePath, FileMode.Open)) { var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*"); videosInsertRequest.ResponseReceived += VideosInsertRequest_ResponseReceived; var res = videosInsertRequest.Upload(); if (res.Exception != null) { ErrorFormat("An error occured while uploading the file {0}: {1}", filePath, res.Exception.Message); return(false); } } InfoFormat("Uploading the video file {0} to YouTube succeeded.", filePath); return(true); } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while uploading the video file {0}: {1}", filePath, e.Message); return(false); } }
public static void StaticRun() { UserCredential credential; using (var stream = new FileStream("creds.json", FileMode.Open, FileAccess.Read)) { string credPath = MainClass.location + "gcreds"; 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, }); var inboxlistRequest = service.Users.Messages.List(UserMail); inboxlistRequest.LabelIds = LabelId; inboxlistRequest.Q = "is:unread"; 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(UserMail, email.Id); var emailInfoResponse = emailInfoRequest.Execute(); MainClass.positionContracts = MainClass.getPosition(); if (emailInfoResponse != null) { string mData = emailInfoResponse.Snippet; if (mData.Contains(MainClass.pair) && mData.Contains(sellTrigger) && (MainClass.positionContracts > 0 || MainClass.positionContracts == 0) && lastAlert != "Sell") { MainClass.log(emailInfoResponse.Snippet); MainClass.log("Short: " + MainClass.pair); string json = MainClass.bitMEXApi.MarketOrder(MainClass.pair, "Sell", Math.Abs(MainClass.positionContracts) + MainClass.qtdyContacts, "Tradingview Short"); if (json.ToLower().IndexOf("error") >= 0 || json.ToLower().IndexOf("canceled") >= 0) { if (json.ToLower().IndexOf("overload") >= 0 && Math.Abs(MainClass.positionContracts) > 0) {/* In case of overload, close the position to prevent losses*/ MainClass.log("System is on overload, trying to close position to prevent losses"); MainClass.log(MainClass.bitMEXApi.MarketClose(MainClass.pair, "Sell")); } return; } lastAlert = "Sell"; } else if (mData.Contains(MainClass.pair) && mData.Contains(buyTrigger) && (MainClass.positionContracts < 0 || MainClass.positionContracts == 0) && lastAlert != "Buy") { MainClass.log(emailInfoResponse.Snippet); MainClass.log("Long: " + MainClass.pair); string json = MainClass.bitMEXApi.MarketOrder(MainClass.pair, "Buy", Math.Abs(MainClass.positionContracts) + MainClass.qtdyContacts, "Tradingview Long"); if (json.ToLower().IndexOf("error") >= 0 || json.ToLower().IndexOf("canceled") >= 0) { if (json.ToLower().IndexOf("overload") >= 0 && Math.Abs(MainClass.positionContracts) > 0) {/* In case of overload, close the position to prevent losses*/ MainClass.log("System is on overload, trying to close position to prevent losses"); MainClass.log(MainClass.bitMEXApi.MarketClose(MainClass.pair, "Buy")); } return; } lastAlert = "Buy"; } /* we'll do some crap here*/ var markAsReadRequest = new ModifyThreadRequest { RemoveLabelIds = new[] { "UNREAD" } }; var markRead = service.Users.Threads.Modify(markAsReadRequest, UserMail, emailInfoResponse.ThreadId); markRead.Execute(); } } } }
public static void GetSheet(string getArea, string spreadsheetid) { UserCredential credential; using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) { string credPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // færdig med at gemme // Laver Google Sheets API service. var service = new SheetsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Definerer hvad den skal kigge efter i vores sheet String spreadsheetId = spreadsheetid; String getRange = getArea; SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, getRange); ValueRange response = request.Execute(); IList <IList <Object> > values = response.Values; // checker om den celle den der i ikke er tom if (values != null && values.Count > 0) { int i = 0; range = values.Count; // laver en todimensionelle liste om til en enkelt dimensionel array foreach (var row in values) { try { checkedState[i] = values[i][2]; processList[i] = values[i][1]; gamesList[i] = values[i][0]; Console.WriteLine(processList[i]); File.AppendAllText(programPath, values[i][0] + "," + values[i][1] + "," + values[i][2] + ";"); i++; } catch (Exception c) { Console.WriteLine(c.Message); } } } // udskriver hvis der er ikke er noget data i det sheet der er blevet defineret else { Console.WriteLine("No data found."); } }
private async Task Run(string chanelIdORVideoId, YouTubeRating action, string comment) { var baseDir = $"{AppDomain.CurrentDomain.BaseDirectory}\\ClientSecrets"; var clientSecretFile = $"{baseDir}\\Config"; var infos = File.ReadAllLines(clientSecretFile); var index = 0; var s = new ConsoleSpinner(); do { var stillValid = index + 5 <= infos.Length; if (!stillValid) { break; } // This is will be skip at first and final if (index > 0) { var csCount = 0; while (csCount < 30) { Thread.Sleep(100); // simulate some work being done s.UpdateProgress(); csCount++; } } // var email = infos[index++]; var clientID = infos[index++]; var clientSecret = infos[index++]; var apiKey = infos[index++]; var chanelId = infos[index++]; Console.WriteLine($"{email}"); Console.WriteLine("-----"); var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets() { ClientId = clientID, ClientSecret = clientSecret }, // This OAuth 2.0 access scope allows for full read/write access to the // authenticated user's account. new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeForceSsl, YouTubeService.Scope.Youtubepartner }, chanelId, CancellationToken.None, new FileDataStore(baseDir, true) ); var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApiKey = apiKey, }); // Chanels List //var chanelsList = youtubeService.Channels.List("snippet,contentDetails,statistics"); //chanelsList.Id = chanelId; //chanelsList.MaxResults = 1; //var chanels = await chanelsList.ExecuteAsync(); //if (chanels != null) // Console.WriteLine($"{chanels.Items[0].Snippet.Title}"); //Console.WriteLine("-----"); // SUB or UNSUB try { switch (action) { case YouTubeRating.Sub: var subBody = new Subscription(); subBody.Snippet = new SubscriptionSnippet(); subBody.Snippet.ChannelId = chanelId; var resourceId = new ResourceId(); resourceId.ChannelId = chanelIdORVideoId; // "UCAuUUnT6oDeKwE6v1NGQxug"; subBody.Snippet.ResourceId = resourceId; var subInsert = youtubeService.Subscriptions.Insert(subBody, "snippet"); var ressubInsert = await subInsert.ExecuteAsync(); break; case YouTubeRating.Unsub: var subList = youtubeService.Subscriptions.List("snippet,contentDetails"); subList.ChannelId = chanelId; var subs = await subList.ExecuteAsync(); var deleteId = String.Empty; foreach (var item in subs.Items) { var needDelete = item.Snippet.ResourceId.ChannelId == chanelIdORVideoId; if (needDelete) { deleteId = item.Id; break; } } if (String.IsNullOrEmpty(deleteId)) { throw new Exception($"{chanelIdORVideoId} not found."); } var subDelete = youtubeService.Subscriptions.Delete(deleteId); var ressubDelete = await subDelete.ExecuteAsync(); break; case YouTubeRating.Like: var ratingLike = youtubeService.Videos.Rate(chanelIdORVideoId, VideosResource.RateRequest.RatingEnum.Like); var resratingLike = await ratingLike.ExecuteAsync(); //var aaa = youtubeService.Videos.GetRating(chanelIdORVideoId); //var bbb = await aaa.ExecuteAsync(); break; case YouTubeRating.Unlike: var ratingUnlike = youtubeService.Videos.Rate(chanelIdORVideoId, VideosResource.RateRequest.RatingEnum.None); var resratingUnlike = await ratingUnlike.ExecuteAsync(); break; case YouTubeRating.Dislike: var ratingDislike = youtubeService.Videos.Rate(chanelIdORVideoId, VideosResource.RateRequest.RatingEnum.Dislike); var resratingDislike = await ratingDislike.ExecuteAsync(); break; case YouTubeRating.Comment: var comThreadBody = new CommentThread(); comThreadBody.Snippet = new CommentThreadSnippet() { ChannelId = chanelId, VideoId = chanelIdORVideoId }; comThreadBody.Snippet.TopLevelComment = new Comment(); comThreadBody.Snippet.TopLevelComment.Snippet = new CommentSnippet() { TextOriginal = comment }; var commentThreadsInsert = youtubeService.CommentThreads.Insert(comThreadBody, "snippet"); var rescommentThreadsInsert = await commentThreadsInsert.ExecuteAsync(); break; default: break; } Console.WriteLine($"{chanelIdORVideoId} OK"); } catch (Exception ex) { Console.WriteLine($"{chanelIdORVideoId} failed with error: {ex.Message}"); } Console.WriteLine("-----"); Console.WriteLine(" "); } while (true); }
private void onlineUploadTabButton_Click(object sender, EventArgs e) { if (videoUploadTabTextBox.Text.Contains("PATH") || (thumbnailUploadTabTextBox.Text.Contains("PATH"))) { MessageBox.Show("Please select an video/thumbnail first!"); } else { progresslabel.Text = "Upload started"; try { Thread thead = new Thread(() => { Run().Wait(); }) { IsBackground = true }; thead.Start(); } catch (AggregateException ex) { MessageBox.Show(ex.Message); } } async Task Run() { UserCredential credential; using (var stream = new FileStream("/Windows/JSON/client_id.json", 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.YoutubeUpload }, "user", CancellationToken.None ); } var youtubeService = new YouTubeService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = Assembly.GetExecutingAssembly().GetName().Name }); var video = new Video(); video.Snippet = new VideoSnippet(); video.Snippet.Title = titleUploadTabTextBox.Text; video.Snippet.Description = descriptionUploadTabTextBox.Text; string[] puretags = Regex.Split(tagsUploadTabTextBox.Text, ","); video.Snippet.Tags = puretags; video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list video.Status = new VideoStatus(); video.Status.PrivacyStatus = "private"; // or "private" or "public" string stringdate = dateTimePicker1.Value.ToString("yyyy:MM:dd") + "T" + dateTimePicker2.Value.ToString("HH:mm") + "Z"; var truedate = DateTime.ParseExact(stringdate, "yyyy':'MM':'dd'T'HH':'mm'Z'", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None); video.Status.PublishAt = truedate; var filePath = videoUploadTabTextBox.Text; // Replace with path to actual movie file. using (var fileStream = new FileStream(filePath, FileMode.Open)) { var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*"); videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged; videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived; await videosInsertRequest.UploadAsync(); } } void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress) { switch (progress.Status) { case UploadStatus.Uploading: progresslabel.Text = String.Format("{0} bytes sent.", progress.BytesSent); break; case UploadStatus.Failed: progresslabel.Text = String.Format("An error prevented the upload from completing.\n{0}", progress.Exception); break; } progressBar.Value = 50; } }
static void Main(string[] args) { Boolean stop = false; while (!stop) { 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 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 = 30; listRequest.Fields = "nextPageToken, files(id, name, size)"; // 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) { if (file.Size != null) { Console.WriteLine("{0} {1}", file.Name, file.Size / 1024 + " КБ"); } else { Console.WriteLine(file.Name + " Папка"); } } } else { Console.WriteLine("No files found."); } Console.WriteLine(); Console.WriteLine("Проверить обновление? Y/N"); string str = ""; str = Console.ReadLine(); if (str.Equals("n") || str.Equals("и")) { stop = true; } } }
private async Task <bool> ExecuteYouTubeDataApiV3(IConfiguration youTubeConf, string sharedSecretFolder, ILogger <YouTubeUploadOperation> logger, BloggingContext context, IWebHostEnvironment environment, CancellationToken token) { UserCredential credential; using (var stream = new FileStream(youTubeConf["ClientSecretsFileName"], FileMode.Open, FileAccess.Read)) { var store = new GoogleKeyContextStore(context, environment, token); var googl_secrets = await GoogleClientSecrets.FromStreamAsync(stream, token); credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( googl_secrets.Secrets, // This OAuth 2.0 access scope allows for read-write access to the authenticated // user's account, but not other types of account access. new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload }, "user", token, store ); } using (var youtubeService = new YouTubeService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = youTubeConf["ApplicationName"] })) { var lst = new List <PlaylistItem>(365); var nextPageToken = ""; while (nextPageToken != null) { var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet"); playlistItemsListRequest.PlaylistId = youTubeConf["playlistId"]; // playlistItemsListRequest.Fields = "items(snippet(description,publishedAt,title))"; playlistItemsListRequest.MaxResults = 50; playlistItemsListRequest.PageToken = nextPageToken; // Retrieve the list of videos uploaded to the authenticated user's channel. var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync(token); foreach (var item in playlistItemsListResponse.Items) { lst.Add(item); } nextPageToken = playlistItemsListResponse.NextPageToken; } string new_video_title = $"timelapse {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}"; bool already_uploaded = false; var year_ago_date = DateTime.Now.AddYears(-1); int delete_count = 10; foreach (var item in lst) { var date = item.Snippet.PublishedAt.GetValueOrDefault(); bool is_to_be_deleted = date < year_ago_date; if (!is_to_be_deleted) { logger.LogInformation("'{title}' [{description}] {publishedAt}", item.Snippet.Title, item.Snippet.Description, date.ToString("O")); } else if (delete_count > 0) { logger.LogWarning("DELETING '{title}' [{description}] {publishedAt}", item.Snippet.Title, item.Snippet.Description, date.ToString("O")); var playlistItemsDeleteRequest = youtubeService.PlaylistItems.Delete(item.Id); var delete_playlist_response = await playlistItemsDeleteRequest.ExecuteAsync(token); var videoDeleteRequest = youtubeService.Videos.Delete(item.Snippet.ResourceId.VideoId); var delete_video_response = await videoDeleteRequest.ExecuteAsync(token); delete_count--; } if (item.Snippet.Title == new_video_title) { already_uploaded = true; logger.LogWarning("'{title}' already uploaded aborting", item.Snippet.Title); break; } } #if DEBUG already_uploaded = true; #endif if (already_uploaded || string.IsNullOrEmpty(_videoFileNameToUpload)) { return(false); } //upload var video = new Video { Snippet = new VideoSnippet { Title = new_video_title, Description = $"Daily timelapse video taken on {DateTime.Now}", Tags = new string[] { "timelapse", "video", "webcam" }, //"1" -> "Film & Animation", see https://developers.google.com/youtube/v3/docs/videoCategories/list CategoryId = "1", }, Status = new VideoStatus { PrivacyStatus = "unlisted" // or "private" or "public" } }; string successVideoID = null; using (var fileStream = new FileStream(_videoFileNameToUpload, FileMode.Open, FileAccess.Read)) { var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*"); videosInsertRequest.ProgressChanged += (IUploadProgress progress) => { switch (progress.Status) { case UploadStatus.Uploading: logger.LogInformation("{bytesSent} bytes sent.", progress.BytesSent); break; case UploadStatus.Failed: logger.LogWarning("An error prevented the upload from completing.\n{exception}", progress.Exception); break; } }; videosInsertRequest.ResponseReceived += (Video uploadedVideo) => { successVideoID = uploadedVideo.Id; logger.LogInformation("Video id '{id}' was successfully uploaded.", uploadedVideo.Id); }; var uploaded = await videosInsertRequest.UploadAsync(token); if (uploaded.Status == UploadStatus.Completed && !string.IsNullOrEmpty(successVideoID)) { var newPlaylistItem = new PlaylistItem(); newPlaylistItem.Snippet = new PlaylistItemSnippet(); newPlaylistItem.Snippet.PlaylistId = youTubeConf["playlistId"]; newPlaylistItem.Snippet.ResourceId = new ResourceId(); newPlaylistItem.Snippet.ResourceId.Kind = "youtube#video"; newPlaylistItem.Snippet.ResourceId.VideoId = successVideoID; newPlaylistItem = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet") .ExecuteAsync(token); logger.LogInformation("Video id '{id}' was added to playlist id '{playlistID}'.", successVideoID, newPlaylistItem.Snippet.PlaylistId); return(true); } return(false); } //end using fileStream } //end using youtubeService }
public void CreateNewAppointment() { string gmailUsername; string syncProfile; GoogleAPITests.LoadSettings(out gmailUsername, out syncProfile); EventsResource service; CalendarListEntry primaryCalendar = null; var scopes = new List <string>(); //Contacts-Scope scopes.Add("https://www.google.com/m8/feeds"); //Notes-Scope scopes.Add("https://docs.google.com/feeds/"); //scopes.Add("https://docs.googleusercontent.com/"); //scopes.Add("https://spreadsheets.google.com/feeds/"); //Calendar-Scope //scopes.Add("https://www.googleapis.com/auth/calendar"); scopes.Add(CalendarService.Scope.Calendar); UserCredential credential; byte[] jsonSecrets = Properties.Resources.client_secrets; //using (var stream = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(this.GetType()).Location) + "\\client_secrets.json", FileMode.Open, FileAccess.Read)) //using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)) //using (var stream = new FileStream(Application.StartupPath + "\\client_secrets.json", FileMode.Open, FileAccess.Read)) using (var stream = new MemoryStream(jsonSecrets)) { FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, scopes, gmailUsername, CancellationToken.None, fDS).Result; var initializer = new Google.Apis.Services.BaseClientService.Initializer(); initializer.HttpClientInitializer = credential; var CalendarRequest = new CalendarService(initializer); //CalendarRequest.setUserCredentials(username, password); var list = CalendarRequest.CalendarList.List().Execute().Items; foreach (var calendar in list) { if (calendar.Primary != null && calendar.Primary.Value) { primaryCalendar = calendar; break; } } if (primaryCalendar == null) { throw new Exception("Primary Calendar not found"); } //EventQuery query = new EventQuery("https://www.google.com/calendar/feeds/default/private/full"); //ToDo: Upgrade to v3, EventQuery query = new EventQuery("https://www.googleapis.com/calendar/v3/calendars/default/events"); service = CalendarRequest.Events; } #region Delete previously created test contact. var query = service.List(primaryCalendar.Id); query.MaxResults = 500; query.TimeMin = DateTime.Now.AddDays(-10); query.TimeMax = DateTime.Now.AddDays(10); //query.Q = "GCSM Test Appointment"; var feed = query.Execute(); Logger.Log("Loaded Google appointments", EventType.Information); foreach (Google.Apis.Calendar.v3.Data.Event entry in feed.Items) { if (entry.Summary != null && entry.Summary.Contains("GCSM Test Appointment") && !entry.Status.Equals("cancelled")) { Logger.Log("Deleting Google appointment:" + entry.Summary + " - " + entry.Start.DateTime.ToString(), EventType.Information); service.Delete(primaryCalendar.Id, entry.Id); Logger.Log("Deleted Google appointment", EventType.Information); //break; } } #endregion var newEntry = Factory.NewEvent(); newEntry.Summary = "GCSM Test Appointment"; newEntry.Start.DateTime = DateTime.Now; newEntry.End.DateTime = DateTime.Now; var createdEntry = service.Insert(newEntry, primaryCalendar.Id).Execute(); Logger.Log("Created Google appointment", EventType.Information); Assert.IsNotNull(createdEntry.Id); var updatedEntry = service.Update(createdEntry, primaryCalendar.Id, createdEntry.Id).Execute(); Logger.Log("Updated Google appointment", EventType.Information); //delete test contacts service.Delete(primaryCalendar.Id, updatedEntry.Id).Execute(); Logger.Log("Deleted Google appointment", EventType.Information); }
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/gmail-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 Gmail API service. var service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Define parameters of request. UsersResource.MessagesResource.ListRequest request = service.Users.Messages.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."); * } */ // List messages IList <Message> messages = ListMessages(service, "me"); Console.WriteLine("Messages: "); if (messages != null && messages.Count > 0) { foreach (Message message in messages) { UsersResource.MessagesResource.GetRequest asd = service.Users.Messages.Get("me", message.Id); string messageSnippet = asd.Execute().Snippet; var messagePayload = asd.Execute().Payload; string sender = messagePayload.Headers[6].Value; var parts = messagePayload.Parts; Console.WriteLine("From: " + sender); if (!string.IsNullOrWhiteSpace(parts[0].Body.Data)) { string InputStr = parts[0].Body.Data.Replace("-", "+").Replace("_", "/"); string decodedString = Encoding.UTF8.GetString(Convert.FromBase64String(InputStr)); Console.WriteLine("Body: " + decodedString); } else { Console.WriteLine("Well that didn't work out, did it?"); } } } else { Console.WriteLine("No messages 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, "*****@*****.**", 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("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(); DateTime currTime = DateTime.Now; DateTime appt = DateTime.Parse(when); if ((currTime.AddDays(1).Month == appt.Month && currTime.AddDays(1).Day == appt.Day) || (currTime.AddDays(7).Day == appt.Day && currTime.AddDays(7).Month == appt.Month)) { listOfEvents.Add(eventItem); } else { Console.WriteLine(""); } } foreach (var eventItem in listOfEvents) { int i = 0; string when = eventItem.Start.DateTime.ToString(); DateTime currTime = DateTime.Now; DateTime appt = DateTime.Parse(when); if ((currTime.AddDays(1).Month == appt.Month && currTime.AddDays(1).Day == appt.Day) || (currTime.AddDays(7).Day == appt.Day && currTime.AddDays(7).Month == appt.Month)) { Console.WriteLine("{0} ({1})", eventItem.Summary, when, "\n"); Appointment newAppt = new Appointment(); newAppt.setAppt(eventItem.Summary); newAppt.setDate(when); while (i < eventItem.Attendees.Count()) { string attendee = eventItem.Attendees[i].Email; if (attendee == "*****@*****.**") { i++; } else { newAppt.fillEmails(attendee); listOfAppointments.Add(newAppt); Console.WriteLine(attendee); i++; } } } } foreach (var apt in listOfAppointments) { foreach (var email in apt.emailList) { var fromAddress = new MailAddress("*****@*****.**", "Food & Care Coalition"); var toAddress = new MailAddress(email, ""); const string fromPassword = password; const string subject = "Appointment Reminder"; string body = "Hello, I am emailing you to confirm your appointment \"" + apt.apptName + "\" on " + apt.Date + ". Please RSVP as soon as possible, I look forward to seeing you!"; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromAddress.Address, fromPassword), Timeout = 20000 }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { smtp.Send(message); } } } Console.Read(); } }
public static void Init() { 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 Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = applicationName, }); var folderMetaData = new Google.Apis.Drive.v3.Data.File() { Name = "FlowerStoreImages", MimeType = "application/vnd.google-apps.folder" }; var req = service.Files.Create(folderMetaData); req.Fields = "id"; req.Execute(); //await req.ExecuteAsync(); //var resp=req.re 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."); } }
// DriveService service; public void getauthorization() { 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/drive-dotnet-quickstart.json"); credential = GoogleWebAuthorizationBroker.AuthorizeAsync( GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive } , "user", CancellationToken.None, new FileDataStore(credPath, true)).Result; Console.WriteLine("Credential file saved to: " + credPath); } // Create Drive API service. service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "MIM Project", }); string pageToken = null; string fileId = ""; do { var request = service.Files.List(); string title = "GIG-MIM build plan"; request.Q = "modifiedTime > '2016-04-01T12:00:00' and (name contains 'MIM TLA Plan' or name contains 'MIM Build Plan') "; // request.Q = "name = 'MIM tracker'"; // string parent_id = "0B1auUUiGcbbBOEIyNjg0alkwc3c"; // request.Q = "'" + parent_id + "' in parents"; request.Spaces = "Drive"; request.Fields = "*"; request.PageToken = pageToken; var result = request.Execute(); foreach (var file in result.Files) { // if (file.CreatedTime>System.DateTime.Now.AddMonths(-1)) // if (file.Name.StartsWith("MIM Build Plan ") || file.Name.StartsWith("MIM TLA Plan ")) // { if (file.Name.IndexOf('[') > 0) { ListViewItem item = new ListViewItem(new string[2] { file.Name.Substring(0, file.Name.IndexOf('[') - 1), file.Id }); this.spreadsheetListView.Items.Add(item); } else { ListViewItem item = new ListViewItem(new string[2] { file.Name, file.Id }); this.spreadsheetListView.Items.Add(item); } // } } pageToken = result.NextPageToken; } while (pageToken != null); do { var request = service.Files.List(); string title = "GIG-MIM build plan"; request.Q = "modifiedTime > '2018-04-01T12:00:00' and (name contains 'NPI TLA Plan' or name contains 'NPI Build Plan') "; // request.Q = "name = 'MIM tracker'"; // string parent_id = "0B1auUUiGcbbBOEIyNjg0alkwc3c"; // request.Q = "'" + parent_id + "' in parents"; request.Spaces = "Drive"; request.Fields = "*"; request.PageToken = pageToken; var result = request.Execute(); foreach (var file in result.Files) { // if (file.CreatedTime>System.DateTime.Now.AddMonths(-1)) // if (file.Name.StartsWith("MIM Build Plan ") || file.Name.StartsWith("MIM TLA Plan ")) // { if (file.Name.IndexOf('[') > 0) { ListViewItem item = new ListViewItem(new string[2] { file.Name.Substring(0, file.Name.IndexOf('[') - 1), file.Id }); this.spreadsheetListView.Items.Add(item); } else { ListViewItem item = new ListViewItem(new string[2] { file.Name, file.Id }); this.spreadsheetListView.Items.Add(item); } // } } pageToken = result.NextPageToken; } while (pageToken != null); /* string fileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\currentRackDeliveryPlan.xlsx"; * fileName = fileName.Replace("file:\\", ""); * * Google.Apis.Drive.v3.Data.File file1 = service.Files.Get(fileId).Execute(); * if (this.downloadfile(service, fileId, fileName)) * { * getallSheet(fileName); * // MessageBox.Show("File has been downloaded"); * * }*/ }
/// <summary> /// Authorise the app from the cloud API via the implemented connector /// </summary> protected override bool Authorise() { try { bool runLocally = (System.Configuration.ConfigurationManager.AppSettings["RunLocally"].ToString() == "true"); ///Toggle between the debug mode and potentially the firewall access issues if (!runLocally) { ///Running over the azure string authRedirectURL = String.Empty; authRedirectURL = "https://googledrivewatcher.azurewebsites.net/Home/SubscribeStorageChanges"; //authRedirectURL = "http://*****:*****@gmail.com"; string accessToken = string.Empty; accessToken = serStatus.access_token; if (!string.IsNullOrEmpty(accessToken)) { // This is where you want to add the code if login is successful. // getgoogleplususerdataSer(accessToken); var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = secrets.ClientId, ClientSecret = secrets.ClientSecret }, Scopes = _scopes, DataStore = new AppDataFileStore(".credentials") }); var token = new TokenResponse { AccessToken = accessToken, RefreshToken = serStatus.refresh_token }; _credential = new UserCredential(flow, serStatus.id_token, token); return(_credential != null); } } } } } else { //Below code does not work in Azure it is not allowed to mimic the browser using (var stream = new FileStream(HttpContext.Current.Request.MapPath("~/client_secret.json"), FileMode.Open, FileAccess.Read)) { //string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); string credPath = HttpContext.Current.Request.MapPath("~/App_Data/.credentials/drive.googleapis.com-dotnet-quickstart.json"); //credPath = Path.Combine(credPath, ".credentials\\drive.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); } return(_credential != null); //Use the code exchange flow to get an access and refresh token. //IAuthorizationCodeFlow flow = // new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer // { // ClientSecrets = secrets, // Scopes = _scopes // }); } } catch (Exception ex) { //throw new Exception(ex.Message, ex); ETL.Logging.Logger.Write(new ETL.Logging.LogEntry { Message = ex.Message }); return(false); } return(false); }
public bool Execute(AnimeFile file) { 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 Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); /* * var req = service.Files.List(); * req.PageSize = 30; * req.Fields = "nextPageToken, files(id, name, parents)"; * * var resf = req.Execute().Files; */ FileInfo fi = new FileInfo(file.encodePath); fileSize = fi.Length; var uploadStream = new FileStream(file.encodePath, FileMode.Open, FileAccess.Read); var insertRequest = service.Files.Create( new GFile { Name = fi.Name, Parents = new List <string> { "0Bwyizu5RNSItY3N4WXExVHhPUnM" } }, uploadStream, "application/octet-stream" ); insertRequest.ChunkSize = ChunkSize * 1024 * 1024; insertRequest.ProgressChanged += Upload_ProgressChanged; insertRequest.ResponseReceived += Upload_ResponseReceived; Console.WriteLine("Uploading: " + fi.Name); var createFileTask = insertRequest.UploadAsync(); createFileTask.ContinueWith(t => { uploadStream.Dispose(); }).Wait(); if (createFileTask.Result.Status != UploadStatus.Failed) { file.fileStatus = FileStatus.UPLOAD; db.FlushData(); } return(true); }
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 = "1decwKsk9kd8FqJP5nAVwAcKoaUYvwe9DFAZNEE5gjPQ"; String range = "Ark1!A2:C999"; 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; int i = 0; if (File.Exists(programPath)) { File.Delete(programPath); } if (values != null && values.Count > 0) { foreach (var row in values) { // Print columns A and E, which correspond to indices 0 and 4. Console.WriteLine("{0}, {1}, {2}", values[i][0], values[i][1], values[i][2]); File.AppendAllText(programPath, values[i][0] + "," + values[i][1] + "," + values[i][2] + ";"); i++; } } else { Console.WriteLine("Error! CODE 2: Could not find data in Sheet or Sheet does not exists"); Console.Read(); } using (WebClient webclient = new WebClient()) { webclient.Credentials = new NetworkCredential("focuslock.dk", "bagebe"); webclient.UploadFile("ftp://ftp.focuslock.dk/ftp/Programs.begeba", programPath); Console.Read(); } }
/* Called by Form1's load event to start processing code*/ public static void InitApp() { UserCredential credential; //Initialize credentials 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; Debug.WriteLine("Credential file saved to: " + credPath); } // Create Gmail API service. service = new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); //Create the directories to store orders try { Directory.CreateDirectory(GrubHubDir); Directory.CreateDirectory(DoorDashDir); Directory.CreateDirectory(HistoryIdDir); Directory.CreateDirectory(iTextLicenseDir); Directory.CreateDirectory(DoorDashDebugDir); Directory.CreateDirectory(ErrorLogDir); } catch (Exception e) { Debug.WriteLine(e.ToString()); } //If this mode is on, then we're just going to handle the testMessageID if (debugMailMode) { Order order = HandleMessage(testMessageId); bool isAdjustedOrder = ThreadHasAdjustedOrders(testMessageId); if (order != null) { UpdateOrderList(order, isAdjustedOrder); } return; } //We check if we need to perform a full sync or a partial sync //If the file doesn't exist, this is the first time running the app, so execute full sync if (!File.Exists(HistoryIdPath)) { FullSyncAppToEmail(); } //PartialSyncAppToEmail(); //The timer continously runs in the background to check the email for new messages const int dueTime = 1000; const int period = 4000; //in miliseconds timer = new TimerT(CheckEmail, "Testing123", dueTime, period); }
public static async Task Main(string[] args) { var config = new ConfigurationBuilder() .AddJsonFile("appSettings.json", true, true) .AddUserSecrets <Program>() .Build(); var tableStorage = new AzureTableStorage(config["StorageAccountConnectionString"]); var storageAccount = CloudStorageAccount.Parse(config["StorageAccountConnectionString"]); var globalSearchTermRepository = new GlobalSearchTermRepository(); var searchClient = new SearchServiceClient("sw5esearch", new SearchCredentials(config["SearchKey"])); var clientSecrets = new ClientSecrets { ClientId = config["GoogleApiClientId"], ClientSecret = config["GoogleApiClientSecret"] }; var googleCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync( clientSecrets, Scopes, "user", CancellationToken.None); // Create Google Sheets API service. var sheetsService = new SheetsService(new BaseClientService.Initializer { HttpClientInitializer = googleCredential, ApplicationName = ApplicationName }); var serviceProvider = new ServiceCollection() .AddSingleton <ITableStorage>(tableStorage) .AddSingleton(storageAccount) .AddSingleton(globalSearchTermRepository) .AddSingleton(searchClient) .AddSingleton(sheetsService) .BuildServiceProvider(); var languages = config["Languages"].Split(','); if (!languages.Any()) { Console.WriteLine("No languages found."); return; } foreach (var language in languages) { var languageEnum = Enum.TryParse <Language>(language, true, out var parsedLanguage) ? parsedLanguage : Language.None; if (languageEnum == Language.None) { Console.WriteLine($"Language {language} not supported."); return; } var stringsClass = LocalizationFactory.Get(languageEnum); await ParseContent.Parse(serviceProvider.GetService <ITableStorage>(), serviceProvider.GetService <CloudStorageAccount>(), serviceProvider.GetService <GlobalSearchTermRepository>(), stringsClass, serviceProvider.GetService <SearchServiceClient>()); } }
/// <summary> /// The main entry point for the application. /// </summary> public static void Main(string[] args) { Console.WriteLine("This application generates an OAuth2 refresh token for use with " + "the Google Ads API .NET client library. To use this application\n" + "1) Follow the instructions on https://developers.google.com/adwords/api/docs/" + "guides/authentication#create_a_client_id_and_client_secret to generate a new " + "client ID and secret.\n2) Enter the client ID and client Secret when prompted.\n" + "3) Once the output is generated, copy its contents into your " + "App.config file.\n\n"); // Accept the client ID from user. Console.Write("Enter the client ID: "); string clientId = Console.ReadLine(); // Accept the client ID from user. Console.Write("Enter the client secret: "); string clientSecret = Console.ReadLine(); // Should API scopes include AdWords API? string useAdWordsApiScope = AcceptInputWithLimitedOptions( "Authenticate for AdWords API?", new string[] { "yes", "no" }); // Should API scopes include AdWords API? string useDfpApiScope = AcceptInputWithLimitedOptions("Authenticate for DFP API?", new string[] { "yes", "no" }); // Accept any additional scopes. Console.Write("Enter additional OAuth2 scopes to authenticate for (space separated): "); string additionalScopes = Console.ReadLine(); List <string> scopes = new List <string>(); if (useAdWordsApiScope.ToLower().Trim() == "yes") { scopes.Add(ADWORDS_API_SCOPE); } if (useDfpApiScope.ToLower().Trim() == "yes") { scopes.Add(DFP_API_SCOPE); } scopes.AddRange(additionalScopes.Split(' ').Select(s => s.Trim()) .Where(s => !string.IsNullOrEmpty(s))); // Load the JSON secrets. ClientSecrets secrets = new ClientSecrets() { ClientId = clientId, ClientSecret = clientSecret }; try { // Authorize the user using installed application flow. Task <UserCredential> task = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, String.Empty, CancellationToken.None, new NullDataStore()); task.Wait(); UserCredential credential = task.Result; Console.WriteLine("\nCopy the following content into your App.config file.\n\n" + $"<add key = 'OAuth2Mode' value = 'APPLICATION' />\n" + $"<add key = 'OAuth2ClientId' value = '{clientId}' />\n" + $"<add key = 'OAuth2ClientSecret' value = '{clientSecret}' />\n" + $"<add key = 'OAuth2RefreshToken' " + $"value = '{credential.Token.RefreshToken}' />\n"); Console.WriteLine("Press <Enter> to continue..."); Console.ReadLine(); } catch (AggregateException) { Console.WriteLine("An error occured while authorizing the user."); } }
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", "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.Console.Update("Unable to authenticate with Google. The following error occurred:<br/>" + ex.Message, Console.Markup.error); } } catch (System.Exception ex) { OGCSexception.Analyse(ex); MainForm.Instance.Console.Update("Unable to authenticate with Google. The following error occurred:<br/>" + ex.Message, Console.Markup.error); } 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 try { GoogleOgcs.Calendar.Instance.Service.Settings.Get("useKeyboardShortcuts").Execute(); } catch (System.Exception ex) { OGCSexception.Analyse(ex); MainForm.Instance.Console.Update("Unable to communicate with Google services.", Console.Markup.warning); authenticated = false; return; } log.Debug("Access token refreshed."); } getGaccountEmail(credential.Token.AccessToken); authenticated = true; }
/// <summary> /// GoogleFit投稿処理 /// </summary> /// <param name="config"></param> /// <returns></returns> public static async Task postGoogleFit(IConfiguration config) { UserCredential credential; credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = config.GetSection("AppSettings")["ClientId"], ClientSecret = config.GetSection("AppSettings")["ClientSecret"] }, new string[] { FitnessService.Scope.FitnessBodyRead, FitnessService.Scope.FitnessBodyWrite }, "user", CancellationToken.None, new FileDataStore("GoogleFitnessAuth", true)//trueにするとカレントパスに保存 ); var fitnessService = new FitnessService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = Assembly.GetExecutingAssembly().GetName().Name }); var dataSource = new DataSource() { Type = "derived", DataStreamName = "GoogieFitTestDataSource", Application = new Application() { Name = "TanitaHealthPlanet", Version = "1" }, DataType = new DataType() { Name = dataTypeName, Field = new List <DataTypeField>() { new DataTypeField() { Name = "weight", Format = "floatPoint" } } }, Device = new Device() { Manufacturer = "Tanita", Model = "RD-906", Type = "scale", Uid = "1000001", Version = "1.0" } }; var dataSourceId = $"{dataSource.Type}:{dataSource.DataType.Name}:{config.GetSection("AppSettings")["ClientId"].Split('-')[0]}:{dataSource.Device.Manufacturer}:{dataSource.Device.Model}:{dataSource.Device.Uid}:{dataSource.DataStreamName}"; var dataSrcList = await fitnessService.Users.DataSources.List(userId).ExecuteAsync(); if (dataSrcList.DataSource.Select(s => s.DataStreamId).Any(s => s == dataSourceId)) { dataSource = fitnessService.Users.DataSources.Get(userId, dataSourceId).Execute(); } else { dataSource = fitnessService.Users.DataSources.Create(dataSource, userId).Execute(); } var postNanosec = GetUnixEpochNanoSeconds(DateTime.UtcNow); var widthDataSource = new Dataset() { DataSourceId = dataSourceId, MaxEndTimeNs = postNanosec, MinStartTimeNs = postNanosec, Point = new List <DataPoint>() { new DataPoint() { DataTypeName = dataTypeName, StartTimeNanos = postNanosec, EndTimeNanos = postNanosec, Value = new List <Value>() { new Value() { FpVal = 80.0 } } } } }; var dataSetId = $"{postNanosec}-{postNanosec}"; await fitnessService.Users.DataSources.Datasets.Patch(widthDataSource, userId, dataSourceId, dataSetId).ExecuteAsync(); }
public static async Task SyncGoogleContactsAsync() { var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync( new Uri("ms-appx:///Assets/client_secrets.json"), new[] { ContactsService.Scope.FullContacts, Oauth2Service.Scope.UserinfoProfile, Oauth2Service.Scope.UserinfoEmail }, "user", CancellationToken.None); await SyncProfileContactImage(); var services = new ContactsService(new BaseClientService.Initializer() { ApplicationName = "WhassApp Windows 8", HttpClientInitializer = credential }); var oauthSerivce = new Oauth2Service(new BaseClientService.Initializer() { ApplicationName = "WhassApp Windows 8", HttpClientInitializer = credential }); var userInfo = await oauthSerivce.Userinfo.Get().ExecuteAsync(); List <string> numberList = new List <string>(); try { PhoneNumbers.PhoneNumberUtil util = PhoneNumbers.PhoneNumberUtil.GetInstance(); ContactList response = await services.Contact.Get(userInfo.Email).ExecuteAsync(); foreach (var c in response.Feed.Entries) { if (c.PhoneNumbers != null) { string phoneNumber = String.Empty; if (c.PhoneNumbers.FirstOrDefault().Text != null) { try { PhoneNumbers.PhoneNumber num = util.Parse(c.PhoneNumbers.FirstOrDefault().Text, "ID"); phoneNumber = num.CountryCode.ToString() + num.NationalNumber.ToString(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception was thrown: " + ex.Message); continue; } } AddContact(new Contacts() { name = c.Name.Text, phoneNumber = phoneNumber }); var check = GetContactByPhoneNumber(phoneNumber); if (check == null) { numberList.Add(phoneNumber); } } } } catch (Google.GoogleApiException ex) { } SocketInstance.Instance.OnGetSyncResult += Instance_OnGetSyncResult; SocketInstance.Instance.SendSync(numberList.ToArray(), Libs.Constants.Enums.SyncMode.Delta, Libs.Constants.Enums.SyncContext.Background); }
public static IConfigurableHttpClientInitializer authenticate( BaseConfig config, string scope) { String[] scopes = new[] { scope }; try { GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result; Console.WriteLine("Using Application Default Credentials."); return(credential.CreateScoped(scopes)); } catch (AggregateException) { // Do nothing, we'll just let it slide and check the others. } if (config.ConfigDir == null) { throw new ArgumentException( "Must use Google Application Default Credentials when running without a " + "configuration directory"); } String oauthFilePath = Path.Combine(config.ConfigDir, "client-secrets.json"); String serviceAccountPath = Path.Combine(config.ConfigDir, "service-account.json"); if (File.Exists(serviceAccountPath)) { Console.WriteLine("Loading service account credentials from " + serviceAccountPath); using (FileStream stream = new FileStream( serviceAccountPath, FileMode.Open, FileAccess.Read)) { GoogleCredential credential = GoogleCredential.FromStream(stream); return(credential.CreateScoped(scopes)); } } else if (File.Exists(oauthFilePath)) { Console.WriteLine("Loading OAuth2 credentials from " + oauthFilePath); using (FileStream oauthFile = File.Open(oauthFilePath, FileMode.Open, FileAccess.Read)) { var clientSecrets = GoogleClientSecrets.Load(oauthFile).Secrets; var userId = "unused"; TokenResponse token = LoadToken(config, scope); if (token != null) { Console.WriteLine("Loading old access token."); try { var init = new GoogleAuthorizationCodeFlow.Initializer() { ClientSecrets = clientSecrets, Scopes = scopes }; var flow = new GoogleAuthorizationCodeFlow(init); UserCredential storedCred = new UserCredential(flow, userId, token); // Want to try and test and make sure we'll actually be able to // use these credentials. if (!storedCred.RefreshTokenAsync(CancellationToken.None).Result) { throw new InvalidDataException(); } return(storedCred); } catch (InvalidDataException) { Console.WriteLine("Failed to load old access token."); // Ignore, we'll just reauthenticate below. } } UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( clientSecrets, scopes, userId, CancellationToken.None).Result; StoreToken(config, credential.Token); return(credential); } } Console.WriteLine("Could not find authentication credentials. Checked:"); Console.WriteLine(" - Google Application Default Credentials"); Console.WriteLine(" - " + serviceAccountPath); Console.WriteLine(" - " + oauthFilePath); Console.WriteLine("Please read the included README for instructions."); return(null); }
private void set_schedule_highlight() { 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/calendar-dotnet-quickstart"); 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, }); DateTime today = DateTime.Today; int days = DateTime.DaysInMonth(today.Year, today.Month); int start_day_of_month = (int)today.AddDays(-today.Day + 1).DayOfWeek; int days_in_month = DateTime.DaysInMonth(today.Year, today.Month); // Define parameters of request. EventsResource.ListRequest request = service.Events.List("primary"); request.TimeMin = today.AddDays(-today.Day + 1); request.TimeMax = today.AddDays(-today.Day + 1 + days_in_month); request.ShowDeleted = false; request.SingleEvents = true; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // List events. events = request.Execute(); Console.WriteLine("Upcoming events:"); if (events.Items != null && events.Items.Count > 0) { foreach (var eventItem in events.Items) { try { DateTime start_date = DateTime.ParseExact( eventItem.Start.Date, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); DateTime end_date = DateTime.ParseExact( eventItem.End.Date, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);; while (start_date != end_date) { int row = (start_date.Day + start_day_of_month - 1) / 7, col = (int)start_date.DayOfWeek; highlight(row, col, Highlight.SCHEDULE); start_date = start_date.AddDays(1); } } catch (Exception e) { Console.WriteLine(e.ToString()); } } } else { Console.WriteLine("No upcoming events found."); } }
public static string UploadFile(string base64File, string fileTitle, string fileType) { UserCredential credential; var fileCategory = ""; if (fileType == "jpg") { fileCategory = "image/jpeg"; } else if (fileType == "pdf") { fileCategory = "application/pdf"; } 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 Drive API service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = ApplicationName, }); var fileMetadata = new Google.Apis.Drive.v3.Data.File() { Name = fileTitle + "." + fileType }; Byte[] bytes = Convert.FromBase64String(base64File); FilesResource.CreateMediaUpload request; using (var stream = new MemoryStream(bytes)) { request = service.Files.Create(fileMetadata, stream, fileCategory); request.Fields = "id, webViewLink"; request.Upload(); } var file = request.ResponseBody; Console.WriteLine("File ID: " + file.Id); Console.WriteLine("File URL: " + file.WebViewLink); Permission newPermission = new Permission(); newPermission.Type = "anyone"; newPermission.Role = "reader"; service.Permissions.Create(newPermission, file.Id).Execute(); return(file.WebViewLink); }
/** * Returns a list of upcoming events on a user's calender * This is most just a proof of concept of integration with the Google Calendar API */ public List <String> getEvents() { UserCredential credential; string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "", "client_secret.json"); using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { string credPath = System.Environment.GetFolderPath( System.Environment.SpecialFolder.Personal); credPath = Path.Combine(credPath, ".credentials/calendar-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, }); // 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 <string> eventInfo = new List <string>(); // List events. Events events = request.Execute(); Console.WriteLine("Upcoming events:"); if (events.Items != null && events.Items.Count > 0) { //create list of events, as strings 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); eventInfo.Add(eventItem.Summary + " " + when); } } else { Console.WriteLine("No upcoming events found."); eventInfo.Add("No upcoming events found"); } return(eventInfo); }