C# Youtube - I want to delete video from my Youtube channel - c#

I want to delete videos from my YouTube channel which video ids are selected, though MultiSelection property of ListBox is on, code doesn't work, is there any other solution? I get such an error as follows:
Execution of request failed: http://gdata.youtube.com/feeds/api/users/xxxxxx/uploads/System.Windows.Forms.ListBox+SelectedObjectCollection
Here is my code:
public void delete()
{
YouTubeRequestSettings settings = new YouTubeRequestSettings(my app name,
my dev key,
my username,
my password);
YouTubeRequest request = new YouTubeRequest(settings);
Uri videoEntryUrl = new Uri(String.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads/{1}", my channel name, list.checkedItems));
Video video = request.Retrieve<Video>(videoEntryUrl);
request.Delete(video);
}
Code for Populating the CheckedListBox
Feed<Video> videoFeed;
string feedUrl = "https://gdata.youtube.com/feeds/api/users/default/uploads";
videoFeed = request.Get<Video>(new Uri(feedUrl));
foreach (Video entry in videoFeed.Entries)
{
list.Items.Add(entry.VideoId,0);
}

Ok...I think the key here is to get the data out of the object collection - and an easy way to do that is with a foreach loop. I'm not familiar with the YouTube API so I don't know what format it expects the video ID in (for multiple videos), but for purposes of this example I'll use a comma.
string videoIDs = "";
foreach (object vidID in list.CheckedItems)
{
videoIDs = videoIDs + vidID.ToString() + ",";
}
videoIDs = videoIDs.Substring(0, videoIDs.Length - 1);
Basically, the above code loops through the CheckedListBox.CheckedItemCollection and gets the video IDs, which is what you are storing in the CheckedBoxList from the code you provided.
Then you can simply use the videoIDs string in your code:
Uri videoEntryUrl = new Uri(String.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads/{1}", my channel name, videoIDs));
Again, this is a general approach - you will need to modify the code to fit the YouTube API.

Feed<Video> videoFeed;
string feedUrl = "https://gdata.youtube.com/feeds/api/users/default/uploads";
videoFeed = request.Get<Video>(new Uri(feedUrl));
foreach (Video entry in videoFeed.Entries)
{
list.Items.Add(entry.VideoId,0);
}

Related

retrieve the duration of each of my youtube videos using C# .NET and the YouTube Data API v3

Is it possible to get the duration of each of my YouTube videos using C# .NET and the YouTube Data API v3 (NOT JavaScript or any other client side language)?
I've been searching for days and the only thing I've come up with is the example that Google has on their .NET Code Samples page which only shows how to get a playlistItems.list. However, this does not give me a list of videos with their associated durations from the contentDeatils.
Please help me figure this out.
Thank you all.
Have been in similar situation where I needed to update descriptions of all my uploads. See hidden gem here: https://github.com/youtube/api-samples/tree/master/dotnet
In project Google.Apis.YouTube.Samples.UpdateVideos you will find a loop which you can slightly modify and use to get duration for each video.
foreach (var channel in channelsListResponse.Items)
{
var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
Console.WriteLine("Videos in list {0}", uploadsListId);
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = youtubeService.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 = await playlistItemsListRequest.ExecuteAsync();
foreach (var playlistItem in playlistItemsListResponse.Items)
{
var videoRequest = youtubeService.Videos.List("snippet");
videoRequest.Id = playlistItem.Snippet.ResourceId.VideoId;
videoRequest.MaxResults = 1;
var videoItemRequestResponse = await videoRequest.ExecuteAsync();
// Get the videoID of the first video in the list
var video = videoItemRequestResponse.Items[0];
var duration = video.ContentDetails.Duration;
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
}
Okay, This is an explanation of how I eventually resolved this issue.
The objective I wish to accomplish with the YouTube data API is to go and retrieve a list of videos from any YouTube channel based on a username or a channel ID.
Ideally, we should just be able to ask YouTube for all the videos from a specific YouTube channel. However, it doesn't seem to work that way.
Ultimately, we need to send a video list request to the YouTubeService.Videos.List method. This will allow us to retrieve the content details, snippet, and statistics for a list of video objects. This method, however, requires a couple of parameters. One is the VideoListRequest.ID parameter which is a string array of the video IDs in the collection of videos you wish to retrieve. The other is the VideoListRequest.MaxResults parameter. This will be the maximum number of videos you wish to pull back.
To retrieve a list of video IDs we need to make another call to the YouTube API and retrieve a list of playlist items from the YouTubeService.PlaylistItems.List method. This method, however, requires the UploadsListID which must be acquired through yet another call to the YouTube API’s YouTubeService.Channels.List method.
So, it turns out we need to make 3 calls to the YouTube API as shown in the chart below.
Step One is to get a list of channels based on either a username or a channel ID. The UploadsListId will come from the ChannelListResponse: channelsListResponse.Items[0].ContentDetails.RelatedPlaylists.Uploads.
Step Two is to get a list of playlist items using the UploadsListID from the previous step. This allows us to retrieve the video ID for each of the videos in the uploaded videos playlist and place them into a string list.
Finally, Step Three is to get the list of videos based on the video IDs in the previous string list. With this response, we can retrieve the duration in each video and convert YouTube's HMS format to a "usable" Timespan formatted string (h:mm:ss).
This is the code I used to accomplish the above description:
public async Task<List<Video>> GetVideoListAsync(ChannelListMethod Method, string MethodValue, int? MaxVideos)
{
// Define variables needed for this method
List<string> videoIdList = new List<string>();
List<Video> videoList = new List<Video>();
string uploadsListId = null;
// Make sure values passed into the method are not null or empty.
if (MaxVideos == null)
{
throw new ArgumentNullException(nameof(MaxVideos));
}
if (string.IsNullOrEmpty(MethodValue))
{
return videoList;
}
// Create the service.
using (YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer
{
ApiKey = _apiKey,
ApplicationName = _appName
}))
{
// Step ONE is to get a list of channels for a specified YouTube user or ChannelID.
// Create the FIRST Request object to get a list of YouTube Channels and get their contentDetails
// based on either ForUserName or ChannelID.
ChannelsResource.ListRequest channelsListRequest = youtubeService.Channels.List("contentDetails");
if (Method == ChannelListMethod.ForUserName)
{
// Build the ChannelListRequest using UserName
channelsListRequest.ForUsername = MethodValue;
}
else
{
// Build the ChannelListRequest using ChannelID
channelsListRequest.Id = MethodValue;
}
// This is the FIRST Request to the YouTube API.
// Retrieve the contentDetails part of the channel resource to get a list of channel IDs.
// We are only interested in the Uploads playlist of the first channel.
try
{
ChannelListResponse channelsListResponse = await channelsListRequest.ExecuteAsync();
uploadsListId = channelsListResponse.Items[0].ContentDetails.RelatedPlaylists.Uploads;
}
catch (Exception ex)
{
ErrorException = ex;
return videoList;
}
// Step TWO is to get a list of playlist items from the Uploads playlist.
// From the API response, use the Uploads playlist ID (uploadsListId) to be used to get list of videos
// from the videos uploaded to the user's channel.
string nextPageToken = "";
while (nextPageToken != null)
{
// Create the SECOND Request object for requestring a list of Playlist items
// from the channel's Uploads playlist.
// Limit the list to maxVideos items and continue to iterate through the pages.
PlaylistItemsResource.ListRequest playlistItemsListRequest = youtubeService.PlaylistItems.List("contentDetails");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = MaxVideos;
playlistItemsListRequest.PageToken = nextPageToken;
// This is the SECOND Request to YouTube and get a Response object containing
// the playlist items in the channel's Uploads playlist.
// Then iterate through the Response items to build a string list of the video IDs
try
{
PlaylistItemListResponse playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
foreach (PlaylistItem playlistItem in playlistItemsListResponse.Items)
{
videoIdList.Add(playlistItem.ContentDetails.VideoId.ToString());
}
}
catch (Exception ex)
{
ErrorException = ex;
return videoList;
}
// Now that we have a collection (string array) of video IDs,
// Step THREE is to retrieve the snippet, contentDetails, and statistics parts of the
// list of videos uploaded to the authenticated user's channel.
try
{
// Create the THIRD Request object for requestring a list of videos and their associated metadata.
var VideoListRequest = youtubeService.Videos.List("snippet, contentDetails, statistics");
// The next line converts the list of video Ids to a comma seperated string array of the video IDs
VideoListRequest.Id = String.Join(",", videoIdList);
VideoListRequest.MaxResults = MaxVideos;
var VideoListResponse = await VideoListRequest.ExecuteAsync();
// This is the THIRD Request to the YouTube API to get a Response object
// containing Collect each Video duration and convert to a usable time format.
foreach (var video in VideoListResponse.Items)
{
video.ContentDetails.Duration = HMSToTimeSpan(video.ContentDetails.Duration).ToString();
videoList.Add(video);
}
// request next page
nextPageToken = VideoListResponse.NextPageToken;
}
catch (Exception ex)
{
ErrorException = ex;
return videoList;
}
}
return videoList;
}
}
I know this isn't the perfect solution, or perhaps the "best" one, but I hope this helps others with the same issue.
Thanks for all of your help #Janis S

Linking to another page from a google maps marker

I am coding in c# and using the Artem.Google v6 package to create my map on my website. I am trying to create links from the markers that are dropped onto the map, all of the markers need to link to the same page but with a different ID. strID contains the entire address that each marker needs to link to. This is how I create the marker:
Marker m = new Marker() { Address = strAddress, Info = strName, Animation = MarkerAnimation.Drop };
m.Info = ConvertStringToLink(strID);
GoogleMap1.Markers.Add(m);
I made this method to try and change the marker's Info into a link:
private string ConvertStringToLink(string msg)
{
string regex = #"((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:#=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])";
Regex r = new Regex(regex, RegexOptions.IgnoreCase);
return r.Replace(msg, "$1").Replace("href=\"www", "href=\"http://www");
}
So that doesn't change the text in the info popup to a link. Am I on the right track here or do I need to do it another way?
So to get it to work I just formatted the info of the marker to turn it into a link.
strName = String.Format("{0}", strName, strID);
Marker m = new Marker() { Address = strAddress, Info = strName, Animation = MarkerAnimation.Drop };

How download "octet-stream" Data from a web service and convert in image in WP8?

Im new with WP8.
Im asking which class i should use to get data from a webservice.
I need to launch many Asynchronous requests. 1request=1 image and i need a lot of image in my UI.
in a first time i tried with the webclient class but i can't manage the content type "application/octet-stream" with it so at this time im trying to use the HttpClient class but I need your help. I also need to use Authentication with credantials to connect to the webservice.
In a second time i need to convert the data obtained in Bitmapimage.But i think it's an easier part.I would probably use the Stream class for that.*
thanks for your help
Sry for my english BTW :p
Im not sure it would help but i join a sample of the code,i used a dictionnary of HttpClient because i encountered an error while trying to launch several async requests on the same instance of a Webclient... the 2 lists remain empty...
Dictionary<string, HttpClient> HttpClientDic = new Dictionary<string, HttpClient>();
List<byte[]> imageDataBlocksPresta = new List<byte[]>();
List<byte[]> imageDataBlocksCollab = new List<byte[]>();
public async Task< List<byte[]>> DownloadAsyncRecherchePhoto(string uri,string critere = "")
{
string password = Authentification.MainPage.Password;
string user = Authentification.MainPage.User;
string domain = Authentification.MainPage.Domain;
i++;
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password, domain) };
HttpClientDic.Add("Client" + i.ToString(), new HttpClient(handler));
if (critere == "presta")
{
imageDataBlocksPresta.Add(await HttpClientDic["Client" + i.ToString()].GetByteArrayAsync(uri));
return imageDataBlocksPresta;
}
else if (critere == "collab")
{
imageDataBlocksCollab.Add(await HttpClientDic["Client" + i.ToString()].GetByteArrayAsync(uri));
return imageDataBlocksCollab;
}
//gérer l'erreur
else return null;

Displaying a List of Videos From My YouTube Channel

I am trying to display a list of my videos from my YouTube channel in C#, but I can't.
When I run the program, I get such an error:
Object reference not set to an instance of an object.
YouTubeRequestSettings settings = new YouTubeRequestSettings("my app name",
"my devkey",
"my email", "my password");
YouTubeRequest request = new YouTubeRequest(settings);
string feedUrl = "https://gdata.youtube.com/feeds/api/users/default/uploads";
Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
foreach (Video entry in videofeed.Entries)
{
list.Items.Add(entry);
}
Any help will be appreciated.
Looks like it should be
YouTubeRequest settings = new YouTubeRequest(ayarlar);
otherwise you're trying to pass the not-yet instantiated settings variable as a parameter to the YouTubeRequest constructor.
Update from comment
Since you want a global variable, don't create a new instance here and use the existing one like this
//earlier code
string feedUrl = "https://gdata.youtube.com/feeds/api/users/default/uploads";
//the Feed<Video> has been removed because you want to use the global variable
videoFeed = request.Get<Video>(new Uri(feedUrl));
foreach (Video entry in videofeed.Entries)
{
list.Items.Add(entry);
}

How to delete all event entries from a specific calendar from Google calendar API .NET

I am trying editing a tool to allow a user to select from a list of their calendars and then clear all event entries / add new ones based on Microsoft project tasks.
Heres the original tool: http://daball.github.com/Microsoft-Project-to-Google-Calendar/
I am completely unexperienced with Google APIs / the calendar API, and am having some trouble. The program I'm editing keeps track of which CalendarEntry the user has selected from a list of their calendars. What I am currently trying to do is create a EventFeed which gives me the EventEntries of that selected calendar, so I can then delete all of them. The purpose of this is to allow someone to use this tool to also update the calendar from the project file whenever changes are made. Here's my function attempting the delete.
private void clearPreviousCalendarEntries(CalendarEntry calendarEntry)
{
EventQuery query = new EventQuery();
query.Uri = new Uri(calendarEntry.Links[0].AbsoluteUri);
EventFeed feed = (EventFeed)calendarService.Query(query);
AtomFeed batchFeed = new AtomFeed(feed);
foreach (EventEntry entry in feed.Entries)
{
entry.Id = new AtomId(entry.EditUri.ToString());
entry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.delete);
batchFeed.Entries.Add(entry);
}
EventFeed batchResultFeed = (EventFeed)calendarService.Batch(batchFeed, new Uri(feed.Batch));
foreach (EventEntry entry in batchResultFeed.Entries)
{
if (entry.BatchData.Status.Code != 200 && entry.BatchData.Status.Code != 201)
this.listBoxResults.SelectedIndex = this.listBoxResults.Items.Add("Problem deleteing " + entry.Title.Text + " error code: " + entry.BatchData.Status.Code);
else
this.listBoxResults.SelectedIndex = this.listBoxResults.Items.Add("Deleted " + entry.Title.Text);
}
}
My feed doesn't return the results I was hoping for, but to be honest I'm not sure how to request the events correctly.
query.Uri = new Uri(calendarEntry.Links[0].AbsoluteUri); is something I grabbed from the portion of the program which is adding event to a specific calendar
AtomEntry insertedEntry = calendarService.Insert(new Uri(calendarEntry.Links[0].AbsoluteUri), eventEntry);
These posts are definitely related to what I'm looking for but I haven't arrived at a solution
google-calendar-get-events-from-a-specific-calendar
how can i retrieve a event exclusive from a calendar that i created (not default one)?
Try something like this:
CalendarService myService = new CalendarService("your calendar name");
myService.setUserCredentials(username, password);
CalendarEntry calendar;
try
{
calendar = (CalendarEntry)myService.Get(http://www.google.com/calendar/feeds/default/owncalendars/full/45kk8jl9nodfri1qgepsb65fnc%40group.calendar.google.com);
foreach (AtomEntry item in calendar.Feed.Entries)
{
item.Delete();
}
}
catch (GDataRequestException)
{
}
You can find "Calendar ID" (something like this: 45kk8jl9nodfri1qgepsb65fnc%40group.calendar.google.com) from Calendar Details page inside Google Calendar.
this is a related post:
google calendar api asp.net c# delete event
this is a useful doc:
http://code.google.com/intl/it-IT/apis/calendar/data/2.0/developers_guide_dotnet.html
A way I eventually arrived at was gathering the calendarID from the URI of the calendar, and then creating a new EventQuery using that id. Here's the new version of the code above
private void clearPreviousCalendarEntries(CalendarEntry calendarEntry)
{
this.listBoxResults.SelectedIndex = this.listBoxResults.Items.Add("Clearing previous calender entries");
String calendarURI = calendarEntry.Id.Uri.ToString();
//The last part of the calendarURI contains the calendarID we're looking for
String calendarID = calendarURI.Substring(calendarURI.LastIndexOf("/")+1);
EventQuery query = new EventQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/" + calendarID + "/private/full");
EventFeed eventEntries = calendarService.Query(query);
AtomFeed batchFeed = new AtomFeed(eventEntries);
foreach (AtomEntry entry in eventEntries.Entries)
{
entry.Id = new AtomId(entry.EditUri.ToString());
entry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.delete);
batchFeed.Entries.Add(entry);
}
EventFeed batchResultFeed = (EventFeed)calendarService.Batch(batchFeed, new Uri(eventEntries.Batch));
//check the return values of the batch operations to make sure they all worked.
//the insert operation should return a 201 and the rest should return 200
bool success = true;
foreach (EventEntry entry in batchResultFeed.Entries)
{
if (entry.BatchData.Status.Code != 200 && entry.BatchData.Status.Code != 201)
{
success = false;
listBoxResults.SelectedIndex = listBoxResults.Items.Add("The batch operation for " +
entry.Title.Text + " failed.");
}
}
if (success)
{
listBoxResults.SelectedIndex = listBoxResults.Items.Add("Calendar event clearing successful!");
}
}
I'm not particular happy with this, it seems odd to use string manipulation to gather the info and chop together my own query. But it works and I have been struggling to find a way to get this done.

Categories

Resources