Jun 16, 2010

Update Panel With Dynamic Controls

I am dynamically adding DropDownLists to a table cell. When a DropDownList's selection is changed, I want to update a value ("Label1") on the screen. This value is contained within the Updatepanel ("UP1"). (The DropDownLists are created based on values from a database.) When I create each DropDownList, I also add it to the for the UpdatePanel. This allow the UpdatePanel to be redrawn when the values in the DropDownLists change.

In the example, when I change the selectedvalue in the DropDownList, the "Label1" value on the screen is correctly changed each time but only the 1st, 3rd, 5th, etc. change results in an AsyncPostback. The 2nd, 4th, 6th, etc. results in a full postback. It seems to me that on the 2nd, 4th, etc. occurrence, the UpdatePanel has somehow lost it's (during the last AsyncPostback). When a full postback occurs, everything is reset so that's why it works again the next time.

I know I need to re-add the dynamic trigger to the UpdatePanel, but I don't really know where I should add them.

Thanks for any help you might be able to provide.








Current Value:




Public currentValue As Integer = 0

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim tr As New TableRow
Dim tc As New TableCell
Dim DDL As New DropDownList
DDL.Items.Add(New ListItem("Item #1", 1))
DDL.Items.Add(New ListItem("Item #2", 2))
DDL.ID = "DDL"
DDL.AutoPostBack = True
AddHandler DDL.SelectedIndexChanged, AddressOf SelectionChanged
Dim asyncTrigger As New AsyncPostBackTrigger
asyncTrigger.ControlID = "DDL"
asyncTrigger.EventName = "SelectedIndexChanged"
UP1.Triggers.Add(asyncTrigger)
tc.Controls.Add(DDL)
tr.Cells.Add(tc)
Table1.Rows.Add(tr)
End Sub

Protected Sub SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim thisDDL As DropDownList = CType(sender, DropDownList)
If ViewState("CurrentValue") = "" Then
currentValue = 0
Else
currentValue = CInt(ViewState("CurrentValue"))
End If
currentValue += thisDDL.SelectedValue
ViewState("CurrentValue") = CStr(currentValue)
Label1.Text = CStr(currentValue)
End Sub

Programmatically adding triggers to an UpdatePanel - Microsoft AJAX Library and ASP.NET 2.0 AJAX Extensions

If you want to add a control to fire the UpdatePanel, you have to add the trigger. You add this through the ScriptManager control. The method is .RegisterAsyncPostBackControl(ControlName);

I put this call in the Page_PreInit() method.

Jun 8, 2010

Integrate Youtube in ASP.NET

    I will discuss how to integrate youtube video in asp.net. Youtube provides the API to access the its huge database of videos. It also provides search facility and customized player for integration.
       First thing you need is to get developer key for accessing youtube service. You can get it from here. Once you get the developer you can use the API URL to retrieve youtube videos. The URL is,
   1: http://www.youtube.com/api2_rest
Fig – (1) Youtube API URL
       There specific parameters that you need to pass in query string to get desire result from youtube. See the list below,
   1: Parameter    Description
   2: =============================================================================================
   3: method       youtube.videos.list_by_tag (only needed as an explicit parameter for REST calls)
   4: dev_id       Your developer ID .
   5: tag          Search keyword
   6: page         The "page number" of results you want to retrieve (e.g. 1, 2, 3)
   7: per_page     The number of results you want to retrieve per page (default 20, maximum 100)
Fig – (2) Parameters for youtube querystring
       So from fig – (1) and (2) if you need to search video for asp.net and you need 10 records per page and page should display 3rd page the the URL will be,
   1: http://www.youtube.com/api2_rest?method=youtube.videos.list_by_tag&dev_id=YOURDEVELOPERID&tag=asp.net&page=3&per_page=10
   2:  
Fig – (3) Querystring for youtube video
      Use page=-1 and per_page=-1 to display all the videos on same page without paging. You will get reply in XML format from this URL. You can retrieve that XML as XML document and use XQuery to to get the desire result. OR you can generate dataset from that XML using ReadXML method. I have used ReadXML method.
      This will create three tables (1) ut_response , (2) video_list and (3) video. in dataset. ut_response table contains the information whether the supplied DeveloperId is correct? If yes, the status field contains “ok”. video_list contains total number of videos returned. video table contains the information about the videos.
   1: private void GetYoutubeVedio()
   2: {      
   3:         
   4:         StringBuilder stbURL = new StringBuilder("http://www.youtube.com/api2_rest?");
   5:         stbURL.Append("method=youtube.videos.list_by_tag");
   6:         stbURL.Append("&dev_id=" + DEVELOPERKEY);
   7:         stbURL.Append("&tag=" + txtSearch.Text.Trim());
   8:         stbURL.Append("&page=-1&per_page=-1"); // you can add custom paging if desired
   9:         
  10:         DataSet ds = new DataSet();
  11:         ds.ReadXml(stbURL.ToString());
  12:  
  13:         dlYoutube.DataSource = ds.Tables[2];
  14:         dlYoutube.DataBind();
  15:         
  16:         
  17: }
Fig – (4)  Function to retrieve youtube video in ASP.NET
     You can retrieve youtube videos using above function in ASP.NET. Youtube also provides player integration details.
      Lets have a look at the code below. This code displays all youtube videos played in same asp.net page.
   1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetYouTubeVedios.aspx.cs"
   2:     Inherits="Youtube_GetYouTubeVedios" %>
   3:  
   4: "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   5: "http://www.w3.org/1999/xhtml">
   6: "server">
   7:     Get Youtube Vedios
   8: 
   9: 
  10:     
  17: 
  18:     
"form1" runat="server">
  19:         
  20:             
  21:                 
  22:                     
  25:                 
  26:                 
  27:                     
  31:                 
  32:                 
  33:                     
  38:                 
  39:                 
  40:                     
  43:                 
  44:                 
  45:                     
 100:                 
 101:             
  23:                         Sample application to fetch vedios from Youtube. 
  24:                     
  28:                         First you need to create developer account in youtube to get developer key. You can get 
  29:                         "http://youtube.com/signup?next=/my_profile_dev" target="_blank">here.
  30:                     
  34:                         Enter Seach text :
  35:                         "txtSearch" runat="server" >
  36:                         "btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
  37:                     
  41:                         
  42:                     
"80%">
  46:                         "dlYoutube" runat="server" CellPadding="4" ForeColor="#333333" OnItemDataBound="dlYoutube_ItemDataBound">
  47:                             
  48:                                 
  49:                                     
  50:                                         
  53:                                     
  54:                                     
  55:                                         
  62:                                         
  90:                                     
  91:                                 
"2">
  51:                                             "lblTotle" Font-Bold="true" runat="server" Text='<%# Eval("title")%>'>
  52:                                         
"top">
  56:                                             <%--"aURL" style="text-decoration: none" runat="server" href='<%# Eval("url")%>'>
  57:                                                 "imgImage" runat="server" ImageUrl='<%# Eval("thumbnail_url")%>' />
  58:                                             --%>
  59:                                             
"server" id="player">
  60:                                             "ltrl" runat="server">
  61:                                         
"top">
  63:                                             
"100%"> 
  64:                                                 
  65:                                                     
  68:                                                     
  71:                                                 
  72:                                                 
  73:                                                     
  76:                                                     
  79:                                                 
  80:                                                 
  81:                                                     
  84:                                                     
  87:                                                 
  88:                                             
  66:                                                         "lblAuthor" runat="server" Text="Author : ">
  67:                                                     
  69:                                                         "lblAuthorName" runat="server" Text='<%# Eval("author")%>'>
  70:                                                     
"top">
  74:                                                         "Label1" runat="server" Text="Description : ">
  75:                                                     
  77:                                                         "Label2" runat="server" Text='<%# Eval("description")%>'>
  78:                                                     
  82:                                                         "Label3" runat="server" Text="Rating : ">
  83:                                                     
  85:                                                         "Label4" runat="server" Text='<%# Eval("rating_avg")%>'>
  86:                                                     
  89:                                         
  92:                             
  93:                             "#5D7B9D" Font-Bold="True" ForeColor="White" />
  94:                             "#E2DED6" Font-Bold="True" ForeColor="#333333" />
  95:                             "White" ForeColor="#284775" />
  96:                             "#F7F6F3" ForeColor="#333333" />
  97:                             "#5D7B9D" Font-Bold="True" ForeColor="White" />
  98:                         
  99:                     
 102:         
 103:     
 104: 
 105: 
Fig – (5) Youtube asp.net aspx page.
   1: using System;
   2: using System.Data;
   3: using System.Configuration;
   4: using System.Collections;
   5: using System.Web;
   6: using System.Web.Security;
   7: using System.Web.UI;
   8: using System.Web.UI.WebControls;
   9: using System.Web.UI.WebControls.WebParts;
  10: using System.Web.UI.HtmlControls;
  11: using System.Text;
  12:  
  13:  
  14: public partial class Youtube_GetYouTubeVedios : System.Web.UI.Page
  15: {
  16:     const string DEVELOPERKEY = "YOUR DEVELOPER KEY";
  17:  
  18:     protected void Page_Load(object sender, EventArgs e)
  19:     {
  20:         
  21:     }
  22:  
  23:     private void GetVedio()
  24:     {      
  25:         
  26:         StringBuilder stbURL = new StringBuilder("http://www.youtube.com/api2_rest?");
  27:         stbURL.Append("method=youtube.videos.list_by_tag");
  28:         stbURL.Append("&dev_id=" + DEVELOPERKEY);
  29:         stbURL.Append("&tag=" + txtSearch.Text.Trim());
  30:         stbURL.Append("&page=-1&per_page=-1"); // you can add custom paging if desired
  31:         
  32:         DataSet ds = new DataSet();
  33:         ds.ReadXml(stbURL.ToString());
  34:  
  35:         dlYoutube.DataSource = ds.Tables[2];
  36:         dlYoutube.DataBind();
  37:         
  38:         
  39:     }
  40:  
  41:     protected void btnSearch_Click(object sender, EventArgs e)
  42:     {
  43:         GetVedio();
  44:     }
  45:     protected void dlYoutube_ItemDataBound(object sender, DataListItemEventArgs e)
  46:     {
  47:         if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  48:         {
  49:             HtmlControl div = (HtmlControl)e.Item.FindControl("player");
  50:             Literal objL = (Literal)e.Item.FindControl("ltrl");
  51:             objL.Text = "";
  52:         }
  53:     }
  54: }
Fig – (6) Youtube asp.net aspx.cs page.

Happy Programming !!!