I added credentials.json in my project. I wrote some code which must make new event in my calendar. When I run my code I also check my Google Calendar but I see there no new event which must be made by my code. Also I don't see token.json in bin/debug folder. How can I solve that issue?
P.S I use the same account
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Highsoft.Web.Mvc.Charts;
using Highsoft.Web.Mvc.Charts.Rendering;
namespace Kyrsovoi
{
public partial class Form1 : Form
{
static string[] Scopes = { CalendarService.Scope.Calendar };
static string ApplicationName = "Google Calendar API .NET Quickstart";
public Form1()
{
InitializeComponent();
}
private void GoogleAPI()
{
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,
});
// 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();
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
{
}
var ev = new Event();
EventDateTime start = new EventDateTime();
start.DateTime = new DateTime(2020, 10, 17, 11, 0, 0);
EventDateTime end = new EventDateTime();
end.DateTime = new DateTime(2020, 10, 17, 11, 30, 0);
ev.Start = start;
ev.End = end;
ev.Summary = "MyEvent";
ev.Description = "TestScription";
var calendarId = "primary";
Event recurringEvent = service.Events.Insert(ev, calendarId).Execute();
Console.WriteLine("Event created: %s\n", ev.HtmlLink);
}
private void button1_Click(object sender, EventArgs e)
{
Form2 newForm = new Form2();
newForm.Show();
}
private void button2_Click(object sender, EventArgs e)
{
Form3 newForm1 = new Form3();
newForm1.Show();
}
private void button3_Click(object sender, EventArgs e)
{
}
}
}
When you have an app that you are testing it hasn't been verified yet. You will see the following screen.
press advanced
If you press the Advanced button you will see the following
authorize the app.
This will let you authorize an unverified application.
Related
I am creating a login form using Xamarin which accepts email, password fields.
After the user enters his details and clicks on login button, no alert box is displayed. It comes out of the app. Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlTypes;
using Xamarin.Forms;
using SQLite;
using System.IO;
namespace LoginPage.Views
{
public class AddDetails : ContentPage
{
private Entry _emailEntry;
private Entry _passwordEntry;
private Button _saveButton;
string _dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "myDB.db3");
public AddDetails()
{
this.Title = "Add Details";
StackLayout stackLayout = new StackLayout();
_emailEntry = new Entry();
_emailEntry.Keyboard = Keyboard.Text;
_emailEntry.Placeholder = "Email";
stackLayout.Children.Add(_emailEntry);
_passwordEntry = new Entry();
_passwordEntry.Keyboard = Keyboard.Text;
_passwordEntry.Placeholder = "Password";
stackLayout.Children.Add(_passwordEntry);
_saveButton = new Button();
_saveButton.Text = "Login User";
_saveButton.Clicked += _saveButton_Clicked;
stackLayout.Children.Add(_saveButton);
Content = stackLayout;
}
private async void _saveButton_Clicked(object Sender, EventArgs e)
{
var db = new SQLiteConnection(_dbPath);
db.CreateTable<User>();
var maxPk = db.Table<User>().OrderByDescending(c => c.Id).FirstOrDefault();
User user = new User()
{
Id = (maxPk == null ? 1 : Convert.ToInt32(maxPk.Id) +1),
Email = _emailEntry.Text,
Password = _passwordEntry.Text
};
db.Insert(user);
await DisplayAlert(null, user.Email + "Saved", "Ok");
await Navigation.PopAsync();
}
}
}
Login screen gets displayed, but no alert box which should say Email saved. Also, it comes out of the app abruptly
Have you set
MainPage = new NavigationPage (new Page1Xaml ());
Please follow this link
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/
Actually when i use to execute my program , each time i need new login code to login into Telegram.So i need help in this regard that login code should be saved and not to feed each time the new login code.
Here is my code:
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using TeleSharp.TL;
using TLSharp.Core;
namespace Telegram
{
public partial class Form1 : Form
{ string hash = String.Empty;
public Form1()
{
InitializeComponent();
}
private async void button2_Click(object sender, EventArgs e)
{
string code = textBox2.Text;
TelegramClient client = Utility.Client;
var user = await client.MakeAuthAsync("SENDER_MOBILE", hash, code);
var result = await client.GetContactsAsync();
//find recipient in contacts
var user1 = result.users.lists.Where(x => x.GetType() == typeof(TLUser)).Cast<TLUser>().FirstOrDefault(x => x.phone == "RECEIVER_MOBILE");
//send message
// await client.SendMessageAsync(new TLInputPeerUser() { user_id = user1.id }, "Hiii,Welcome to Telegram");
this.Hide();
Form2 ss = new Form2();
ss.Show();
}
private async void button1_Click(object sender, EventArgs e)
{
Utility.Client = new TelegramClient(APP_ID, "APP_SECRET");
TelegramClient client = Utility.Client;
await client.ConnectAsync();
hash = await client.SendCodeRequestAsync("MY_MOBILE_NUMBER");
button2.Enabled = true;
}
}
}
In my class that i'm using to upload to youtube a video files and it's working fine the uploading i want to make something that on the form designer i will have a button of a gmail account when i click this button it will make two things:
Will upload the video file to the account of this button.
For example the text on the button will be test#gmail.com
So when i click the button it will check and if there is already a user connected on the pc to gmail account and if it's not test#gmail.com then first make revoke then connect to the test#gmail.com and upload the video file.
But in case there no gmail account yet connected on the pc then the user will enter a gmail account it will connect to it and upload.
Will revoke.
The problem now is that i have one button that all it does is revoking.
And i need to change on the browser in this case chrome the gmail account or to log in to a gmail account then running my program over again then it will showm e this screen where i need to accept the authorization to this acocunt then it will upload to it the video file.
And i want to pass over the part of log in each time to another gmail via the chrome browser and pass over the need of making accept over again each time changing account.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Google.GData.Client;
using Google.GData.Extensions;
using System.Reflection;
using System.IO;
using System.Threading;
using System.Net;
using Google.Apis.YouTube;
using Google.Apis.Requests;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail;
using MailBee;
namespace test
{
public partial class testing : Form
{
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
YouTubeService service;
string apiKey = "myapikey";
string FileNameToUpload = "";
string[] stringProgressReport = new string[5];
long totalBytes = 0;
DateTime dt;
public static string fileuploadedsuccess = "";
public Youtube_Uploader(string filetoupload)
{
InitializeComponent();
FileNameToUpload = #"C:\Users\test\Videos\test.mp4";
service = AuthenticateOauth(apiKey);
var videoCatagories = service.VideoCategories.List("snippet");
videoCatagories.RegionCode = "IL";
var result = videoCatagories.Execute();
UserCredentials();
UserYoutubeService();
MakeRequest();
backgroundWorker1.RunWorkerAsync();
}
public static string uploadstatus = "";
Video objects = null;
private void videosInsertRequest_ResponseReceived(Video obj)
{
System.Timers.Timer aTimer;
aTimer = new System.Timers.Timer();
aTimer.Elapsed += aTimer_Elapsed;
aTimer.Interval = 10000;
aTimer.Enabled = false;
uploadstatus = obj.Status.UploadStatus;
if (uploadstatus == "uploaded")
{
fileuploadedsuccess = "file uploaded successfully";
}
if (uploadstatus == "Completed")
{
fileuploadedsuccess = "completed";
}
objects = obj;
}
double mbSent = 0;
int percentComplete = 0;
VideoProcessingDetailsProcessingProgress vp = new VideoProcessingDetailsProcessingProgress();
private void videosInsertRequest_ProgressChanged(IUploadProgress obj)
{
ulong? ul = vp.TimeLeftMs;
stringProgressReport[1] = obj.Status.ToString();
mbSent = ((double)obj.BytesSent) / (1 << 20);
stringProgressReport[2] = mbSent.ToString();
percentComplete = (int)Math.Round(((double)obj.BytesSent) / totalBytes * 100);
stringProgressReport[3] = percentComplete.ToString();
if (obj.BytesSent != 0)
{
var currentTime = DateTime.Now;
TimeSpan diff = currentTime - dt;
double diffSeconds = (DateTime.Now - dt).TotalSeconds;
double averageSpeed = obj.BytesSent / diffSeconds;
double MBunits = ConvertBytesToMegabytes((long)averageSpeed);
stringProgressReport[4] = string.Format("{0:f2} MB/s", MBunits);
}
}
public static YouTubeService AuthenticateOauth(string apiKey)
{
try
{
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
ApiKey = apiKey,
ApplicationName = "YouTube Uploader",
});
return service;
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException);
return null;
}
}
private void MakeRequest()
{
var searchListRequest = service.Search.List("snippet");
searchListRequest.Q = "daniel lipman gta"; // Replace with your search term.
searchListRequest.RegionCode = "IL";
searchListRequest.MaxResults = 50;
var searchListResponse = searchListRequest.Execute();
List<string> videos = new List<string>();
List<string> channels = new List<string>();
List<string> playlists = new List<string>();
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
case "youtube#channel":
channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
break;
case "youtube#playlist":
playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
break;
}
}
}
static Video video = new Video();
public void Revoke()
{
if (uc!=null)
{
uc.RevokeTokenAsync(CancellationToken.None);
}
}
UserCredential uc = null;
private void UploadVideo(string FileName, string VideoTitle, string VideoDescription)
{
try
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
video.Snippet = new VideoSnippet();
video.Snippet.Title = VideoTitle;
video.Snippet.Description = VideoDescription;
video.Snippet.Tags = new string[] { "tag1", "tag2" };
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public";
using (var fileStream = new FileStream(FileName, FileMode.Open))
{
const int KB = 0x400;
var minimumChunkSize = 256 * KB;
var videosInsertRequest = youtubeService.Videos.Insert(video,
"snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged +=
videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived +=
videosInsertRequest_ResponseReceived;
// The default chunk size is 10MB, here will use 1MB.
videosInsertRequest.ChunkSize = minimumChunkSize * 3;
dt = DateTime.Now;
videosInsertRequest.Upload();
}
}
catch (Exception errors)
{
string errorss = errors.ToString();
}
}
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
private void Youtube_Uploader_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
UploadVideo(FileNameToUpload, "test", "Testing");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Revoke();
}
UserCredential credential = null;
private void UserCredentials()
{
using (FileStream stream = new FileStream(#"C:\jason file\client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None,
new FileDataStore("YouTube.Auth.Store")).Result;
}
uc = credential;
}
private void UserYoutubeService()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
}
}
}
In this class i have this part:
private void button1_Click(object sender, EventArgs e)
{
Revoke();
}
And
public void Revoke()
{
if (uc!=null)
{
uc.RevokeTokenAsync(CancellationToken.None);
}
}
And the user credential
UserCredential credential = null;
private void UserCredentials()
{
using (FileStream stream = new FileStream(#"C:\jason file\client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None,
new FileDataStore("YouTube.Auth.Store")).Result;
}
uc = credential;
}
The problem is that this GoogleWebAuthorizationBroker show the screen that i need to accept each time i did revoke.
Also a problem is how to check using the GoogleWebAuthorizationBroker if there is any user logged in already on the pc to gmail and get the gmail address.
And then to decide if to revoke or not and also how to connect to a gmail account using the GoogleWebAuthorizationBroker.
I'm using the google api.
I know how to upload a video to Youtube using Youtube API within C#
But I'd like to use the Youtube API to return a date when a particular user last uploaded a video.
My code for uploading a video using C# is below, but I really don't know how to do the above???
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.GData.Client;
using Google.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.GData.YouTube;
using Google.GData.Extensions.Location;
namespace UploadLimit
{
public partial class Form1 : Form
{
string key = "somegarbage";
string appName = "SlowUpload";
string username = "blarg";
string password = "blarg";
public Form1()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
txtFile.Text = dialog.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
YouTubeRequestSettings settings = new YouTubeRequestSettings(appName, key, username, password);
YouTubeRequest request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = "My Test Movie";
newVideo.Tags.Add(new MediaCategory("Autos", YouTubeNameTable.CategorySchema));
newVideo.Keywords = "cars, funny";
newVideo.Description = "My description";
newVideo.YouTubeEntry.Private = false;
newVideo.Tags.Add(new MediaCategory("mydevtag, anotherdevtag",
YouTubeNameTable.DeveloperTagSchema));
newVideo.YouTubeEntry.Location = new GeoRssWhere(37, -122);
// alternatively, you could just specify a descriptive string
// newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(txtFile.Text, "video/quicktime");
Video createdVideo = request.Upload(newVideo);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UploadLimit
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
You can get all the user's videos and get the latest date:
var videos = new YouTubeRequest().GetVideoFeed(userId).Entries
DateTime lastUploadDate = videos.Max(video => video.YouTubeEntry.Published)
To get the actual video's title:
var lastVideo = videos.Where(video => video.YouTubeEntry.Published == lastUploadDate).First();
var name = lastVideo.Title
I wrote a simple image uploader in C#. Here's my code:
using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace Snappx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GlobalHook.HookManager.KeyUp += new KeyEventHandler(MyKeyUp);
CheckForIllegalCrossThreadCalls = false;
new Task(this.Hide).Start();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(-1);
}
string ORIGINIM;
async void MyKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.PrintScreen)
{
await GetImage();
e.Handled = true;
}
else e.Handled = false;
}
String img = #"temp";
async Task GetImage()
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save(img, ImageFormat.Png);
}
using (var w = new WebClient())
{
var values = new NameValueCollection { { "key", "85684005b7d4faa4c33ee480010d4982" }, { "image", Convert.ToBase64String(File.ReadAllBytes(img)) } };
notifyIcon1.ShowBalloonTip(3, "Uploading", "Uploading image to Imgur", ToolTipIcon.Info);
w.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
Task<byte[]> x = w.UploadValuesTaskAsync(new Uri("http://imgur.com/api/upload.xml"), values);
byte[] response = await x;
while (w.IsBusy) System.Threading.Thread.Sleep(500);
File.Delete(img);
ORIGINIM = Convert.ToString(XDocument.Load(new MemoryStream(response)));
ORIGINIM = ORIGINIM.Substring(ORIGINIM.LastIndexOf("<original_image>")).Replace("<original_image>", "");
ORIGINIM = ORIGINIM.Substring(0, ORIGINIM.LastIndexOf("</original_image>")).Replace("</original_image>", "");
Clipboard.SetText(ORIGINIM);
if (!File.Exists(#"Uploads.txt")) File.Create(#"Uploads.txt");
new StreamWriter(#"Uploads.txt").WriteLine(ORIGINIM);
notifyIcon1.ShowBalloonTip(3, "Done", "URL copied to clipboard.", ToolTipIcon.Info);
}
}
private void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
int percentage = e.ProgressPercentage * 2;
notifyIcon1.ShowBalloonTip(3, "Uploading", (percentage).ToString() + "%", ToolTipIcon.Info);
}
}
}
First of all, when there is no Uploads.txt file, it returns an Exception handler. Then second time I run it, it creates it. Is there any simpler way to store it?
Second question:
Am I able to add two different options, one for capture full screen and one for select screen region.
How could I integrate it with my code? Could you post it?
Instead of (!File.Exists(#"Uploads.txt")) File.Create(#"Uploads.txt") try this
using (StreamWriter sw = new StreamWriter(File.Open(#"Uploads.txt", FileMode.OpenOrCreate)))
{
sw.WriteLine(ORIGINIM);
}
The reason why it worked on the second try is because you didn't create a lock on the file with File.Create - the existing logic opens the file, which creates a FileStream, then you attempt to open StreamWriter on the same file. You should instead create the StreamWriter by passing the FileStream into its constructor, as shown in the above example.