Posts Tagged ‘ASP.Net’

.Net ASP.Net – AJAX with Continuous Progress Bar

7 Comments

I was recently asked about getting a Progress Bar to work in ASP.Net.  It didn’t need to be a progress bar that had a percentage, just something that would alert a user that something is happening behind the scenes.

So I did some Google searching, and found tons of resources where people had created their own Progress Bar controls.  While that was all fine and good, I wasn’t looking to download somebody else’s custom control, and I wasn’t going to make my own.  So I wanted to figure out how I could use existing ASP.Net and AJAX controls to accomplish this task.

It turned out to be easier than I thought it would be.

I knew that I needed the progress bar to show modally, so that the user would not be able to interact with the form during the postback.  So I decided to use the ModalPopupExtender AJAX control.

So first, I have my Button, the ModalPopupExtender, the Panel that the extender will display, the Script Manager, and a hidden control.

<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <div>
            <asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" OnClientClick="StartProgressBar()"
                     runat="server" Text="Submit Time" Width="170px" />

            <ajaxToolkit:ModalPopupExtender ID="ProgressBarModalPopupExtender" runat="server"
                     BackgroundCssClass="ModalBackground" BehaviorID="ProgressBarModalPopupExtender"
                     TargetControlID="hiddenField" PopupControlID="Panel1" />

            <asp:Panel ID="Panel1" runat="server" Style="display: none; background-color: #C0C0C0;">
                 <img src="progressbar.gif" alt="" />
            </asp:Panel>

            <asp:HiddenField ID="hiddenField" runat="server" />
       </div>
   </ContentTemplate>
</asp:UpdatePanel>

If you notice, the TargetControlID attribute of the extender is NOT the button.  The reason for this is that the default functionality of the ModalPopupExtender is to require a button click from the Panel to close it.  Since I want the Panel to stay visible while the server does it’s processing, I set the TargetControlID to the hidden control.

Another thing to notice is the BackgroundCssClass attribute of the ModalPopupExtender.  This is REQUIRED for the extender to actual be modal.  Without it, the extender is a non-modal popup.(more on this later)

Also notice that the Button has both of the click events populated.  The OnClick event will be the server-side event handler.

protected void btnSubmit_Click(object sender, EventArgs e)
{
     Thread.Sleep(7000);
     ProgressBarModalPopupExtender.Hide();
}

This event simply pauses server processing for 7 seconds to simulate a long running process.

The OnClientClick event will be calling a javascript function…

<script language="javascript" type="text/javascript">
    function StartProgressBar() {
        var myExtender = $find('ProgressBarModalPopupExtender');
        myExtender.show();
        return true;
    }
</script>

And last, the CSS entry for the background of the ModalPopupExtender.

If you do not already have a CSS class added to your project, you will need to add one, and link it to the page in the HEAD tag.

<link href="main.css" rel="stylesheet" type="text/css" />

Then add this entry to the CSS file.

.ModalBackground
{
    background-color:Gray;

    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
}

If using Visual Studio 2008, you will get warnings saying that “filter” and “opacity” are not known CSS properties.  This is an issue with Visual Studio.  They are valid properties and they do work.  The 4 properties that are listed in the CSS entry should handle the opacity for all major browsers.  I have tested with IE7, Firefox 3.5, and Chrome.

And that is all you have to do.  The ModalPopupExtender will show when the button is clicked, and the server will start processing the code.  When the server has completed and sends the response back to the browser, it will hide the ModalPopupExtender.

Tags: , , , ,

.Net ASP.Net – Pushing File to Browser

1 Comment

Here is a short snippet that will push/serve a file from the server to the browser for download.

****** NOTE *******
This will not work inside of an AJAX UpdatePanel.  If the code is called from a button click event, that button will need to be outside of any AJAX UpdatePanel.

protected void DownloadFile(string fullFilePath)
{
      // Gets the File Name
      string fileName = fullFilePath.Substring(fullFilePath.LastIndexOf('\\') + 1);
      byte[] buffer;

      using (FileStream fileStream = new FileStream(fullFilePath, FileMode.Open))
      {
           int fileSize = (int)fileStream.Length;

           buffer = new byte[fileSize];

           // Read file into buffer
           fileStream.Read(buffer, 0, (int)fileSize);
      }

      Response.Clear();

      Response.Buffer = true;
      Response.BufferOutput = true;
      Response.ContentType = "application/x-download";
      Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
      Response.CacheControl = "public";
      // writes buffer to OutputStream
      Response.OutputStream.Write(buffer, 0, buffer.Length);
      Response.End();
}
Tags: ,

.Net ASP.Net – Uploading File To Server

2 Comments

Here is a small snippet of code that will allow visitors to your website to upload files to your server.

This code will open an OpenFileDialog box to allow the user to select a file.

<asp:TableCell>
     Select File:
     <input id="uplTheFile" type="file" runat="server" style="width: 476px; height: 26px" />
</asp:TableCell>

This code will add a button to the form to upload the file.

<asp:TableCell>
     <asp:Button ID="cmdUploadFile" value="Upload" runat="server" Text="Upload" OnClick="cmdUploadFile_Click" />
</asp:TableCell>

cmdUploadFile_Click Event

protected void cmdUploadFile_Click(object sender, EventArgs e)
{
     string strFileNameOnServer = uplTheFile.PostedFile.FileName;
     string appDataPath = HttpContext.Current.Server.MapPath("~/App_Data");

     if (string.IsNullOrEmpty(strFileNameOnServer))
     {
           lblInformation.Text = "Error - a file name must be specified.";
           return;
     }

     if (uplTheFile.PostedFile != null)
     {
          try
          {
               uplTheFile.PostedFile.SaveAs(appDataPath + "\\" + strFileNameOnServer);
          }
          catch (Exception ex)
          {
               lblInformation.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>.  " + ex.Message;
          }
      }
}

This will upload the file into the App_Data folder of the website.

Tags: ,