Wednesday, May 20, 2009

Maintain Viewstate for Dynamic controls across the postback

       Most of us have faced the case when we have to load the controls dynamically. We can load user control by calling LoadControl method. To load inbuilt server controls we can use Page.Form.Controls.Add() method or we can user any container like panel or place holder and call Controls.Add() method. Upto this it looks very easy and works fine. However at first postback you either find the control is not loaded or the viewstate is not preserved for that control.

        Lets take an example, we have a user control with only one textbox inside it and a web for which have two buttons LoadControl and Submit. When user clicks on LoadControl button we will load the user control and on Submit button we just submit the form so that postback occurs.

   1: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="ucTestControl.ascx.cs"
   2:      Inherits="ucTestControl" %>
   3: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

Fig - (1) User control with only a textbox.



   1: <%@ Page Language="C#" AutoEventWireup="true" 
   2: CodeFile="LoadUserConrtolDynamically.aspx.cs"
   3:     Inherits="LoadUserConrtolDynamically" %>
   4:  
   5: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   6: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   7: <html xmlns="http://www.w3.org/1999/xhtml">
   8: <head runat="server">
   9:     <title>Dynamically Load User Control</title>
  10: </head>
  11: <body>
  12:     <form id="form1" runat="server">
  13:     <div>       
  14:         <table>            
  15:             <tr>
  16:                 <td colspan="2">
  17:                     Click on "Load Control" button to load user control dynamically.
  18:                 </td>
  19:             </tr>
  20:             <tr>
  21:                 <td>
  22:                     <asp:Button ID="btnLoad" runat="server" Text="Load Control" OnClick="btnLoad_Click" />
  23:                 </td>
  24:                 <td>
  25:                     <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
  26:                 </td>
  27:             </tr>
  28:             <tr>
  29:                 <td colspan="2">
  30:                     Enter Name:
  31:                 </td>                
  32:             </tr>
  33:         </table>
  34:     </div>
  35:     </form>
  36: </body>
  37: </html>

Fig - (2) Webform with two buttons. 



   1: protected void btnSubmit_Click(object sender, EventArgs e)
   2: {
   3:     
   4: }
   5:  
   6: protected void btnLoad_Click(object sender, EventArgs e)
   7: {
   8:     AddUserControl();
   9: }
  10:  
  11: private void AddUserControl()
  12: {
  13:     UserControl ucTest = (UserControl)LoadControl("~/ucTestControl.ascx");
  14:     Page.Form.Controls.Add(ucTest);
  15:     IsControlAdded = true;
  16: }

Fig - (3) Code behind for Webform


          As you can see we are calling LoadControl() method to load our user control. Now when you click on submit button and you find that the control disappears.  WHY? The reason is as we have loaded the control the page's control tree does not have its detail so we need to load the control again with each postback. So first rule for lading dynamic control is,


RULE 1 : Load the Dynamic control in each postback


        So in our example we also need to add the control with each postback. However we need to check that whether the control is loaded before postback or not. To check this I have created one property as shown in code below,



   1: public bool IsControlAdded
   2: {
   3:     get
   4:     {
   5:         if (ViewState["IsControlAdded"] == null)
   6:             ViewState["IsControlAdded"] = false;
   7:  
   8:         return (bool)ViewState["IsControlAdded"];
   9:  
  10:     }
  11:     set
  12:     {
  13:         ViewState["IsControlAdded"] = value;
  14:     }
  15: }
  16:  
  17: protected void Page_Load(object sender, EventArgs e)
  18: {
  19:     if(IsControlAdded)
  20:         AddUserControl();
  21: }
  22:  
  23: protected void btnSubmit_Click(object sender, EventArgs e)
  24: {        
  25: }
  26:  
  27: protected void btnLoad_Click(object sender, EventArgs e)
  28: {
  29:     if(!IsControlAdded)
  30:         AddUserControl();
  31: }
  32:  
  33: private void AddUserControl()
  34: {
  35:     UserControl ucTest = (UserControl)LoadControl("~/ucTestControl.ascx");
  36:     Page.Form.Controls.Add(ucTest);
  37:     IsControlAdded = true;
  38: }

Fig - (4) loading dynamic control with each postback.


         You may have notice the code the code for lading user control,



   1: UserControl ucTest = (UserControl)LoadControl("~/ucTestControl.ascx");
   2: Page.Form.Controls.Add(ucTest);

Fig - (5) Code for loading User control Dynamically


        You may also write this two line code in single line as shown below,



   1: Page.Form.Controls.Add(LoadControl("~/ucTestControl.ascx"));

Fig - (6) Code for loading Dynamic Control


        If you use this code to load user control dynamically than sometime you find an interesting issue. The viewstate is not maintained for dynamically loaded control !!!!!! The viewstate requires the controls ID to store the viewstate properly. So always use code shown in Fig - (4) to load user control dynamically.


RULE 2 : Always load the Dynamic control by assigning it to one temporary variable so that it has unique id.


       One more common mistake is we write Page.Controls.Add() to add the control. This will leads to "Control 'ControlName' of type 'ControlType' must be placed inside a form tag with runat=server" error.


       Now we have to find how the viewstate is maintained for dynamically loaded user control. I will suggest you to read this article first. When we add any control dynamically it play "catch-up" with the page life cycle once they are added. Once the control is added to the "Controls" collection, it plays "catch-up" with the page life cycle, and all the events that it missed are fired. This leads to a very important conclusion: you can add dynamic controls at any time during the page life cycle until the "PreRender" event. Even when you add the dynamic control in the "PreRender" event, once the control is added to the "Controls" collection, the "Init", "LoadViewState", "LoadPostbackdata", "Load", and "SaveViewstate" are fired for this control.


     We have seen how to load user controls dynamically now we will see how to load inbuilt server controls.  The process is same however we don't have to use LoadControl method, we can directly use Controls.Add() method as shown below,



   1: TextBox tempText = new TextBox();
   2: tempText.ID = LstTextBoxId.Count.ToString();
   3: // pnlTextBox is asp:Panel
   4: pnlTextBox.Controls.Add(tempText);

Fig - (7) Load server controls at runtime and maintaining viewstate


        Here we have added server controls and user controls dynamically using regular way. You can load user controls / server control dynamically using AJAX also. Below is the code where I have displayed loading controls using AJAX and normal way.



<%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="LoadUserConrtolDynamically.aspx.cs"
    Inherits="LoadUserConrtolDynamically" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dynamically Load User Control</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <table>
            <tr>
                <td colspan="2">
                    Click on "Add Textbox" button to add texbox dynamically.
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnAddTextBox" runat="server" Text="Add Textbox" OnClick="btnAddTextBox_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Panel ID="pnlTextBox" runat="server">
                    </asp:Panel>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblTest" runat="server"></asp:Label>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <br />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    Click on "Add Textbox using Ajax" button to add texbox dynamically with Ajax.
                </td>
            </tr>
            <tr>
                <td>
                    <asp:UpdatePanel ID="upnlLOadControl" runat="server">
                        <ContentTemplate>
                            <asp:Button ID="btnAddTextBoxAjax" runat="server" Text="Add Textbox using Ajax" OnClick="btnAddTextBoxAjax_Click" />
                            <asp:Panel ID="pnlAjaxTextbox" runat="server">
                            </asp:Panel>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <br />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    Click on "Load Control" button to load user control dynamically.
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="btnLoad" runat="server" Text="Load Control" OnClick="btnLoad_Click" />
                </td>
                <td>
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    Enter Name:
                </td>                
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Fig - (8) code for aspx page.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class LoadUserConrtolDynamically : System.Web.UI.Page
{
    public bool IsControlAdded
    {
        get
        {
            if (ViewState["IsControlAdded"] == null)
                ViewState["IsControlAdded"] = false;
 
            return (bool)ViewState["IsControlAdded"];
 
        }
        set
        {
            ViewState["IsControlAdded"] = value;
        }
    }
 
    public List<String> LstTextBoxId
    {
        get
        {
            if (ViewState["LstTextBoxId"] == null)
                ViewState["LstTextBoxId"] = new List<String>();
 
            return (List<String>)ViewState["LstTextBoxId"];
 
        }
        set
        {
            ViewState["LstTextBoxId"] = value;
        }
    }
 
    public List<String> LstAjaxTextBoxId
    {
        get
        {
            if (ViewState["LstAjaxTextBoxId"] == null)
                ViewState["LstAjaxTextBoxId"] = new List<String>();
 
            return (List<String>)ViewState["LstAjaxTextBoxId"];
 
        }
        set
        {
            ViewState["LstAjaxTextBoxId"] = value;
        }
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if(IsControlAdded)
            AddUserControl();
 
        if (LstTextBoxId.Count > 0)
            AddTextBoxes(pnlTextBox, LstTextBoxId);
 
        if (LstAjaxTextBoxId.Count > 0)
            AddTextBoxes(pnlAjaxTextbox, LstAjaxTextBoxId);
    }
 
    protected void btnSubmit_Click(object sender, EventArgs e)
    {        
    }
 
    protected void btnLoad_Click(object sender, EventArgs e)
    {
        if(!IsControlAdded)
            AddUserControl();
    }
 
    private void AddUserControl()
    {
        UserControl ucTest = (UserControl)LoadControl("~/ucTestControl.ascx");
        Page.Form.Controls.Add(ucTest);
        IsControlAdded = true;
    }
 
    private void AddTextBoxes(Panel pnlTemp,List<String> lstTemp)
    {
        TextBox tempText;
        for (int i = 0; i < lstTemp.Count; i++)
        {
            tempText = new TextBox();
            tempText.ID = lstTemp[i];
            pnlTemp.Controls.Add(tempText);
        }
    }
 
    protected void btnAddTextBox_Click(object sender, EventArgs e)
    { 
        TextBox tempText = new TextBox();
        tempText.ID = LstTextBoxId.Count.ToString();
        pnlTextBox.Controls.Add(tempText);
        LstTextBoxId.Add(LstTextBoxId.Count.ToString());
    }
 
    protected void btnAddTextBoxAjax_Click(object sender, EventArgs e)
    {
        TextBox tempText = new TextBox();
        tempText.ID = Guid.NewGuid().ToString();
        pnlAjaxTextbox.Controls.Add(tempText);
        LstAjaxTextBoxId.Add(tempText.ID);
    }
}

Fig - (9) Code for aspx.cs page



<%@ Control Language="C#" AutoEventWireup="true" 
CodeFile="ucTestControl.ascx.cs" Inherits="ucTestControl" %>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

Fig - (10) Code for user control


 


Happy Programming !!!

Thursday, May 14, 2009

Could not load file or assembly Microsoft.SqlServer.Management.Sdk.Sfc

        You may receive "Could not load file or assembly Microsoft.SqlServer.Management.Sdk.Sfc" while connection to database.  I got the error when I tried to connect to SQL Server 2005 from Visual studio 2008 using server explorer. The exact error is,

Could not load file or assembly ‘Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91′ or one of its dependencies. The system cannot find the file specified.

     To solve this error you need to download following three updates from Microsoft.

  • Microsoft SQL Server System CLR Types
  • Microsoft SQL Server 2008 Management Objects
  • Microsoft SQL Server 2008 Native Client

I found the solution form here. Thanks to Ahmed !!!

Thursday, March 12, 2009

Happy Holi

       HOLI , a festival of color!!!!!!.  This holi is the best holi I enjoyed so far. I was with my friends for whole day and we colored one another. These are my college friends Mihir - Binal, Piyush – Apeksha. We missed our two friends who are in US. SHAILESH and DIPAK. See few snaps……

11032009552

 

11032009548

 

11032009557

 

11032009551

 

11032009560

 

11032009562

Its me (Chirag Darji) !!

Happy Holi !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11

Wednesday, January 07, 2009

The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.Data.Database, null]) failed: The value can not be null or an empty string. (Strategy type ConfiguredObjectStrategy, index 2)

         You may find this error while working with Data Application block in enterprise library. When you look into the inner exception you will find the message "The value can not be null or an empty string.".  This message does not give proper information to user.

         When enterprise library does not find default database than it will show this error. You need to add "defaultDatabase" in web.config file to solve this error.

   1: <configuration>
   2:     <configSections>          
   3:     </configSections>  
   4:     <connectionStrings>
   5:         <add connectionString="" providerName="System.Data.SqlClient"  name="ConnectionStr"/>    
   6:     </connectionStrings>
   7:   <dataConfiguration defaultDatabase="ConnectionStr" />

Fig - (1) Add DataConfiguration section to web.config file to avoid error


         When you add <dataConfiguration defaultDatabase="ConnectionStr" /> tag to web.config file you may get "Unrecognized configuration section dataConfiguration" error. Add "dataConfiguration" section in Configuration section to solve "Unrecognized configuration section dataConfiguration" error.



   1: <section name="dataConfiguration" 
   2: type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

Fig - (2) Solution of Unrecognized configuration section dataConfiguration error


 


Happy Programming!!!

Monday, January 05, 2009

An error occurred creating the configuration section, 'Microsoft.Practices.EnterpriseLibrary,The located assembly's manifest definition does not match the assembly reference

     Today I was exploring Enterprise Library 4.1 and encounter this error. I created a sample application and added reference to few DLL from "EntLib41Src\bin" folder to my application. When I hit F5 to run the application I got following error,

"An error occurred creating the configuration section handler for exceptionHandling: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)"

      While searching for the reason I found a link here. According to this link assemblies in "EntLib41Src\bin" folders are not strong name assemblies. So when you run the application you will encounter error as shown above. While "Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin" folder contains strong name assemblies. You have to add reference from "Program Files\Microsoft Enterprise Library 4.1 - October 2008\Bin" folder in your application.

Happy Programming !!!

Wednesday, October 22, 2008

Page Methods is undefined

        You may receive "Page Methods is undefined while calling Server Side function from Client Side Code using PageMethods in AJAX. The possible cause can be,

1. You may have not added EnablePageMethods="true" in ScriptManager tag.

   1: <ajax:ScriptManager 
   2:     EnablePageMethods="true" ID="ScriptManager1" runat="server">
   3: </ajax:ScriptManager>

2. You have a pre-release version of Atlas or the Ajax beta installed. Download latest version from here.


3. Your application’s virtual directory is configured for .NET Framework 1.1


4. Your application does not have the Ajax DLL in its Bin folder. The DLL is "System.Web.Extensions.dll". You may find the DLL at "C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025". You may have this DLL at different location.


5. Your Web.config does not include a WebServices section. To verify this create a new website and select Ajax Enable Website. You can see that all necessary tags are included in web.config file of this website. You cab replace new web.config file with your application. 


Happy Programming !!!

Tuesday, September 16, 2008

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: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   5: <html xmlns="http://www.w3.org/1999/xhtml">
   6: <head runat="server">
   7:     <title>Get Youtube Vedios</title>
   8: </head>
   9: <script src="swfobject.js" type="text/jscript"></script>
  10:     <script type="text/javascript">
  11:  
  12:     var params = { allowScriptAccess: "always" };
  13:     var atts = { id: "myytplayer" };
  14:     
  15:  
  16:   </script>
  17: <body>
  18:     <form id="form1" runat="server">
  19:         <div>
  20:             <table >
  21:                 <tr>
  22:                     <td>
  23:                         Sample application to fetch vedios from Youtube. 
  24:                     </td>                    
  25:                 </tr>
  26:                 <tr>
  27:                     <td>
  28:                         First you need to create developer account in youtube to get developer key. You can get 
  29:                         <a href="http://youtube.com/signup?next=/my_profile_dev" target="_blank">here</a>.
  30:                     </td>                    
  31:                 </tr>
  32:                 <tr>
  33:                     <td>
  34:                         Enter Seach text :
  35:                         <asp:TextBox ID="txtSearch" runat="server" ></asp:TextBox>
  36:                         <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
  37:                     </td>
  38:                 </tr>
  39:                 <tr>
  40:                     <td>
  41:                         <br />
  42:                     </td>
  43:                 </tr>
  44:                 <tr>
  45:                     <td width="80%">
  46:                         <asp:DataList ID="dlYoutube" runat="server" CellPadding="4" ForeColor="#333333" OnItemDataBound="dlYoutube_ItemDataBound">
  47:                             <ItemTemplate>
  48:                                 <table>
  49:                                     <tr>
  50:                                         <td colspan="2">
  51:                                             <asp:Label ID="lblTotle" Font-Bold="true" runat="server" Text='<%# Eval("title")%>'></asp:Label>
  52:                                         </td>
  53:                                     </tr>
  54:                                     <tr>
  55:                                         <td valign="top">
  56:                                             <%--<a id="aURL" style="text-decoration: none" runat="server" href='<%# Eval("url")%>'>
  57:                                                 <asp:Image ID="imgImage" runat="server" ImageUrl='<%# Eval("thumbnail_url")%>' />
  58:                                             </a>--%>
  59:                                             <div runat="server" id="player"></div>
  60:                                             <asp:Literal ID="ltrl" runat="server"></asp:Literal>
  61:                                         </td>
  62:                                         <td valign="top">
  63:                                             <table width="100%">
  64:                                                 <tr>
  65:                                                     <td>
  66:                                                         <asp:Label ID="lblAuthor" runat="server" Text="Author : "></asp:Label>
  67:                                                     </td>
  68:                                                     <td>
  69:                                                         <asp:Label ID="lblAuthorName" runat="server" Text='<%# Eval("author")%>'></asp:Label>
  70:                                                     </td>
  71:                                                 </tr>
  72:                                                 <tr>
  73:                                                     <td valign="top">
  74:                                                         <asp:Label ID="Label1" runat="server" Text="Description : "></asp:Label>
  75:                                                     </td>
  76:                                                     <td>
  77:                                                         <asp:Label ID="Label2" runat="server" Text='<%# Eval("description")%>'></asp:Label>
  78:                                                     </td>
  79:                                                 </tr>
  80:                                                 <tr>
  81:                                                     <td>
  82:                                                         <asp:Label ID="Label3" runat="server" Text="Rating : "></asp:Label>
  83:                                                     </td>
  84:                                                     <td>
  85:                                                         <asp:Label ID="Label4" runat="server" Text='<%# Eval("rating_avg")%>'></asp:Label>
  86:                                                     </td>
  87:                                                 </tr>
  88:                                             </table>
  89:                                         </td>
  90:                                     </tr>
  91:                                 </table>
  92:                             </ItemTemplate>
  93:                             <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
  94:                             <SelectedItemStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
  95:                             <AlternatingItemStyle BackColor="White" ForeColor="#284775" />
  96:                             <ItemStyle BackColor="#F7F6F3" ForeColor="#333333" />
  97:                             <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
  98:                         </asp:DataList>
  99:                     </td>
 100:                 </tr>
 101:             </table>
 102:         </div>
 103:     </form>
 104: </body>
 105: </html>

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 = "<script language='javascript' type='text\\javascript'>swfobject.embedSWF('http://www.youtube.com/v/" + Convert.ToString(DataBinder.Eval(e.Item.DataItem,"id")) + "&enablejsapi=1&playerapiid=ytplayer','" + div.ClientID + "', '425', '356', '8', null, null, params, atts);</script>";
  52:         }
  53:     }
  54: }

Fig - (6) Youtube asp.net aspx.cs page.


 


Happy Programming !!!