Cannot update an image using HttpHandler, UpdatePanel and a Timer - asp.net

I'm trying in ASP.NET to use a HTTPHandler to display an image and update every 5 sec.
This httphandler simply renders the current time into a Bitmap.
In aspx side, the Image is inside a AJAX UpadtePanel, and I'm using a timer to refresh the image every 5 sec.
My problem is that :
in IE9, the image is not updated at all. My HttpHandler is requested only once.
in chrome, the image is updated but it "blinks", ie every 5s it is cleared for few secs then displayed, then cleared again etc...
For debugging purpose I have also added inside the UpdatePanel a label, filled by a random value. It is well updated in both web browsers.
Here is the code in my aspx page :
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" ID="UpdateTimer" Interval="5000" OnTick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" ID="TimedPanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="UpdateTimer" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Image ID="TheImage" alt="httpHandler" src="getImage.ashx?id=1" runat="server" />
<asp:Label ID="Label" runat="server" Font-Size="XX-Large" ></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
In my HttpHandler, I did not forget to disable caching like this :
cache.SetCacheability(HttpCacheability.NoCache);
cache.SetNoStore();
cache.SetExpires(DateTime.MinValue);
And to prevent my IE9 web browser caching the image, I also tried to change ImageUrl each time the timer is invoked in the aspx.cs file, like following. But my HttpHandler is still called only once when the page is displayed for the first time :
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
Label.Text = ((System.Environment.TickCount / 100.0) % 360).ToString("F2");
TheImage.ImageUrl = "getImage.ashx?id=" + System.Environment.TickCount.ToString();
}
I hope my problem is well explained.
What do I do wrong?
Thanks in advance!

Some suggestions:
Add Enabled="True" to your timer.
Add the source code to your getImage.ashx to your post.
Use the asp.net tags like ImageUrl in your <asp:Image /> instead of the native html tags.
Use a div instead of an img (i.e. <asp:Panel />)
change the update mode of your UpdatePanel to Always

Related

update panel webcontrol required form field

I created a simple control which uses an update panel with a button click trigger and yes a script manager above the control. Click the button and a label is updated with the current time and this has worked fine for 6 years
Today, I changed the page to be responsive with Bootstrap but this is irrelevant to this question.
The control was added to a page which has labels and textboxes (simple form with first name / last name).
<asp:TextBox ID="txtFirstName" runat="server" CssClass="form-control input-lg" Placeholder="Your First Name" MaxLength="20" Required="true"></asp:TextBox>
If I remove:
Required="true"
and click the button in the control the date / time updates but placing this back stops the date / time updating. I need to use both as I wish for the first name to be required but also for the time to update
Simple Example:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblTime" runat="server" Text=""></asp:Label>
<asp:Button ID="btnRefreshTime" runat="server" Text="Refresh Time" OnClick="btnRefreshTime_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnRefreshTime" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Code Behind:
Protected Sub btnRefreshTime_Click(sender As Object, e As EventArgs)
lblTime.Text = DateTime.Now.ToString()
End Sub
What am I doing wrong and what would I need to do to resolve it without opening the form up to abuse (script attacks) etc? I don't wish to add the following to the page directive:
ValidateRequest="false"
Thank you in advance
Probabily the button server side event is prevented to execute due to the client side validation of required = "true".
Try to change the button with somewhat else which does not trigger client side validation by design. I would try with a LinkButton.

RegisterStartupScript not working with UpdatePanel and Google Visualization charts

On my ASP.NET page I am using Google Visualization charts inside of an asp:UpdatePanel. The user selects a chart they want to see from two asp:DropDownLists and then my C# code generates the JavaScript and I then call ScriptManager.RegisterStartipScript(...). When the page first loads the first default chart (i.e. first call to RegisterStartupScript) works and I can view the javascript from View Source. It is only on the postbacks that I get a blank chart and when I then go to View Source the page didn't receive the new JavaScript and it still has the old default JavaScript from the first page load.
Here is the weird behavior. If I use the exact same code but replace my Google Chart code with alert(...); then the alert() fires every time and when I view the source the script is there.
I've tried may different things and also followed such answers as here. Below is my code and any help would be appreciated, I've had other people look at this and we are all stumped.
FYI: If I remove all UpdatePanels and related items (ScriptManager and UpdateProgress) and use ClientScript.RegisterStartupScript() then everything works fine and I get the new JavaScript code on my page and the new chart appears as it should.
<asp:ScriptManager ID="ScriptMgr" runat="server" />
<asp:UpdatePanel ID="UpdatePanelData" runat="server">
<ContentTemplate>
<p>
<asp:DropDownList ID="PlotList" runat="server" AutoPostBack="true" Width="500px"
onselectedindexchanged="PlotList_SelectedIndexChanged"></asp:DropDownList>
<asp:DropDownList ID="RangeList" runat="server" Width="125px"
style="float:right;" AutoPostBack="True"
onselectedindexchanged="RangeList_SelectedIndexChanged">
</asp:DropDownList>
<br />
<asp:Label ID="PlotDescription" runat="server" Width="100%"></asp:Label>
</p>
<div id="chart_material" class="GoogleChart" style="width:100%;height:450px;"></div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RangeList" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="PlotList" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgressData" runat="server" DisplayAfter="500">
<ProgressTemplate>
<div class="LoadingPanel">
<asp:Image ID="LoadingImage" runat="server" ImageUrl="~/Images/loading_2.gif" AlternateText="Loading ..." ToolTip="Loading ..." style="padding: 10px;position:fixed;top:45%;left:50%;" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
And my C# code looks like this. The function DisplayPlot is called from the two DropDownList events and each list passes in themselves as 'control'.
private void DisplayPlot(Control control)
{
PlotInformation Plot = new PlotInformation(ChartDivID);
double Range = Convert.ToDouble(RangeList.SelectedValue);
string JavaScript = Plot.GetPlotScript(PlotList.SelectedItem.Text, Range);
PlotDescription.Text = Plot.GetDataPlotDescription(PlotList.SelectedItem.Text);
//string TestScript = "<script type=\"text/javascript\">\n\talert('" + PlotList.SelectedItem.Text + "');\n</script>";
ScriptManager.RegisterStartupScript(control, control.GetType(), ScriptKey, JavaScript, false);
//ScriptManager.RegisterStartupScript(control, this.GetType(), ScriptKey, JavaScript, false);
//if (!ClientScript.IsStartupScriptRegistered(ScriptKey))
// ClientScript.RegisterStartupScript(this.GetType(), ScriptKey, JavaScript);
}
I know this is late, but I spent a lot of time on the same bug.
Try changing:
ScriptManager.RegisterStartupScript(control, control.GetType(), ScriptKey,
JavaScript, false);
To
ScriptManager.RegisterStartupScript(UpdatePanelData, UpdatePanelData.GetType(), ScriptKey,
JavaScript, false);

Update Panel PostBackTrigger, Update Progress not displaying

I have an update panel and update progress with a PostBackTrigger Event. But update progress is not showing when i am clicking on the button. please find the below sample code
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="updatepanelDropDownTaskType" CssClass="Token-setup-popup" DynamicLayout="true">
<ProgressTemplate>
<div id="loading" class="loading">
<asp:Image runat="server" ID="imgBusyIndicator" ImageUrl="~/images/busy-indicator.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="updatepanelDropDownTaskType" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="btnExport" />
</Triggers>
<ContentTemplate>
<asp:Button ID="btnExport" runat="server" Text="Export To CSV" CssClass="button" CausesValidation="true" onclick="btnExport_Click" ClientIDMode="Static"/></asp:Button>
</ContentTemplate>
</asp:UpdatePanel>
My code behind
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = FileType;
Response.Write(content);
HttpContext.Current.ApplicationInstance.CompleteRequest();
Well Your code is Okay. Problem is with your Triggers which you are using in UpdatePanel.
Microsoft says
The UpdateProgress control renders a <div> element that is
displayed or hidden depending on whether an associated UpdatePanel
control has caused an asynchronous postback. For initial page
rendering and for synchronous postbacks, the UpdateProgress
control is not displayed.
See more details on MSDN
So you are using PostBackTrigger in your UpdatePanel which will cause a synchronous postback and UpdateProgress will not show up .
<Triggers>
<asp:PostBackTrigger ControlID="btnExport" />
// Incorrect
</Triggers>
Change it to
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnExport" />
// Correct
</Triggers>
And this will show up your UpdateProgress and will work as you are expecting.
As you have mentioned in your comments you are performing downloading as well on your Grid. Same way you could register your Button with ScriptManager. This will register your button and will aware of download button while asynchronous postbacks.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnExport = e.item.FindControl("btnExport") as Button;
if (btnExport != null)
{
((ScriptManager)this.Page.Master.FindControl("ID of your Script manager")).RegisterPostBackControl(downloadDocColumn);
// In Above line i assumed Script Manager is placed on Your master page.
}
}
}
Hope this helps...
I wrote an "Ajaxable Panel" (term explained in blog post) that may be helpful in your scenario.
http://leftyftw.wordpress.com/2011/10/01/an-ajaxable-panel/
It was geared towards SharePoint, but is perfectly applicable here.
Finally i acheived this task, with the help of iframe and endrequestHandler of sys.webforms. i explained clearly in my blog , please find the link http://bhuvanram.wordpress.com/. The Complete method has to be called in Iframe instead of calling in the same page
Try adding below to your web.config file under system.web
<xhtmlConformance mode="Transitional"/>
It may fix your problem if code is perfect.
Vote as answer if it fix your issue.

Cannot Download file in UpdatePanel

The below code works which allows me to download a Word document.....
Try
Response.BufferOutput = True
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Charset = ""
HttpContext.Current.Response.ContentType = "application/msword"
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=myfile.doc")
HttpContext.Current.Response.Write(s)
'HttpContext.Current.Response.End()
HttpContext.Current.ApplicationInstance.CompleteRequest()
HttpContext.Current.Response.Flush()
Catch ex As Exception
Response.Write(ex.Message)
End Try
But as soon as i add an UpdatePanel - it doesnt download the file and no errors are generated? After reading around i added a trigger with the ControlID value set to the button that starts creating the Word doc file. I've tried several combinations of code but nothing seems to work. Any help on how to narrow this down? I've also debugged and no errors show. Ive checked my downloads folder - nothing there, tried setting no cache (Response.Cache.SetCacheability(HttpCacheability.NoCache)) and that didnt work. As soon as i remove the UpdatePanel then all seems to work?
<asp:UpdateProgress ID="ProgressUpdate" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
<ProgressTemplate>
<img alt="progress" src="../images/loading.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="buttonDownloadFile" />
</Triggers>
<ContentTemplate>
..
Completely lost on this one. Could anyone suggest a workaround or how to tackle this problem?
The accepted answer is just plain wrong. You need to register the control with the scriptmanager. Mine is in the master page and here is the code i use to register any button for proper post backs.
private void MasterPageRegisterButtonForPostBack(Control bt)
{
MasterPage masterPage = Master;
if (masterPage is MainMaster)
{
var mainMaster = masterPage as MainMaster;
if (bt != null && mainMaster.MasterScriptManager != null)
{
mainMaster.MasterScriptManager.RegisterPostBackControl(bt);
}
}
}
I got it working the following way:
inside my Update Panel I configured the controls that may forece a full postback in order to get the download working.
(I'm using also Master pages,this is the same solution as Steve's but registering it in the aspx and not in code behind)
<asp:UpdatePanel runat="server" ID="UpdatePanelDownload" UpdateMode="Conditional" ChildrenAsTriggers="True">
<ContentTemplate>
<asp:LinkButton ID="LinkButtonDownload" OnClick="Download_Click" runat="Server">Save XML</asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="LinkButtonDownlod" />
</Triggers>
</asp:UpdatePanel>
I had to open an ashx Generic Handler in another window and passed some session variables to it, like filename, full path, etc.
I did it like this
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%foreach(var f in listOfObject){ %>
<a class="btn btn-danger" href="javascript:__doPostBack('ctl00$BodyContent$butDownload', '<%=f.ID %>')" >Download</a>
<%} %>
</ContentTemplate>
</asp:UpdatePanel>
<asp:LinkButton runat="server" ID="butDownload" OnClick="butDownload_Click" style="display:none;">LinkButton</asp:LinkButton>
///----Server-Side-----
protected void butDownload_Click(object sender, EventArgs e)
{
string strID = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(strID))
{
int id = int.Parse(strID);
//---Do what you want here
}
}
The UpdatePanel does not support file upload or download. There are tons of ajax-enabled components out there that will do this, Google is your friend.
EDIT: -
Some examples: -
http://forums.asp.net/t/1076322.aspx?How+to+create+a+flipcart+like+panel+for+showing+products+in+gridview - I like this approach, he injects an IFrame using JavaScript that points to a page responsible for downloading the file. Works inside an UpdatePanel
http://encosia.com/ajax-file-downloads-and-iframes/ - Similar approach

FileUpload in FormView inside an UpdatePanel

The Scenario:
I have an ASP.Net webpage which I intend to use for letting the user(not the real users, but content manager basically) insert and edit the records in a table using a FormView. This FormView is inside an UpdatePanel, as I'm also using cascading dropdownlists to let the user select some values.
Now, this FormView also contains 4 FileUpload controls, and as you might know that these fileupload controls require a full postback since most browsers do not let Javascript access the disk. So, this problem would have been solved by doing something like:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="InsertButton" />
<asp:PostBackTrigger ControlID="UpdateButton" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>
Edit: Forgot to add that the fileuploading takes place in the OnUpdating and OnInserting events of the SqlDataSource.
The Problem:
Since the InsertButton and the UpdateButton reside inside the Formview, I cannot directly access their ID's through markup. And MSDN says that:
Programmatically adding
PostBackTrigger controls is not
supported.
Please suggest some solution to make this work. Any insight on the matter is highly appreciated. Thanks.
P.S.- A workable solution for me was to set the UpdatePanel's PostBackTrigger as the whole FormView itself:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="FormView1" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>
But now due to a bit of change in requirements, this solution(if you call it a solution) is not acceptable.
Have you given a though about using Iframe for doing the postback ? something like:
<iframe name="uploader" id=uploader
src="uploaderSender.aspx?AllowedExtension=<%= AllowedExtension %>&StoringPath=<%= StoringPath %>&StoringFileName=<%= StoringFileName %>&OldFileName=<%= OldFileName %>&MaximumSize=<%= MaximumSize %>"
width="450" height="50" frameborder=0 scrolling=no >
</iframe>
with uploaderSender.aspx like :
<form action="UploaderReceiver.aspx" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" onchange="document.getElementById('IsFileUploading').style.visibility = 'visible'; document.forms[0].submit()"/>
<span id="IsFileUploading" style="visibility: hidden">
<asp:Image ID="Image1" runat="server" ImageUrl="~/immagini/Ajax-loader.gif" />
</span>
</form>
and UploaderReceiver.aspx like :
protected void Page_Load(object sender, EventArgs e)
{
//if there is one file to process
if (Request.Files.Count > 0)
//create the folder if it does'nt exists and returns the local path to get it
string StoringPathToBeSaved = StoringPath.GetFolderPath();
// append the name of the file to upload to the path.
StoringPathToBeSaved = StoringPathToBeSaved + StoringFileName + Extension;
Request.Files[0].SaveAs(StoringPathToBeSaved);
}
this is just bits of code just for you to figure out if you would be interested in this way of dealing with the upload, I can give you more if you want after.
see you, and good luck with your code,
Yay!! Finally got it to work!
Here's How:
Well contrary to what MSDN says, we can in fact add PostBack Triggers Programmatically. Not necessarily to the UpdatePanel, but to the ScriptManager.
After hours of playing around, here's what worked:
We are not able to access controls inside a FormView, untill the template has been rendered, so we can only add postback triggers after the formview's OnDataBound Event.
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
LinkButton lb = (LinkButton)FormView1.FindControl("UpdateButton");
ScriptManager.GetCurrent(Page).RegisterPostBackControl(lb);
}
//Similarily you can put register the Insert LinkButton as well.
}
And now, if your UpdatePanel causes ConditionalUpdate, you can do something like this to make it work:
The Markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>..
<EditItemTemplate>
...
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" OnClick="Cause_PostBack"CommandName="Update">Update</asp:LinkButton>
...
</EditItemTemplate>
..</ContentTemplate>
</asp:UpdatePanel>
CodeBehind:
//call this function as the OnClick Event Handler for the Controls you want to register as
//triggers.
protected void Cause_PostBack()
{
UpdatePanel1.Update();
}
Otherwise, if your situation allows it(as mine does), just set the UpdatePanel's UpdateMode="Always"
This is old, but was trying to solve another problem and ran into this. This wasn't my problem, but here's an alternative for anyone new who runs into this as well.
You stated your problem as:
Since the InsertButton and the UpdateButton reside inside the Formview, I cannot directly access their ID's through markup
You actually can access their ID's through markup to use as the ControlID in the PostBackTrigger. You just have to use the button's name that is created in the page html mark-up as the ControlID. You can find the name created by viewing the page source when you're viewing the page in the browser. It typically is the name of the FormView + $ + name of the button.
For example, let's say you have a FormView named "FormView1" that contains an Insert button which you gave the ID of "btnInsert" during design. If you open up your page in the browser to view it live and then view the page's source, you'll notice that the html mark-up of the button will actually be given the name "FormView1$btnInsert".
Use that name as the ControlID in your PostBackTrigger and your update panel will work.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="FormView1$btnInsert" />
</Triggers>
<ContentTemplate>....</ContentTemplate>
</asp:UpdatePanel>

Resources