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.
Related
How to stop my livestream in YouTube while completed my live telecast using c#
How to stop the livestream Using c# Code, can you please give some suggestion
string[] scopes = { "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.upload" };
var creadentails = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = YTPublishSettings.PublisherClientId,
ClientSecret = YTPublishSettings.PublisherClientSecret,
},
scopes, "user", default).Result;
if (creadentails.Token.IsExpired(SystemClock.Default))
creadentails.RefreshTokenAsync(CancellationToken.None).Wait();
var secrets = new ClientSecrets
{
ClientId = YTPublishSettings.PublisherClientId,
ClientSecret = YTPublishSettings.PublisherClientSecret,
};
var token = new TokenResponse { RefreshToken = creadentails.Token.RefreshToken };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets }),
"user", token);
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = credentials,
ApplicationName = "**************",
});
var broadcast = new LiveStream
{
Cdn = new CdnSettings
{
FrameRate = "35fps",
IngestionType = "rtmp",
Resolution = "720p"
},
Snippet = new LiveStreamSnippet
{
Description = Description,
Title = Title,
},
};
var request = service.LiveStreams.Delete(YTPublishSettings.PublisherId);
var response = request.Execute();
return new YouTubeStreamDeleteStatus()
{
success = "Deleted",
};
How can end My YouTube live stream API in 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",
});
I am having trouble integrating Google Drive in my ASP.NET web application. It is not showing up the consent screen where user can enter his/her Google credentials to authorize my application.
Below is my code:
String CLIENT_ID = "XXXXXX";
String CLIENT_SECRET = "XXXXXX";
String APP_USER_AGENT = "<Application - Name>";
string[] scopes = new string[] { DriveService.Scope.Drive };
DriveService service=null;
try
{
var dbDataStore = new DatabaseDataStore("<DBServer>", "<DBUser>", "<Pwd>", "<DataBase>");
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = CLIENT_ID, ClientSecret = CLIENT_SECRET },
scopes, Convert.ToString(Session["UserId"]), CancellationToken.None, dbDataStore).Result;
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = APP_USER_AGENT,
});
}
catch (Exception ex)
{
}
My understanding for every google api calls we should get permission
https://developers.google.com/identity/protocols/OpenIDConnect#consentpageexperience
You could use https://admin.google.com/AdminHome?chromeless=1#OGX:ManageOauthClients for overriding the permission
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?
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"
});