locked
Asynchronous operations are not allowed in this context RRS feed

  • Question

  • User-1392235324 posted

    I have the following code

    ASPX page :

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="youtube.aspx.cs" Inherits="karimdemo2._ka2" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <h1 style="margin-left: 0px">Download Youtube Videos</h1>
       <table>
        <tr>
         <td>
          YouTube URL:
        </td>
         <td>
          <asp:TextBox ID="txtYouTubeURL" runat="server" Text="" Width="450" />
         </td>
        </tr>
        <tr>
         <td>
         </td>
         <td>
          <asp:Button ID="btnProcess" Text="Process" runat="server" OnClick="btnProcess_Click"
            Width="100" />
         </td>
        </tr>
        <tr>
         <td>
           <asp:DropDownList ID="ddlVideoFormats" runat="server" Visible="false">          </asp:DropDownList>
         </td>
         <td>
           <asp:Button ID="btnDownload" Text="Download" runat="server" OnClick="btnDownload_Click" Width="100" Visible="false" />
         </td>
        </tr>
      </table>
      <br />
      <asp:Label ID="lblMessage" Text="" runat="server" />
        </div>
        </form>
    </body>
    </html>
    

    And CS code :

    using System;
    using System.Web;
    using System.Net;
    using System.IO;
    using System.Collections.Specialized;
    using System.Web.UI.WebControls;
    using System.Drawing;
    
    namespace karimdemo2
    {
      public partial class _ka2 : System.Web.UI.Page
      {
        protected void Page_Load(object sender, EventArgs e)
        {
        }    
    
        protected void btnProcess_Click(object sender, EventArgs e)
        {
              try
              {
                  Uri videoUri = new Uri(txtYouTubeURL.Text);
                  string videoID = HttpUtility.ParseQueryString(videoUri.Query).Get("v");
                  string videoInfoUrl = "http://www.youtube.com/get_video_info?video_id=" + videoID;
    
                  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(videoInfoUrl);
                  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
                  Stream responseStream = response.GetResponseStream();
                  StreamReader reader = new StreamReader(responseStream, System.Text.UTF8Encoding.GetEncoding("utf-8"));
    
                  string videoInfo = HttpUtility.HtmlDecode(reader.ReadToEnd());
    
                  NameValueCollection videoParams = HttpUtility.ParseQueryString(videoInfo);
    
                  if (videoParams["reason"] != null)
                  {
                      lblMessage.Text = videoParams["reason"];
                      return;
                  }
    
                  string[] videoURLs = videoParams["url_encoded_fmt_stream_map"].Split(',');
    
                  foreach (string vURL in videoURLs)
                  {
                      string sURL = HttpUtility.HtmlDecode(vURL);
    
                      NameValueCollection urlParams = HttpUtility.ParseQueryString(sURL);
                      string videoFormat = HttpUtility.HtmlDecode(urlParams["type"]);
    
                      sURL = HttpUtility.HtmlDecode(urlParams["url"]);
                      sURL += "&signature=" + HttpUtility.HtmlDecode(urlParams["sig"]);
                      sURL += "&type=" + videoFormat;
                      sURL += "&title=" + HttpUtility.HtmlDecode(videoParams["title"]);
    
                      videoFormat = urlParams["quality"] + " - " + videoFormat.Split(';')[0].Split('/')[1];
    
                      ddlVideoFormats.Items.Add(new ListItem(videoFormat, sURL));
                  }
    
                  btnProcess.Enabled = false;
                  ddlVideoFormats.Visible = true;
                  btnDownload.Visible = true;
                  lblMessage.Text = string.Empty;
              }
              catch (Exception ex)
              {
                  lblMessage.Text = ex.Message;
                  lblMessage.ForeColor = Color.Red;
                  return;
              }
        }
    
        private void Completed(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
          lblMessage.Text = "Video downloaded on: " + DateTime.Now.ToString();
          lblMessage.ForeColor = Color.Green;
        }
    
        protected void btnDownload_Click(object sender, EventArgs e)
        {
          try
          {
            string sURL = ddlVideoFormats.SelectedValue;
     
            if (string.IsNullOrEmpty(sURL))
            {
              lblMessage.Text = "Unable to locate the Video.";
              return;
            }
     
            NameValueCollection urlParams = HttpUtility.ParseQueryString(sURL);
     
            string videoTitle = urlParams["title"] + " " + ddlVideoFormats.SelectedItem.Text;
            string videoFormt = HttpUtility.HtmlDecode(urlParams["type"]);
            videoFormt = videoFormt.Split(';')[0].Split('/')[1];
     
            string downloadPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string sFilePath = string.Format(Path.Combine(downloadPath, "d:\\DZHosts\\LocalUser\\xxxx\\www.xxxxxxxxxx.somee.com\\downloads\\{0}.{1}"),    videoTitle, videoFormt);
     
            WebClient webClient = new WebClient();
            webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Completed);
            webClient.DownloadFileAsync(new Uri(sURL), sFilePath);
          }
          catch (Exception ex)
          {
            lblMessage.Text = ex.Message;
            lblMessage.ForeColor = Color.Red;
            return;
          }
        }
      }
    }

    And I get the following error:

    Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete even

    How to solve this problem ?

    Sunday, December 13, 2015 11:00 AM

Answers

  • User-1392235324 posted

    Solved!

    Async="true"

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, December 13, 2015 11:02 AM