How to create a window handle for invoke? - c#

I am trying to fill a checkboxlist clbWiedergabelisten with playlist names of the authenticating user under youtube. This is my code
private async Task RunAbrufen()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for read-only access to the authenticated
// user's account, but not other types of account access.
new[] { YouTubeService.Scope.YoutubeReadonly },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var playlistListRequest = youtubeService.Playlists.List("snippet");
playlistListRequest.Mine = true;
// Retrieve the contentDetails part of the playlist resource for the authenticated user's playlist.
var playlistListResponse = await playlistListRequest.ExecuteAsync();
this.Invoke((MethodInvoker)delegate
{
clbWiedergabelisten.Items.Clear();
});
foreach (var playlist in playlistListResponse.Items)
{
Console.WriteLine(playlist.Snippet.Title);
this.Invoke((MethodInvoker)delegate
{
clbWiedergabelisten.Items.Add(playlist.Snippet.Title);
});
}
}
it is being run by
try
{
await new Form1().RunAbrufen();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
But each time it says that a window handle has to be created before invoke can be used. How to do that?

Related

How to refresh a Google OAuth2 AccessToken

I have seen a lot of questions about this with varying answers. Some are for different languages. It is not clear to me the correct way to handle this issue.
This is what I have come up with:
public bool Init()
{
UserCredential credential;
ClientSecrets secrets = new ClientSecrets()
{
ClientId = m_ClientID,
ClientSecret = m_ClientSecret
};
if (!m_LogFilePathSet)
return false;
try
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
secrets,
m_Scopes,
"user",
CancellationToken.None,
new FileDataStore("MSAToolsSoftware.GMail.Application")).Result;
if (credential.Token.IsExpired(Google.Apis.Util.SystemClock.Default))
{
var refreshResult = credential.RefreshTokenAsync(CancellationToken.None).Result;
}
var initializer = new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = m_ApplicationName
};
m_Service = new GmailService(initializer);
}
catch(Exception ex)
{
SimpleLog.Log(ex);
return false;
}
return true;
}
Is this the correct way to refresh the access token (if required)?
Thank you.

get all playlist of an user from YouTube. working in api explorer but not in c#

I wanna get all playlists of a channel
all settings works on API explorer but when I try it in the client it not working
other things of youtube data api3 like channel and playlistitems working, my problem is just with playlist.list
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for full read/write access to the
// authenticated user's account.
new[] { YouTubeService.Scope.Youtube },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
var channelVids = youtubeService.Playlists.List("snippet");
channelVids.Id = "UCIabPXjvT5BVTxRDPCBBOOQ";
//channelVids.Fields = "items(id,snippet(description,publishedAt,thumbnails/default/url,title)),nextPageToken";
channelVids.MaxResults = 25;
var results = await channelVids.ExecuteAsync();
Console.WriteLine(results.Items.Count + " lists");
I found my solution
it was just a typo
channelVids.Id = "UCIabPXjvT5BVTxRDPCBBOOQ";
to
channelVids.ChannelId = "UCIabPXjvT5BVTxRDPCBBOOQ";

youtube Add Subscription via C#

I am building a YouTube app for windows 8.1.
I am having a trouble with, add(Insert) subscription is fail
my code:
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
"user",
CancellationToken.None);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
HttpClientInitializer = credential,
ApplicationName = "AppName"
});
Subscription body = new Subscription();
body.Snippet = new SubscriptionSnippet();
body.Snippet.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q";
try
{
var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();
}
catch (Exception e)
{
throw e;
}
When I set a breakpoint at the first line.
when execute to last line, breaks this function
Update(2015-11-14):
Error Message:
The subscription resource specified in the request must use the snippet.resorceId property to identify the channel that is being subscribed to [400]
Successful Code:
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
"user",
CancellationToken.None);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
//ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
HttpClientInitializer = credential,
ApplicationName = "4GameTV"
});
try
{
Subscription body = new Subscription();
body.Snippet = new SubscriptionSnippet();
body.Snippet.ResourceId = new ResourceId();
body.Snippet.ResourceId.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q"; //replace with specified channel id
var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();
}
catch (Exception e)
{
throw e;
}
Your authentication seems a bit off from what I normally use. Also ApiKey is only needed if you want to access public data.
string[] scopes = new string[] { YouTubeService.Scope.Youtube };
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, "test"
, CancellationToken.None
, new FileDataStore("Daimto.YouTube.Auth.Store")).Result;
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "YouTube Data API Sample",
});

GoogleWebAuthorizationBroker.AuthorizeAsync throws an error

i was trying to create and run the sample project given in this link.
here is the code:
namespace GmailQuickstart
{
class Program
{
static string[] Scopes = { GmailService.Scope.GmailReadonly };
static string ApplicationName = "Gmail API Quickstart";
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");
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.LabelsResource.ListRequest request = service.Users.Labels.List("me");
// List labels.
IList<Label> labels= request.Execute().Labels;
Console.WriteLine("Labels:");
if (labels != null && labels.Count > 0)
{
foreach (var labelItem in labels)
{
Console.WriteLine("{0}", labelItem.Name);
}
}
else
{
Console.WriteLine("No labels found.");
}
Console.Read();
}
}
}
after i have done everything stated in google's documentation, including issuing a secrets.json file for my application/product, i ran it.
It fails with an exception, containing a "An invalid argument was supplied" inner exception.
I have retried everything with a new acocunt given new api credentials, etc., and still same error occurs. what am i doing wrong?
Try this
ClientSecrets secrets = new ClientSecrets()
{
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET
};
var token = new TokenResponse { RefreshToken = REFRESH_TOKEN };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets
}),
"user",
token);
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "ApplicationName"
});

GoogleDriveAPI C# Windows-Service

I have a working C# programm which downloads and uploads files from Google Drive. The next step I wanted to do is to run my programm with a service periodically every 5 minutes. The service starts every 5 minutes, but my programm fails to authenticate to the GoogleDrive API (the credentials are null) and I don't know why.
I install and uninstall the service from my GUI program.
Note: I'm new to windows-services
public async Task Run()
{
UserCredential credential = null;
System.IO.FileStream stream = null;
try
{
stream = new System.IO.FileStream(#"C:\Users\carl\Documents\Visual Studio 2013\Projects\ServiceTest1\GoogleDrive\client_secrets.json", System.IO.FileMode.Open, System.IO.FileAccess.Read);
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"Cloud Manager",
CancellationToken.None,
new FileDataStore("ServiceTest1")
).Result;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if(stream != null)
{
stream.Dispose();
}
}
await credential.RefreshTokenAsync(CancellationToken.None);
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "CloudManagerGD",
});
// For debug purpose only.
FileList fl = await service.Files.List().ExecuteAsync();
About about = await service.About.Get().ExecuteAsync();
await GetFiles(service, "trollol", fl);
await PostFiles(service, "trollol", fl);
}

Categories

Resources