List Videos From a Channel using YouTube API V3 in C#

Friends,

Google has retired YouTube API V2 and trying to fetch videos using the API V2 returns an error as “410 Gone Away“. In this post, we will see how can we retrieve all videos from a specific YouTube Channel using the latest YouTube API V3.

Let’s get started creating the application.

  • We create a new Stand alone application named “YouTubeVideos” and install the Nuget package named “Google.Apis.YouTube.V3″ to the application. In case you’re unaware of installing Nuget packages to your application, check it out here.

youtube-1

youtube-2

  • Once the project gets created, “Select the project” and go to “APIs & Auth” > “Credentials” from the left sidebar.

youtube-3

  • If you just want to retrieve videos, you can go ahead and click on “Create new Key” under Public API access. However, if you want to use oAuth to validate user credentials before showing them videos, you need to create Client ID. For this example, we will be using “Public API access”.
  • After the key is created, copy the key in a notepad file.
  • Coming back to the application, below is the complete code —
using System;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;

namespace YoutubeVideos
{
    class Program
    {
        static void Main(string[] args)
        {
            YouTubeService yt = new YouTubeService(new BaseClientService.Initializer() { ApiKey = "YOUR_API_KEY" });


            var searchListRequest = yt.Search.List("snippet");
            searchListRequest.ChannelId = "YOUR_CHANNEL_ID";
            var searchListResult = searchListRequest.Execute();
            foreach (var item in searchListResult.Items)
            {
                Console.WriteLine("ID:" + item.Id.VideoId);
                Console.WriteLine("snippet:" + item.Snippet.Title);
            }
        }
    }
}

The above code will list the VideoID and Title of the videos present in your channel.

I hope this article helped you in retrieving YouTube videos from your channel. Let me know in case you have any other way of doing so or need any help.

Presented on Azure Websites in C# Corner Kolkata Chapter

This Sunday on 28th June, 2015 I presented on “Azure Websites” for C# Corner Kolkata Chapter’s event -“A Day With Azure” at Microsoft Office, Kolkata. In spite of heavy rain, the audience made it to the venue to learn about Azure. IN this session, I discussed about the following topics –

  • Hosting your application in Azure – Different Offerings by Microsoft
  • Azure Websites
  • Understanding Authentication
  • Web Hosting Plans
  • Deploy to Websites via Various options
  • Configuring Azure Websites

Here are the slides for the presentation –

azure-certificate

It was an amazing experience interacting with the attendees and I personally had a lot of fun presenting. I hope to speak more in the upcoming events.

azure-group

How To Keep IIS Express After Debugging is Stopped in Visual Studio

Friends,

In Visual Studio 2012 whenever you debug a web application and open the application in Chrome/Firefox, the application used to run even after you have stopped debugging. This means, you can stop debugging, edit some piece of code, rebuild and just refresh the page in browser to test things. However, in Visual Studio 2013 this does not happen. By default when you stop debugging, IIS express is turned off and you need to run the application again to start the web application. In this article, we will see how we will prevent Visual Studio 2013 from doing so.To turn off this feature, you need to perform the following steps –

  • Open Options dialog box via Tools > Options
  • Find Debugging > Edit and Continue
  • Uncheck “Enable Edit and Continue” and click OK.

vs2013-tip

  • You’re done.

Hope you like this article. Keep learning and sharing.

Upload Files to FTP Server in C#

Friends,

In some of my previous articles, I wrote about with How To List Files From FTP Server, How To Delete File From FTP Server, How To Download File From FTP Server. In this article, we will see how can we upload a file to FTP server using C# from our local hard disk.

private void UploadFileToFTP()
{
   FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/sample.txt");
               
   ftpReq.UseBinary = true;
   ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
   ftpReq.Credentials = new NetworkCredential("user", "pass");

   byte[] b = File.ReadAllBytes(@"E:\sample.txt");
   ftpReq.ContentLength = b.Length;
   using (Stream s = ftpReq.GetRequestStream())
   {
        s.Write(b, 0, b.Length);
   }

   FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();

   if (ftpResp != null)
   {
         if(ftpResp.StatusDescription.StartsWith("226"))
         {
              Console.WriteLine("File Uploaded.");
         }
   }
}

The above code reads a text file names “sample.txt” from your hard disk and uploads it to the root folder of the server named “www.server.com”. If you see the code,we created an object of FtpWebRequest class and this time, we passed the RequestMethod as UploadFile. This command tells the CLR to upload the mentioned file from the local system to server. It is important to note that we need to tell the file name after the server name to define the file name that will be used for uploading the file. Another thing to note is we need to set the UseBinary property of the FTPWebRequest object to true to be able to download files and view its contents properly.

Hope this post will help you in uploading files to any FTP server in C#! Keep learning and sharing! Cheers!

Getting Started With HTML Agility Pack

Friends,

In this post we will see how to get started with HTML Agility Pack and code samples to see how web scraping can be achieved using this package in C#. For users who are unaware about “HTML Agility Pack“, This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT. In simple words, it is a .NET code library that allows you to parse “out of the web” files (be it html/php/aspx).

To make it more simpler, you can scrape web pages present on Internet using this library.

How to Get HTML Agility Pack in your application

You can get HTML Agility Pack in your application using Nuget. To install it in your project, you can just use the following in Package Manager Console

Install-Package HtmlAgilityPack 

Read this: How to add Nuget packages in your project

After adding the reference via Nuget, you need to include the reference in your page using –

using HtmlAgilityPack;

Load a Page From Internet

To load a page directly from Web, you can use the following code:

 HtmlWeb web = new HtmlWeb();
 HtmlDocument document = web.Load("http://www.c-sharpcorner.com");

After executing this 2 lines of code, we have the entire page of http://c-sharpcorner.com in document object of HtmlDocument class.

Load a Page from a Saved Document

Several times we need to load a HTML document from a saved file from our hard disk. To load a HTML document from a saved file, we need to write the following code –

HtmlDocument document2 = new HtmlDocument();
document2.Load(@"C:\Temp\sample.txt")

At this point, we have the entire HTML parsed and loaded in document2 object.

At this point, let us see a sample HTML that we’re using in sample.txt file –

<html>
<head>
</head>
<body>
	<div id="div1">
		<a href="div1-a1">Link 1 inside div1</a>
		<a href="div1-a2">Link 2 inside div1</a>
	</div>
	<a href="a3">Link 3 outside all divs</a>	
	<div id="div2">
		<a href="div2-a1">Link 1 inside div2</a>
		<a href="div2-a2">Link 2 inside div2</a>
	</div>
</body>
</html>

Get all Hyperlinks in a page

Once we have the HTML document loaded, let us see how can we get all hyperlinks from the page.

HtmlDocument document2 = new HtmlDocument();
document2.Load(@"C:\Temp\sample.txt")
HtmlNode[] nodes = document2.DocumentNode.SelectNodes("//a").ToArray();
foreach (HtmlNode item in nodes)
{
     Console.WriteLine(item.InnerHtml);
}

This will output the following text –

html-agility-pack-1

Select a specific div in a page

To get a specific div in a page, we will use the following code –

HtmlDocument document2 = new HtmlDocument();
document2.Load(@"C:\Temp\sample.txt")
HtmlNode node = document2.DocumentNode.SelectNodes("//div[@id='div1']").First();

This code will select the div with id ‘div1′ from the page and return in the Node. You can now iterate on the ChildNodes property of HtmlNode class to get further child elements of the DOM element.

Select all Hyperlinks within a specific div

To select all hyperlinks within a specific div, we can use the following 2 ways –

HtmlDocument document2 = new HtmlDocument();
document2.Load(@"C:\Temp\sample.txt")

//Approach 1
HtmlNode node = document2.DocumentNode.SelectNodes("//div[@id='div1']").First();

HtmlNode [] aNodes = node.SelectNodes(".//a").ToArray();

//Approach 2
HtmlNode [] aNodes2 = document2.DocumentNode.SelectNodes("//div[@id='div1']//a").ToArray();

The above code will give the following output –

html-agility-pack-2

Filter hyperlinks for certain conditions

In case you want to filter nodes based on conditions, you can also use LINQ to perform any kind of query on the nodes and return your specific nodes. For example, the below code will return all hyperlinks where the anchor tags contain ‘div2‘ in their link text.

HtmlDocument document2 = new HtmlDocument();
document2.Load(@"C:\Temp\sample.txt");

HtmlNode[] nodes = document2.DocumentNode.SelectNodes("//a").Where(x=&gt;x.InnerHtml.Contains("div2")).ToArray();
foreach (HtmlNode item in nodes)
{
    Console.WriteLine(item.InnerHtml);
}

The above code will give the following output –

html-agility-pack-3

Hope this post gives you a head start with HTML Agility Pack. If you have any questions or would like me to provide some support using this, please connect with me here.

How To Install a Nuget Package In Project

Friends,

If you are a Microsoft developer, you must be aware about Nuget. In case you’re not aware about Nuget, it is the package manager for the Microsoft development platform including .NET. The NuGet Gallery is the central package repository used by all package authors and consumers. In this post, I will show you how can you add any Nuget package to your project.

There are 2 ways to add Nuget package to your project. We will take the example of adding jQuery to our project –

Via Package Manager Console using Commands

Package Manager Console is a Window where you can run Powershell scripts to add/remove/update Nuget packages. To open the Package Manager Console, you need to go to Tools > Nuget Package Manager > Package Manager Console.

nuget-1

To install jQuery, you can go to the Package Manager Console and type –

Install-Package jQuery

As soon as you do, jQuery will be added to your project.

Via Visual Studio IDE using mouse clicks

If you’re someone who would like to perform the installation using mouse and mot using command line, you can do the following –

  1. Right click on Solution Explorer and click Manage Nuget Packagesnuget-2
  2. Search for your Library, jQuery in our case and hit Enter.
  3. Click Install button present on the right side of the project you want to install and you’re done.

nuget-3

Hope this post helps you in installing Nuget packages in your project. Keep learning and sharing.

Solution: The URL for Web project ‘X’ is configured to use IIS as the web server but the URL is currently configured on the IIS Express web server

Friends,

While working on a web project, I started getting this error while loading the project in VS2012 this morning. I did a Bing search on the problem and came across the following solutions. Different solutions work for different users so I am listing down all at a single point.

Below is the list of solutions –

  • Delete the *.csproj.user file from Hard Disk and reload the project
  • Open Visual Studio as administrator and try reloading the project.
  • Edit *.csproj file and set the value of UseIISExpress property to False. Save the project file and try reloading the project.
  • Edit *.csproj file and set the value of SaveServerSettingsInUserFile property to True. Save the project file and try reloading the project.
  • If none of the above methods work, the last method would be to create a new website in IIS, edit the *.csproj file and change the value of IISUrl property to the new website URL you created.

Hope one of the above mentioned solutions helps you resolve this problem with ease. Do let me know which one of the above resolved your problem in comments. Keep learning and sharing.