Tuesday 17 May 2016

Video Download from youtube using url




Step1: Add an aspx page to you current project. In case of mine it is, YouTube.aspx

Step2: In the webform, add the async property to Page attribute. This will informs to ASP.NET engine, the page have async methods.

<%@ Page Language="C#" Async="true" AutoEventWireup="true"

Step3: Add a TextBox and Button controls to webform. TextBox is for accepting YouTube Video URL and Button event contains the core logic for downloading video to target path. (In my case, I am downloading videos to system downloads folder).

<span>Enter YouTube URL:</span>
<b r />
<asp:TextBox ID="txtYouTubeURL" runat="server" Text="" Width="450" />
<b r />
<asp:Button ID="btnDownload" Text="Download" runat="server" OnClick="btnDownload_Click" />
<b r />
<b r />
<asp:Label ID="lblMessage" Text="" runat="server" />

Step4: YouTube URL's are not an actual video download URLs. We need to track all the URLs from the Page Source. Among all the URLs, get one of the URL having query string with type as 'video/mp4'. At the same time get Video title from Page Source itself. Once we are ready with Video URL and Title, make a request to server to download the video file from YouTube.







protected void btnDownload_Click(object sender, EventArgs e)
{
    DownloadYouTubeVideo();
}


private void DownloadYouTubeVideo()
{
    try
    {
        string sURL = txtYouTubeURL.Text.Trim();
        bool isDownloaded = false;
 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 
        Stream responseStream = response.GetResponseStream();
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
        StreamReader reader = new StreamReader(responseStream, encode);
 
        string pageSource = reader.ReadToEnd();
        pageSource = HttpUtility.HtmlDecode(pageSource);               
 
        List<Uri> urls = GetVideoDownloadUrls(pageSource);
 
        string videoTitle = HttpUtility.HtmlDecode(GetVideoTitle(pageSource));               
 
        foreach (Uri url in urls)
        {
            NameValueCollection queryValues = HttpUtility.ParseQueryString(url.OriginalString);
 
            if (queryValues["type"].ToString().StartsWith("video/mp4"))
            {
                string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                string sFilePath = string.Format(Path.Combine(downloadPath, "Downloads\\{0}.mp4"), videoTitle);
 
                WebClient client = new WebClient();
                client.DownloadFileCompleted += client_DownloadFileCompleted;                       
                client.DownloadFileAsync(url, sFilePath);
                isDownloaded = true;
 
                break;
            }
        }
 
        if (urls.Count == 0 || !isDownloaded)
        {
            lblMessage.Text = "Unable to locate the Video.";
            return;
        }
    }
    catch (Exception e)
    {
        lblMessage.Text = "An error occurred while downloading video: " + e.Message;
    }
}
private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    lblMessage.Text = "Your video has been downloaded.";
}
private List<Uri> GetVideoDownloadUrls(string pageSource)
{
    string pattern = "url=";
    string queryStringEnd = "&quality";
 
    List<Uri> finalURLs = new List<Uri>();
    List<string> urlList = Regex.Split(pageSource, pattern).ToList<string>();
 
    foreach (string url in urlList)
    {               
        string sURL = HttpUtility.UrlDecode(url).Replace("\\u0026", "&");
 
        int index = sURL.IndexOf(queryStringEnd, StringComparison.Ordinal);
        if (index > 0)
        {
            sURL = sURL.Substring(0, index).Replace("&sig=", "&signature=");
            finalURLs.Add(new Uri(Uri.UnescapeDataString(sURL)));
        }
    }
 
    return finalURLs;           
}

private string GetVideoTitle(string pageSource)
{
    int startIndex = pageSource.IndexOf("<title>");
    int endIndex = pageSource.IndexOf("</title>");
 
    if (startIndex > -1 && endIndex > -1)
    {
        string title = pageSource.Substring(startIndex + 7, endIndex - (startIndex + 7));
        return title;
    }
 
    return "Unknown";
}


Step5: Have a look at your target folder, you will see the Downloaded Video file.

Note: You might need to increase AsyncTimeOut on page directive in order to download larger videos. At the time of downloading video, even if you get TimeOut error, still the download will continue to target folder.

That's It! Thoutgh it is prety simple, it also involves the complexity of finding actual downloadable video URL. 


Saturday 14 May 2016

Format DateTime column (field) in ASP.Net GridView with AutoGenerateColumns True

Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
Download and install Northwind Database
HTML Markup
The following HTML Markup consists of an ASP.Net GridView with AutoGenerateColumns property with set to True and specified with OnRowDataBound event.
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="OnRowDataBound">
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Binding the Repeater control using records form database
Inside the Page load event handler, the Repeater is populated with the records from the Customers table of the Northwind database.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        string query = "SELECT EmployeeId, (FirstName + '' + LastName) Name, BirthDate FROM Employees";
        using (SqlCommand cmd = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub
Private Sub BindGrid()
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As New SqlConnection(constr)
        Dim query As String = "SELECT EmployeeId, (FirstName + '' + LastName) Name, BirthDate FROM Employees"
        Using cmd As New SqlCommand(query)
            Using sda As New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As New DataTable()
                    sda.Fill(dt)
                    GridView1.DataSource = dt
                    GridView1.DataBind()
                End Using
            End Using
        End Using
    End Using
End Sub
Formatting DateTime column (field) in ASP.Net GridView with AutoGenerateColumns True
Inside the OnRowDataBound event handler, the value of the DateTime field is formatted to the desired DateTime format.
C#
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[2].Text = Convert.ToDateTime(e.Row.Cells[2].Text).ToString("dd, MMM yyyy");
    }
}
VB.Net
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        e.Row.Cells(2).Text = Convert.ToDateTime(e.Row.Cells(2).Text).ToString("dd, MMM yyyy")
    End If
End Sub


Implement jQuery AutoComplete TextBox from database using AJAX PageMethods in ASP.Net

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
    rel="Stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $("[id$=txtSearch]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Default.aspx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("[id$=hfCustomerId]").val(i.item.val);
            },
            minLength: 1
        });
    });  
</script>
Enter search term:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient
 
 
 The ASP.Net PageMethod
The following AJAX PageMethod accepts a parameter prefix and its value is used to find matching records from the Customers Table of the Northwind database.
The select query gets the Name and the ID of the customer that matches the prefix text.
The fetched records are processed and a Key Value Pair is created by appending the Id to the Name field in the following format {0}-{1} where is the Name {0} and {1} is the ID of the Customer.
 C#
[WebMethod]
public static string[] GetCustomers(string prefix)
{
    List<string> customers = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select ContactName, CustomerId from Customers where ContactName like @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
                }
            }
            conn.Close();
        }
    }
    return customers.ToArray();
}
 
VB.Net
<WebMethod()>
Public Shared Function GetCustomers(prefix As StringAs String()
    Dim customers As New List(Of String)()
    Using conn As New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As New SqlCommand()
            cmd.CommandText = "select ContactName, CustomerId from Customers where ContactName like @SearchText + '%'"
            cmd.Parameters.AddWithValue("@SearchText", prefix)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    customers.Add(String.Format("{0}-{1}", sdr("ContactName"), sdr("CustomerId")))
                End While
            End Using
            conn.Close()
        End Using
    End Using
    Return customers.ToArray()
End Function
 
 
Fetching the selected item on Server Side
The Key (Customer Name) and Value (Customer ID) can be fetched on server side inside the click event handler of the Button from the Request.Form collection as shown below.
 C#
protected void Submit(object sender, EventArgs e)
{
    string customerName = Request.Form[txtSearch.UniqueID];
    string customerId = Request.Form[hfCustomerId.UniqueID];
    ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('Name: " + customerName + "\\nID: " + customerId +"');"true);
}
 
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
    Dim customerName As String = Request.Form(txtSearch.UniqueID)
    Dim customerId As String = Request.Form(hfCustomerId.UniqueID)
    ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert('Name: " & customerName & "\nID: " & customerId &"');"True)
End Sub