How to convert code YouTube API from Console to WPF [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have code worked fine in Console but i tried convert it to WPF c# but i didn't success.
I tried porting each part to WPF and I found out the code below (2nd code I quoted below) when I convert it to WPF it doesn't work
Please help me. How to it work fine in WPF c#
This is my code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace ConsoleApp2
{
internal class PlaylistUpdates
{
public string PrivacyStatus { get; private set; }
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: Playlist Updates");
Console.WriteLine("==================================");
try
{
//new PlaylistUpdates().Run().Wait();
//new PlaylistUpdates().RunUpload().Wait();
new PlaylistUpdates().Editvideo().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Editvideo()
{
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 channelsListRequest = youtubeService.Channels.List("contentDetails");
channelsListRequest.Mine = true;
// Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
var channelsListResponse = await channelsListRequest.ExecuteAsync();
foreach (var channel in channelsListResponse.Items)
{
// From the API response, extract the playlist ID that identifies the list
// of videos uploaded to the authenticated user's channel.
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
Console.WriteLine("Videos in list {0}", uploadsListId);
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet,status");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
// Create a new, private playlist in the authorized user's channel.
var newVideo = new Video();
newVideo.Snippet = new VideoSnippet();
newVideo.Id = "6obQQde1X3A";
newVideo.Snippet.Title = "My Title";
newVideo.Snippet.Description = "My Description";
newVideo.Snippet.Tags = new string[] { "tag 1", "tag 2", "tag 3" };
newVideo.Snippet.CategoryId = "22";
newVideo.Status = new VideoStatus();
newVideo.Status.PrivacyStatus = "public";
newVideo = await youtubeService.Videos.Update(newVideo,"Id,snippet,status").ExecuteAsync();
Console.WriteLine("Change video details OK ....");
// Retrieve the list of videos uploaded to the authenticated user's channel.
var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
foreach (var playlistItem in playlistItemsListResponse.Items)
{
Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
}
}
}
}
If i remove this code below. It worked fine!
// Create a new, private playlist in the authorized user's channel.
var newVideo = new Video();
newVideo.Snippet = new VideoSnippet();
newVideo.Id = "6obQQde1X3A";
newVideo.Snippet.Title = "My Title";
newVideo.Snippet.Description = "My Description";
newVideo.Snippet.Tags = new string[] { "tag 1", "tag 2", "tag 3" };
newVideo.Snippet.CategoryId = "22";
newVideo.Status = new VideoStatus();
newVideo.Status.PrivacyStatus = "public";
newVideo = await youtubeService.Videos.Update(newVideo,"Id,snippet,status").ExecuteAsync();
Console.WriteLine("Change video details OK ....");
This is my code in WPF
private async Task Change_VideoDetails()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
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 channelsListRequest = youtubeService.Channels.List("contentDetails");
channelsListRequest.Mine = true;
// Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
var channelsListResponse = await channelsListRequest.ExecuteAsync();
foreach (var channel in channelsListResponse.Items)
{
// From the API response, extract the playlist ID that identifies the list
// of videos uploaded to the authenticated user's channel.
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
//Console.WriteLine("Videos in list {0}", uploadsListId);
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = youtubeService.PlaylistItems.List("Id,snippet,status");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
var newVideo = new Video();
newVideo.Snippet = new VideoSnippet();
newVideo.Id = "6obQQde1X3A";
txtLog.AppendText("\nWill change video details....." + newVideo.Id + );
txtLog.ScrollToEnd();
newVideo.Snippet = new VideoSnippet();
newVideo.Id = "6obQQde1X3A";
newVideo.Snippet.Title = "My Title";
newVideo.Snippet.Description = "My Description";
newVideo.Snippet.Tags = new string[] { "tag 1", "tag 2", "tag 3" };
newVideo.Snippet.CategoryId = "22";
newVideo.Status = new VideoStatus();
newVideo.Status.PrivacyStatus = "public";
newVideo = await youtubeService.Videos.Update(newVideo, "Id,snippet,status").ExecuteAsync();
txtLog.AppendText("\nChanged video details ....." + newVideo.Id);
txtLog.ScrollToEnd();
// Retrieve the list of videos uploaded to the authenticated user's channel.
var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
int line_count=0;
foreach (var playlistItem in playlistItemsListResponse.Items)
{
line_count += 1;
if (line_count == int.Parse(txtVideonumber.Text))
{
break;
}
//}
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
}
}
I used below code for run above code:
private void BtnChange_Click(object sender, RoutedEventArgs e)
{
Change_VideoDetails();
}
I tried run debugger and my code is stopping at bellow code:
newVideo = await youtubeService.Videos.Update(newVideo, "Id,snippet,status").ExecuteAsync();
I don't understand why it is stopping? Please help me solve it

You must await an asynchronous method i.e. await the Task result:
// Since this is an event handler 'async void' is allowed.
// Otherwise you must use 'async Task' or 'async Task<T>'
private async void BtnChange_Click(object sender, RoutedEventArgs e)
{
await Change_VideoDetails();
}
Awaiting the Task is important to allow proper exception handling/behavior. If you don't await a Task then the exception will not propagate properly - the exception will be swallowed. This is because in an async method the exceptions are captured and placed on the Task object. When you await the Task, you allow the execption to propagate to the caller's context to finally hold your application or being handled in a catch block.
Your problem is difficult to solve for somebody that has no acces to your environment (including the Youtube account and authentication configuration).
First make sure that your debugger will break on all exceptions by enabling at least all CLR exceptions: select Debug/ Windows/Exception Setting in the main menu and check the "Common Language Runtime Exceptions" check box.
If still no exception is thrown in the debugger, remove the ExecuteAsync() to execute the operation synchronously. This way you can test if you encounter a deadlock. When it comes to async/await you must know that console apps, Asp.Net and Winforms/Wpf/UWP have a different behavior in certain aspects.

Related

Livebroadcast ID from different channel

i try to get the livechat Messages vie the c# API from a different channel.
To achieve this i Need the liveboradcast id.
I managed to get the live Video and id via search, but it seems this id isnt the livebroadcast id.
This is my Code so far.
As i said it Returns a Video and the ID, but the Broadcast Response with this id is 0.
Example:
"[GER/HD] Boss Riesenaffe/Megapithecus Hard, oder auch nicht ;) ARK: Survival Evolved (t3CwM9MJSNI)"
Anyone know where i can get the livebroadcast id !?
Stream SStream = new FileStream("client_secrets.json", FileMode.Open);
UserCredential Credentials = await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(SStream).Secrets, new[] { YouTubeService.Scope.YoutubeForceSsl }, "user", CancellationToken.None, new FileDataStore(this.GetType().ToString()));
Service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = Credentials,
ApplicationName = "name"
});
var searchListRequest = Service.Search.List("snippet");
searchListRequest.EventType = SearchResource.ListRequest.EventTypeEnum.Live;
searchListRequest.Type = "video";
searchListRequest.ChannelId = "thechannelid";
searchListRequest.MaxResults = 50;
var searchListResponse = await searchListRequest.ExecuteAsync();
List<string> videos = new List<string>();
string ID = null;
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
ID = searchResult.Id.VideoId;
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
}
}
Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
LiveBroadcastsResource.ListRequest Request = Service.LiveBroadcasts.List("id,snippet,contentDetails,status");
Request.BroadcastType = LiveBroadcastsResource.ListRequest.BroadcastTypeEnum.All;
//Request.BroadcastStatus = LiveBroadcastsResource.ListRequest.BroadcastStatusEnum.Active;
Request.MaxResults = 10;
Request.Id = ID;
Console.WriteLine("ID: " + Request.Id);
//Request.Mine = false;
var BroadCastResponse = Request.Execute();
Console.WriteLine(BroadCastResponse.Items.Count);
foreach (LiveBroadcast c in BroadCastResponse.Items)
{
Console.WriteLine("Title: " + c.Snippet.Title);
}
AFAIK, you can only search broadcasts that the channel you are authenticated has created.
Try using search.list:
Returns a collection of search results that match the query parameters specified in the API request.
As stated in this related SO post, search.list returns video from a particular channel, without being authenticated as that channel/user, if you know that channel's channelId.
HTTPS Request:
HTTP GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channelId}&eventType=live&type=video&key={YOUR_API_KEY}

Get all videos from channel - Youtube API v3 c#

Is it possible to get all videos from a channel (not mine)?
If it is possible, can I use a simple API key or should I use OAuth 2.0 credentials?
I have done in this way and it worked for me
I have used Youtube API v3 from Nuget Packet manager
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
public ActionResult GetVideo(YouTubeData objYouTubeData)
{
try
{
var yt = new YouTubeService(new BaseClientService.Initializer() { ApiKey = "Your API Key" });
var channelsListRequest = yt.Channels.List("contentDetails");
channelsListRequest.ForUsername = "kkrofficial";
var channelsListResponse = channelsListRequest.Execute();
foreach (var channel in channelsListResponse.Items)
{
// of videos uploaded to the authenticated user's channel.
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = yt.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
// Retrieve the list of videos uploaded to the authenticated user's channel.
var playlistItemsListResponse = playlistItemsListRequest.Execute();
foreach (var playlistItem in playlistItemsListResponse.Items)
{
// Print information about each video.
//Console.WriteLine("Video Title= {0}, Video ID ={1}", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
var qry = (from s in ObjEdbContext.ObjTubeDatas where s.Title == playlistItem.Snippet.Title select s).FirstOrDefault();
if (qry == null)
{
objYouTubeData.VideoId = "https://www.youtube.com/embed/" + playlistItem.Snippet.ResourceId.VideoId;
objYouTubeData.Title = playlistItem.Snippet.Title;
objYouTubeData.Descriptions = playlistItem.Snippet.Description;
objYouTubeData.ImageUrl = playlistItem.Snippet.Thumbnails.High.Url;
objYouTubeData.IsValid = true;
ObjEdbContext.ObjTubeDatas.Add(objYouTubeData);
ObjEdbContext.SaveChanges();
ModelState.Clear();
}
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
}
}
catch (Exception e)
{
ViewBag.ErrorMessage = "Some exception occured" + e;
return RedirectToAction("GetYouTube");
}
return RedirectToAction("GetYouTube");
}
Provide your channel name in this line
channelsListRequest.ForUsername = "kkrofficial"; //kkrofficial is kkr channel name.
Follow this link
https://developers.google.com/youtube/v3/code_samples/dotnet#retrieve_my_uploads
You can use your API key and just query all channels video ( even if not yours :) )
public Task<List<SearchResult>> GetVideosFromChannelAsync(string ytChannelId)
{
return Task.Run(() =>
{
List<SearchResult> res = new List<SearchResult>();
string nextpagetoken = " ";
while (nextpagetoken != null)
{
var searchListRequest = _youtubeService.Search.List("snippet");
searchListRequest.MaxResults = 50;
searchListRequest.ChannelId = ytChannelId;
searchListRequest.PageToken = nextpagetoken;
searchListRequest.Type = "video";
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = searchListRequest.Execute();
// Process the video responses
res.AddRange(searchListResponse.Items);
nextpagetoken = searchListResponse.NextPageToken;
}
return res;
});
}
This method should get you on track
Here is a quick example on how to output video names for a channel using a console app.
You will need an API key. To get an API key,
Go to https://console.cloud.google.com/
Use your gmail account to log in.
Click on Enable APIs and services (or go to APIs and services if you already enabled it).
In the API Library page, search for youtube.
Select Youtube Data API v3.
Click on Enable to enable API.
Click on Credentials on the left side menu (or click on Manage, then Credentials if it's already enabled).
Click on Create Credentials at the top.
Select API key.
Copy your API key value and paste in the code below.
In Visual Studio, create a new .NET Framework Console App.
Go to Nuget Packet Manager.
Install Google.Apis.Youtube.v3 package.
using System;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace GetYouTubeVideos
{
class Program
{
static void Main(string[] args)
{
GetVideos();
}
public static void GetVideos()
{
try
{
YouTubeService yt = new YouTubeService(new BaseClientService.Initializer() { ApiKey = "put api key here" });
ChannelsResource.ListRequest channelsListRequest = yt.Channels.List("contentDetails");
channelsListRequest.ForUsername = "put channel user name here";
// channelsListRequest.Id = "put channel id here (if you want to use the channel id)";
ChannelListResponse channelsListResponse = channelsListRequest.Execute();
foreach (Channel channel in channelsListResponse.Items)
{
string uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
string nextPageToken = "";
while (nextPageToken != null)
{
PlaylistItemsResource.ListRequest playlistItemsListRequest = yt.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
PlaylistItemListResponse playlistItemsListResponse = playlistItemsListRequest.Execute();
foreach (PlaylistItem playlistItem in playlistItemsListResponse.Items)
{
Console.WriteLine("Video Title= {0}, Video ID ={1}", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}

insert task in task list google-task-api

I am really confused. I am testing google task api, I can access my tasks but when I am tiring to insert a task it gives an error. in documentation this code is available, that dose not work because there is no Fetch function available.
Task task = new Task { Title = "New Task"};
task.Notes = "Please complete me";
task.Due = "2010-10-15T12:00:00.000Z";
Task result = service.Tasks.Insert(task, "#default").Fetch();
Console.WriteLine(result.Title);
I modified my code to,
Google.Apis.Tasks.v1.Data.Task task = new Google.Apis.Tasks.v1.Data.Task { Title = "five" };
task.Notes = "Please complete me";
task.Due = DateTime.Now;
Google.Apis.Tasks.v1.Data.Task result = service.Tasks.Insert(task,taskList.Id.ToString()).Execute();
Console.WriteLine(result.Title);
But I am facing an error and Execute line:
An unhandled exception of type 'Google.GoogleApiException' occurred in Google.Apis.dll
Additional information: Google.Apis.Requests.RequestError
Insufficient Permission [403]
You can copy following code lines from Google Docs:
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/tasks-dotnet-quickstart.json
static string[] Scopes = { TasksService.Scope.Tasks };
static string ApplicationName = "YOUR APPLICATION NAME";
Please make sure that you use the same App name in your program and at
the Google Console.
And most important, as the code comment says, delete the .credentials directory.
The following Code works fine for me:
static void Main(string[] args)
{
UserCredential credential;
// Copy & Paste from Google Docs
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/tasks-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 Tasks API service.
var service = new TasksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
TasklistsResource.ListRequest listRequest = service.Tasklists.List();
// Fetch all task lists
IList<TaskList> taskList = listRequest.Execute().Items;
Task task = new Task { Title = "New Task" };
task.Notes = "Please complete me";
task.Due = DateTime.Parse("2010-10-15T12:00:00.000Z");
task.Title = "Test";
// careful no verification that taskList[0] exists
var response = service.Tasks.Insert(task, taskLists[0].Id).Execute();
Console.WriteLine(response.Title);
Console.ReadKey();
}
And you are right there is no method Fetch(), but as you can see I changed it to Execute() like you did and it works ;)
I had this problem too...
I resolve this by getting de ID of the taskList first and passing into the insert method.
public void IncluirTicket(string messageShort, string observacao)
{
// Define parameters of request.
listRequest = service.Tasklists.List();
listRequest.MaxResults = 10000;
// List task lists.
IList<TaskList> taskList = listRequest.Execute().Items;
var listaPendencias = taskList.Where(x => x.Title == "pendencias").ToList();
var listaPendenciasID = listaPendencias[0].Id;
Google.Apis.Tasks.v1.Data.Task task = new Google.Apis.Tasks.v1.Data.Task { Title = messageShort };
task.Notes = observacao;
task.Due = DateTime.Now;
Google.Apis.Tasks.v1.Data.Task result = service.Tasks.Insert(task, listaPendenciasID).Execute();
Console.WriteLine(result.Title);
}
Works for me.

The redirect URI in the request: http://localhost:12349/authorize/ did not match a registered redirect URI

I'm getting this error while trying to run my c# console application... I am trying to call google calender api v3 to fetch calender and add event to calender. According to the sample code from google-api-dotnet-client I am doing this.( https://code.google.com/p/google-api-dotnet-client/source/browse/Calendar.VB.ConsoleApp/Program.vb?repo=samples ) Here is the vb.net code. I am using this sample after converting it to c# code.
Here is my code:
class Program
{
static void Main(string[] args)
{
try
{
new Program().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("ERROR: " + e.Message);
}
}
}
private async Task Run()
{
UserCredential credential;
IList<string> scopes = new List<string>();
CalendarService service;
scopes.Add(CalendarService.Scope.Calendar);
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
// problem occuring during executing this statement.
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
scopes,
"user", CancellationToken.None, new FileDataStore("Calender.SampleApp") );
}
BaseClientService.Initializer initializer = new BaseClientService.Initializer();
initializer.HttpClientInitializer = credential;
initializer.ApplicationName = "C# Calendar Sample";
service = new CalendarService(initializer);
Event newEvent = new Event();
newEvent.Summary = "Appointment";
newEvent.Description = "Need to meet my Uncle";
IList<EventReminder> reminders = new List<EventReminder>();
reminders.Add(new EventReminder { Method = "sms", Minutes = 10 });
newEvent.Reminders = new Event.RemindersData { UseDefault = false, Overrides = reminders };
newEvent.Recurrence = new String[] { "DTSTART;TZID=Bangladesh Standard Time:20140124T163000;RRULE:FREQ=DAILY" };
IList<EventAttendee> attendees = new List<EventAttendee>();
attendees.Add(new EventAttendee { Email = "hannan.cse.m#gmail.com", Organizer = true, DisplayName = "Hannan" });
newEvent.Attendees = attendees;
newEvent.GuestsCanInviteOthers = false;
newEvent.GuestsCanModify = false;
newEvent.GuestsCanSeeOtherGuests = false;
newEvent.Location = "Dhaka, Bangladesh";
newEvent.Start = new EventDateTime { DateTime = DateTime.Now, TimeZone = "Bangladesh Standard Time" };
Event recurringEvent = service.Events.Insert(newEvent, "primary").Execute();
var list = await service.CalendarList.List().ExecuteAsync();
}
}
This is my redirect URIs in my GoogleDevelopers Console project.
Redirect URIs: http://localhost:7744/authorize/
And this is the error message shown in browser.
I couldn't find any way to resolve this problem. Some help will be appreciable. I also search all the realted post in stackoverflow. But I couldn't find it's solution.
I think you are doing something wrong while "create client id" in GoogleDevelopers Console. Make sure that you have chosed "Installed application" in application type to access your project from console application.
Have a look in the attached image. According to request type you must create clientid
and credintials in your registered application in Google Developers Console.
You don't need to define redirect uri in console application while authenticating.
I was having this error on a simple test program (https://ctrlq.org/google.apps.script/docs/guides/rest/quickstart/dotnet.html), and it happens to be the client_secret.json was th wrong one, download it again and it worked.

New to C#. How to use google-admin-sdk (add users, add user to group a.s.o.)?

Trying to get the hang of how to use google-admin-sdk in C# (got a possible job-opening)
I've managed to create code for creating users and adding a user to a group in Python 2.7 as commandline-tools.
But the employer asked med if I could do the same in C#. I think I would get the hang of it, but would appreciate some help on how to start.
I have installed Visual Studio Express 2012 for Desktop and downloaded:
google-admin-directory_v1-rev6-csharpp-1.4.0-beta.zip
google-api-dotnet-client-1.4.0-beta-samples.zip
google-api-dotnet-client-1.4.0-beta.zip
But I can't find any (for me understandble) samples.
Any one care to give me any good pointers? Would be very much appreciated. :)
/Jonas
Edit : Adding my code so far!
using System;
using System.Diagnostics;
using System.Linq;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Admin.directory_v1;
using Google.Apis.Admin.directory_v1.Data;
namespace Bergstedts.ListUsers
{
public class Program
{
static void Main(string[] args)
{
// Display the header and initialize the sample.
CommandLine.EnableExceptionHandling();
CommandLine.DisplayGoogleSampleHeader("Lists all Users");
// Register the authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = "my ID",
ClientSecret = "my secret"
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new DirectoryService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "List Users",
});
service.Users.List().Domain = "mydomain.com";
Users results = service.Users.List().Execute();
Console.WriteLine("Users:");
foreach (User list in results.UsersValue)
{
Console.WriteLine("- " + list.Name);
}
Console.ReadKey();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { DirectoryService.Scopes.AdminDirectoryUser.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
Edit : Found how to add the domain :
service.Users.List().Domain = "mydomain.com";
But I still get the same error message :
An error has occured:
Google.Apis.Requests.RequestError
Bad Request [400]
Errors [
Message[Bad Request] Location[ - ] Reason[badRequest] Domain[global]
]
This is fixed now!
split the list().Execute() like this! Got help from #peleyal
var listReq = service.Users.List();
listReq.Domain = domain;
Users results = listReq.Execute();
This is another way to get users from a Domain (just a little different)
String serviceAccountEmail = "xxxxxxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"xxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser},
User = "your USER",
}.FromCertificate(certificate));
var service = new DirectoryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "name of your app",
});
var listReq = service.Users.List();
listReq.Domain = "your domain";
Users allUsers = listReq.Execute();
foreach(User myUser in allUsers.UsersValue){
Console.WriteLine("*" + myUser.PrimaryEmail);
}
Console.ReadKey();
For people who want more information, can visit Admin-SDK Users: list and the Directory API: Limits and Quotas

Categories