How to update a status label while processing something on the server? - asp.net

I have a requirement to process (server side) a lot of data (files) when the user clicks a button. I'd like to show a running summary of each file name as it's being processed. I've been trying to do it with the UpdatePanel control but only the very last update happens. Here's some simple code I created to simulate the issue (it should count up from 1 to 10 but instead waits the 5 seconds and outputs 10):
<%# Page Language="C#" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager1.RegisterAsyncPostBackControl(Button1);
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 1; i <= 10; i++)
{
Label1.Text = i.ToString();
System.Threading.Thread.Sleep(500);
UpdatePanel1.Update();
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Is there a way to make this work? Or maybe a better way to do it?
Thanks in advance,
Jason

You'll need to use an ajax call to the server. I have copied this code from one of my previous projects it's a bit long code. try it and let me know if it works.
page1.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script type="text/javascript">
function BeginProcess() {
// Create an iframe.
var iframe = document.createElement("iframe");
// Point the iframe to the location of
// the long running process.
iframe.src = "Process.aspx";
// Make the iframe invisible.
iframe.style.display = "none";
// Add the iframe to the DOM. The process
// will begin execution at this point.
document.body.appendChild(iframe);
// Disable the button and blur it.
document.getElementById('trigger').blur();
}
function UpdateProgress(PercentComplete, Message) {
document.getElementById('ContentPlaceHolder2_lbDownload').setAttribute("disabled", "true");
document.getElementById('trigger').value = PercentComplete + '%: ' + Message;
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<input type="submit" value="Start BackUp Process!"
id="trigger" onclick="BeginProcess(); return false;"
style="width: 250px;" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1"
AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
</ProgressTemplate>
</asp:UpdateProgress>
</asp:Content>
Process.aspx.cs
public partial class Process : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder SB = new StringBuilder();
// Padding to circumvent IE's buffer.
Response.Write(new string('*', 256));
Response.Flush();
// Initialization
UpdateProgress(0, "Initializing task.");
try
{
foreach (yourloophere)
{
UpdateProgress(increment, db.Name + " Backup Started....");
//your process code
UpdateProgress(increment, db.Name + " Backup Completed!");
//your process code
SB.Append(db.Name + "BackUp Complted!");
//your process code
SB.Append("<br/>");
}
// All finished!
UpdateProgress(100, "All Database BackUp Completed!");
}
catch (Exception ex)
{
UpdateProgress(0, "Exception: " + ex.Message);
SB.Append("Back Up Failed!");
SB.Append("<br/>");
SB.Append("Failed DataBase: " + DBName);
SB.Append("<br/>");
SB.Append("Exception: " + ex.Message);
}
}
protected void UpdateProgress(double PercentComplete, string Message)
{
// Write out the parent script callback.
Response.Write(String.Format("<script type=\"text/javascript\">parent.UpdateProgress({0}, '{1}');</script>", PercentComplete, Message));
// To be sure the response isn't buffered on the server.
Response.Flush();
}
}

Related

Button not fired up inside asp user control used for umbraco macro

I'm searching solutions for my problem already since 2-3h and I decided better to ask.
I have created and empty web site and the installed umbraco, set up a new macro and it seemd ok but a button is not fired .
The code in Test.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Tests.ascx.cs" Inherits="Demo.Tests" %>
<h1>test</h1>
<form id="Form1" runat="Server">
<asp:Button ID="btnRunTest" OnClick="onClick_btnRunTest" Text="Run test" runat="server" CausesValidation = "false"/>
</form>
<div style="background-color: #de6363; padding: 10px;">
<asp:Label ID="lblMessage" runat="server" Text="" ForeColor="black" />
</div>
And code behind:
public partial class Tests : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
//btnRunTest.Click += new EventHandler(this.onClick_btnRunTest);
}
public void onClick_btnRunTest(object sender, EventArgs e)
{
lblMessage.Text = "";
Stopwatch stopwatch = Stopwatch.StartNew();
DynSLinkedList<int?> list = new DynSLinkedList<int?>();
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Add(1);
list.Add(18);
list.Add(-1);
list.Add(-2);
list.Remove(18);
list.Remove(-2);
list.Remove(1);
var time = stopwatch.Elapsed.ToString();
lblMessage.Text = "Task finished in time "+time +"</br>";
}
}
When I hit the button page reloads but the onClick_btnRunTest is not hit

ViewState on programmatically loaded usercontrols (restored after Page_Load)

I'm trying to create a simple web page with a navigation bar and some usercontrols (ascx) programmatically loaded.
All controls are inside an update panel.
When I click on a link button (from the navigation bar) I do the following things:
I save the current usercontrol using viewstate.
Than I reload the current usercontrol.
My 'page_load' always reloads the current control.
Always assigning the same ID to the programmatically loaded control allows me to save the usercontrol viewstate.
So everything look good except one little thing: the usercontrol viewstate in not available during the usercontrol Page_Load!
Look below for (* HERE).
The 'txtTest.Text' value is always "0" (also during postback).
It seems that the user control viewstate is restored after the (usercontrol) Page_Load.
How is it possible?
--- "DEFAULT.ASPX": ---
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="sm" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="pnlMain" runat="server">
<ContentTemplate>
<div class="links">
<asp:LinkButton ID="lnkButton1" runat="server" OnClick="lnkButton1_Click" Text="Link 1"></asp:LinkButton>
<asp:LinkButton ID="lnkButton2" runat="server" OnClick="lnkButton2_Click" Text="Link 2"></asp:LinkButton>
</div>
<br />
<asp:Panel ID="pnlCtrl" runat="server"></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
--- "DEFAULT.ASPX.CS": ---
private string CtrlAscx
{
get
{
if (ViewState["CtrlAscx"] == null)
{
ViewState["CtrlAscx"] = String.Empty;
}
return ViewState["CtrlAscx"].ToString();
}
set
{
ViewState["CtrlAscx"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
loadMyControl();
}
private void loadMyControl()
{
if (!String.IsNullOrEmpty(CtrlAscx))
{
pnlCtrl.Controls.Clear();
Control c = LoadControl(CtrlAscx);
c.ID = CtrlAscx + "ID"; // this line is mandatory in order to mantain the usercontrol viewstate
pnlCtrl.Controls.Add(c);
}
}
protected void lnkButton1_Click(Object sender, EventArgs e)
{
CtrlAscx = "Control1.ascx";
loadMyControl();
}
protected void lnkButton2_Click(Object sender, EventArgs e)
{
CtrlAscx = "Control2.ascx";
loadMyControl();
}
-- "CONTROL1.ASCX" --
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Control1.ascx.cs" Inherits="WebTest.Control1" %>
Control1: <asp:TextBox id="txtTest" runat="server" Text="0"></asp:TextBox>
<asp:Button ID="btnTest" runat="server" />
-- "CONTROL1.ASCX.CS" --
public partial class Control1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (txtTest.Text == "0") // * HERE
{
txtTest.Text = "1";
}
}
}
Try the EnableViewState="true" attribure on txtTest as well as on your custom user control when creating it :
.
.
c.EnableViewState = true;
pnlCtrl.Controls.Add(c);

Returning javascript in an ASP.NET ajax postback fails, but works fine on initial page load

I have a standard webpage containing an UpdatePanel, and a button. Upon loading the page some javascript is set and the page renders a chart (using Highcharts from here http://www.highcharts.com/products/highcharts).
When I reload the UpdatePanel using a button, dropdown etc the chart does not re-render.
For brewity I have shortened the code, but normally I have an UpdatePanel with a dropdown where users can select various charts, then data is fetched from a database and the results are sent back to the page.
Can anybody explain why it does not work / load the chart when I click on the button - and how to fix it?
The chart can be download here: http://www.highcharts.com/products/highcharts - simply add this to a folder called /js/highcharts.js
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="false" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string jschart = "var chart;$('" + up1.ClientID + "').ready(function() {chart = new Highcharts.Chart({"
+ "title: { text: 'Traffic',x: 0, style: {fontSize:'13px'} },"
+ "chart:{renderTo: 'container', defaultSeriesType: 'column'},";
litChartData.Text = String.Format("{0} {1}", jschart, getData());
}
private string getData()
{
// this is normally coming from a database...
return "xAxis:{title:{text:'Date'}, type:'datetime'}, yAxis:{title:{text:'Hits'}},"
+ "series: [{ name:'Impressions',type:'column',"
+ "data: [ "
+ "[Date.UTC(2011,7,18),13],"
+ "[Date.UTC(2011,7,24),21],"
+ "[Date.UTC(2011,8,30),60]]"
+ "}] }) });";
}
</script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="/js/highcharts.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scr" />
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<script type="text/javascript">
<asp:Literal ID="litChartData" runat="server" />
</script>
<div id="container" style="width:700px;height:300px;margin:0 auto;background-color:#eee"></div>
<center><asp:Button ID="btn" runat="server" Text="Ajax postback" /></center>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
the chart is rendered on the client side upon jquery's Ready event, but the event is not re-fired upon ajax calls. the solution might be emitting different scripts depending on whether the request is initial or subsequent one (ajax).
on initial call just emit the script you have in jschart var.
on subsequent calls emit the same script but without wrapping it into Ready event binding.
UPDATE:
i totally forgot update panel does not execute nested scripts after updating.
the solution for that is registering scripts via script manager. try the following code. note there is no script literal in the update panel anymore.
<%# Page Language="C#" AutoEventWireup="true" EnableViewState="false" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string jschart =
"if (window.chart) { window.chart.destroy(); }" +
"window.chart = new Highcharts.Chart(" +
"{title: { text: 'Traffic',x: 0, style: {fontSize:'13px'} }," +
"chart:{renderTo: 'container', defaultSeriesType: 'column'}," +
getData() +
"});";
ScriptManager.RegisterStartupScript(this, this.GetType(), "chart", jschart, true);
}
private string getData()
{
// this is normally coming from a database...
return
"xAxis:{title:{text:'Date'}, type:'datetime'}, "
+ "yAxis:{title:{text:'Hits'}},"
+ "series: [{"
+ "name:'Impressions',"
+ "type:'column',"
+ "data:"
+ "[[Date.UTC(2011,7,18),13],"
+ "[Date.UTC(2011,7,24),21],"
+ "[Date.UTC(2011,8,30),60]]"
+ "}]";
}
</script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script src="/js/highcharts.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scr" />
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<div id="container" style="width:700px;height:300px;margin:0 auto;background-color:#eee"></div>
<center><asp:Button ID="btn" runat="server" Text="Ajax postback" /></center>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

breakpoint problem in asp.net

I've posted a breakpoint in web user control. But Control is not going on breakpoint. Why is this happening.
I have done inline code.
<%# Import Namespace="System" %>
<%# Import Namespace="System.Web.UI.WebControls" %>
<%# Import Namespace="IBlog.Web.HandleUserControl" %>
<script language="C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Pagemenu.pageload();
}
public string Geturl(string url)
{
return Pagemenu.Geturl(url);
}
protected void menu1_MenuItemClick(object sender, MenuEventArgs e)
{
Pagemenu.menu1_MenuItemClick(sender, e);
}
//protected void Page_SelectedIndexChanged(object sender, EventArgs e)
//{
// Pagemenu.Page_SelectedIndexChanged(sender, e);
//}
//protected void MoreClick(object sender, EventArgs e)
//{
// DataList2.Visible = true;
//}
protected void lbmore_Click(object sender, EventArgs e) //this is the code i want to debug
{
}
</script>
<script type="text/javascript">
function mover()
{
var elem = document.getElementById("<%= DataList2.ClientID %>");
elem.style.display="block"
}
function mout()
{
var elem = document.getElementById("<%= DataList2.ClientID %>");
elem.style.display="none"
}
</script>
<div class="navi">
<div class="pages">
<ul>
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal">
<ItemTemplate>
<li><a href='<%#Geturl((string)DataBinder.Eval(Container.DataItem, "URL"))%>'>
<%# DataBinder.Eval(Container.DataItem, "Title") %>
</a></li>
</ItemTemplate>
</asp:DataList>
</ul>
</div>
<asp:LinkButton ID="lbmore" runat="server" Text="More" OnClick="lbmore_Click"></asp:LinkButton>
<div class="pages2" id="more" runat="server">
<%--More--%>
<ul style="background-color: #626669; padding: 0 6px 0 6px; margin: 28px 0 0 0px">
<asp:DataList ID="DataList2" runat="server" Visible="false">
<ItemTemplate>
<li style="float: left;"><a href='<%#Geturl((string)DataBinder.Eval(Container.DataItem, "URL"))%>'>
<%# DataBinder.Eval(Container.DataItem, "Title") %>
</a></li>
</ItemTemplate>
<ItemStyle Wrap="True" />
</asp:DataList>
</ul>
</div>
</div>
You've got an empty method - the framework won't allow you to attach a debugger in there, as there's nothing to do - the compiler will have optimised that code base out, as there's no code in the method.
Have you tried adding some simple code in the method to force it to do something (declare, set and view a variable for example)?
Edit to respond to comments
You have specified debug="true" in your web.config, and you have attached Visual Studio to the web site (either by pressing F5 in VS with the project loaded, or through "Debug | Attach to process...")?
Are you building a Web Application (you have to compile the project to see changes in code, you have a /bin folder in the root with a dll in in) or a web site (you don't have to compile things, you have an /app_code folder for shared classes, etc).

Method calls with time interval (asp.net c#)

Hi I want to call a method based on one time span
here is my trail
protected void binddata(object sender, EventArgs e)
{
// my logic here
}
Now I want to call this method for every 5 mins
using c# and asp.net how can i achieve this?
thank you
you have a timer control in ASP.Net ajax controls.
http://msdn.microsoft.com/fr-fr/library/system.web.ui.timer.aspx
It provides a postbak
exemple from msdn:
<%# Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<head runat="server">
<title>Timer Example Page</title>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
OriginalTime.Text = DateTime.Now.ToLongTimeString();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
StockPrice.Text = GetStockPrice();
TimeOfPrice.Text = DateTime.Now.ToLongTimeString();
}
private string GetStockPrice()
{
double randomStockPrice = 50 + new Random().NextDouble();
return randomStockPrice.ToString("C");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="10000" />
<asp:UpdatePanel ID="StockPricePanel" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" />
</Triggers>
<ContentTemplate>
Stock price is <asp:Label id="StockPrice" runat="server"></asp:Label><BR />
as of <asp:Label id="TimeOfPrice" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<div>
Page originally created at <asp:Label ID="OriginalTime" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Hope this help.
Using System.Threading.Timer - http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx.
Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler( binddata);
myTimer.Interval = 5*60*100;
myTimer.Start();

Resources