unable to solve Timer_Tick - c#

i have same problem as this question.se the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation i havent any problem with <%# Page EnableEventValidation="false" %>.I solve it and i try
protected void Timer1_Tick(object sender, EventArgs e)
{
Label2.Text = Convert.ToString((Convert.ToInt32(Label2.Text) - 1));
if (Convert.ToInt32(Label2.Text) == 0)
{
Timer1.Dispose();
Submit();
}
}
Code work fine means submit () is work if i call from submit button.If its call from Timer_Tick its not work.And timer is not stop or dispose.What is a problem plz suggest?
timer:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
</asp:Timer>
<asp:Label ID="Label1" runat="server" Text="Remaining Time:(Min)"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="100"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>

where are you Enabling or Starting the timer on the page? The timer will not automatically start upon page load, you will need to explicitly call Start() or set Enabled = true

Label2.Text = Convert.ToString((Convert.ToInt32(Label2.Text) - 1));
Does that line works?
Maybe the if
Convert.ToInt32(Label2.Text) == 0
doesn't return true

Related

ASP.NET -> Synchronous call to a javascript function

I'm in need of a synchronous call from code-behind ASP.NET (C#) to a Javascript function.
I've tried the ScriptManager.Registerclient, but as this is asynchronous this is no good. I'm in need of some testing in javascript before returning a value (updating an UpdatePanel) to check whether or not the operation is valid.
For a short code example:
myButton_click(object sender, EventArgs args)
{
<callJavascriptSynchronous>
if (MyHiddenField.Value == "true")
//Do
else
//Don't
}
MyHiddenField is within an UpdatePanel. For the javascript function:
function javascriptFoo(myInteger)
{
var returnValue = window.external.TestInteger(myInteger);
document.getElementById('<%=MyHiddenField.ClientID%>').value = returnValue;
}
The UpdatePanel looks like this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:HiddenField ID="MyHiddenField" runat="server" ClientIDMode="Static" Value="" Visible="false"/>
</ContentTemplate>
Any suggestions on the synchronous call?
Thanks!
Edit: Added full code:
MyPage.aspx:
function javascriptFoo(myInteger)
{
var returnValue = window.external.TestInteger(myInteger);
document.getElementById('<%=MyHiddenField.ClientID%>').value = returnValue;
}
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:HiddenField ID="MyHiddenField" runat="server" ClientIDMode="Static" Value="" Visible="false"/>
</ContentTemplate>
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
MyPage.aspx.cs:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
ScriptManager.RegisterStartupScript(UpdatePanelContext, UpdatePanelContext.GetType(), "AlertTest", "AlertTest()", true);
string sVal = HiddenFieldContext.Value;
if (sVal == "true") //do
else //don't
}
When you're in your button's click-event, you've already left the frontend and cannot jump back for a function call. Execute the function first, clientside, upon the button-click (read about the OnClientClick event), then return your result with the postback.
This link addresses the same issue.

Calling asp net button click event with JS will not call server side event

Sorry to post perhaps a silly problem here, but I'm at my wits end with it. I have a hidden field with a button inside an update panel like so:
<asp:UpdateProgress runat="server" ID="updprCompLines" AssociatedUpdatePanelID="updpanCompLines">
<ProgressTemplate>
<img src="../Images/ajax-loader.gif" alt="Please wait..." /> </ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server" ID="updpanCompLines" UpdateMode="Conditional">
<%--<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnFillMembers" />
</Triggers>--%>
<ContentTemplate>
<div>
<asp:HiddenField ID="hdnField" runat="server" />
<asp:Button ID="btnFillMembers" runat="server" style="display:none;"
Text="DummyButton" onclick="btnFillMembers_Click" />
</div>
The update panel also contains a gridview and inside my gridview I have a link button:
<ItemTemplate>
<asp:LinkButton ID="lkbtBenefName" runat="server" Text='<%#Eval("COMPETENCE_CODE") %>'
OnClientClick='<%#Eval("COMPETENCE_LINE_ID", "return SelectedCompetence({0})") %>'/>
</ItemTemplate>
The call is to a JS function that is supposed to call the above button:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" EnablePageMethods="true"/>
<script type="text/javascript">
function SelectedCompetence(CompetenceLineId) {
document.getElementById('<%= hdnField.ClientID %>').value = CompetenceLineId;
var clickButton = document.getElementById('<%= btnFillMembers.ClientID %>');
clickButton.click();
}
</script>
Button click event method:
protected void btnFillMembers_Click(object sender, EventArgs e)
{
lblGvMemError.Text = "";
lblGvMemError.ForeColor = Color.Red;
if (hdnField.Value != null || hdnField.Value.ToString() != "")
{
try
{
int CompLineId = Convert.ToInt32(hdnField.Value);
GetSelectedCompLineMembers(CompLineId);
}
catch (Exception ex)
{
lblGvMemError.Text = "Error: " + ex.Message;
}
}
updpanCompLinesMembers.Update();
}
The problem is that while debugging, it never runs the click event and it doesn't give any error messages either. I don't understand, I have a similar form where this works; I don't get why it doesn't here... Any help please?
Have you confirmed that SelectedCompetence is being called via an alert or similar? Additionally, have you made sure that the clickButton variable is being assigned to successfully?
I know this isn't an answer, but don't yet have the reputation to comment, and sometimes it's the easy stuff so maybe this will help! :)

Update panel from a server side thread

I am trying to develop a chat using aspx. I already got it working with asmx + winform but now I have problems with asmx + aspx.
Basically what I want to do is call the WebMethod CheckForMessages every two seconds and, if there are messages, add them to a list box inside an update panel and do UpdatePanel1.Update();.
The problem is that apparently I can' t do this using a thread like I do in my winform.
void check() {
while (true) {
Thread.Sleep(2000);
string message = CheckForMessages();
if (message != "") {
ListBox1.Items.Add(message);
UpdatePanel1.Update();
}
}
}
I start the thread like this:
protected void Page_Load(object sender, EventArgs e) {
timer = new Thread(new ThreadStart(check));
timer.Start();
}
It doesn't throw an exception or anything, the program runs as intended. The web service is called, a string is returned if there is a message, the thread adds the message to the list and calls UpdatePanel1.Update();. Yet the panel is not updated.
What could the problem be ?
In ASP.Net you can use timer control along with updatepanel.
<asp:UpdatePanel runat="server" ID="uxUpdatePanel" UpdateMode="Conditional" EnableViewState="true">
<ContentTemplate>
<div>
<asp:Label ID="Label1" runat="server" style="display:none;"><%=GetMessageLog()%></asp:Label>
<asp:ListBox runat="server" ID="ListBox1" EnableViewState="true">
</asp:ListBox>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="uxTimer" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer runat="server" ID="uxTimer" Interval="2000">
</asp:Timer>
And in Code-behind you to code like:
public string GetMessageLog()
{
string message = CheckForMessages();
if (message != "") {
ListBox1.Items.Add(message);
return DateTime.Now.ToLongTimeString();
}
This should work for you. But I will recommend you to use Javascript and JQuery to call Web-Service asynchronously with setTimeout function.
Instead of the server actively pushing changes to the client, try the opposite : make the client actively query the server, and update its state accordingly.
One way to do that is create a button to query the server manually. After you verify that it works, make the button hidden using css, and set a function to click the button in a regular interval. You can use javascript setInterval for this.
To click a button in javascript, you can do something like this :
setInterval(function(){ document.getElmtById(“<%= theButton.ClientID %>").click(); }, 2000);
The above code should click theButton every 2 seconds.
You should have a look at SignalR.net. Jabbr.net is based on signalR and exactly what you need. https://github.com/davidfowl/JabbR
yes Vishal... maybe less complex:
<asp:UpdatePanel ID="updatePanelPromptB" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="labelPlayback" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timerPromptB" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Timer runat="server" ID="timerPromptB" OnTick="timerPromptB_Tick" Enabled="false" Interval="4000" />
private void promptBottom(string text)
{
labelPlayback.Text = text;
updatePanelPromptB.Update();
timerPromptB.Enabled = true;
}
protected void timerPromptB_Tick(object sender, EventArgs e)
{
labelPlayback.Text = "OK";
timerPromptB.Enabled = false;
}

Using a Timer post back, which controller to use that doesn't post back to server?

Being new to ASP.NET I have run into trouble building my own Whack-a-mole program. I think my problem comes from using Buttons, which by themselves send post backs to the server, making the software unusable. The looks are in place, making new buttons show up in the grid, in different places by random. However, when a button is pushed – the score doesn’t change (which I feel is strange).
Not so strange is that the Button doesn’t work since it sends post back to the server – reloading the UpdatePanel. I think I should use a different controller like the CheckBox and style it hard using CSS (which isn’t a problem). Is this the correct way to go, or should I make use of JavaScript AJAX instead?
Note to self: This technique shouldn’t be used in a public application since it put too much unwanted pressure on the web server. Use in test and learning only!
Thanx for listening!
<%# Page Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="Whack-a-mole.aspx.cs"
Inherits="Whack_a_mole" %>
<asp:Content ID="Content" ContentPlaceHolderID="cphContent" runat="server">
<h1>Whack-a-Mole</h1>
<asp:ScriptManager ID="smgrTime" runat="server" />
<asp:Timer ID="Timer" OnTick="Timer_Tick" runat="server" Interval="2000" />
<asp:UpdatePanel ID="updpButtons" runat="server" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer" />
</Triggers>
<ContentTemplate>
<asp:Label ID="lblPoints" runat="server" Text="Score: 0p" />
<asp:Button ID="Button1" runat="server" BorderStyle="Outset"
BorderWidth="3px" CssClass="mole" Text="Mole"
onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" BorderStyle="Outset"
BorderWidth="3px" CssClass="mole" Text="Mole"
onclick="Button2_Click" />
<asp:Button ID="Button3" runat="server" BorderStyle="Outset"
BorderWidth="3px" CssClass="mole" Text="Mole"
onclick="Button3_Click" />
<!-- continues the same way down to Button25 -->
<asp:Button ID="Button25" runat="server" BorderStyle="Outset"
BorderWidth="3px" CssClass="mole" Text="Mole"
onclick="Button25_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Excerpt from the Code file:
// points vairable
private int points;
// Property for points
public int Points
{
get { return points; }
set { points = value; }
}
protected void Timer_Tick(object sender, EventArgs e)
{
Random random = new Random();
int visible;
foreach (Button button in buttonList)
{
visible = random.Next(1, 10);
if (visible == 3)
button.Visible = true;
else
button.Visible = false;
}
lblPoints.Text = "Score: " + Points + " p";
}
protected void Button1_Click(object sender, EventArgs e)
{
Points = Points + 1;
}
Where is your Points variable declared?
I think it might be a member of the Whack_a_mole WebForm class and that is why it doesn't update. The instance of the WebForm is only used for 1 Postback, and then it is destroyed.
But more important, for a game like this you should use JavaScript or SilverLight.

Asp.net Timer resets on page refresh

I'm using a simple asp.net timer with this code as a backend
protected void Timer1_Tick(object sender, EventArgs e)
{
int seconds = int.Parse(Label1.Text);
if (seconds > 0)
Label1.Text = (seconds - 1).ToString();
else
Timer1.Enabled = false;
}
The timer is grouped along with a Label and a Button inside a UpdatePanel in my front-end.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Image ID="RedBox" runat="server" ImageUrl="~/images/redbox.png" Visible="false" CssClass="redbox1" ClientIDMode="Static" />
<asp:Button ID="schlbtn1" runat="server" Text="Go To Lectures" CssClass="btn btn-lg btn-success btn-block" OnClick="schlbtn1_Click" Visible="true" ForeColor="Black" ViewStateMode="Enabled" ClientIDMode="Static" />
<asp:Label ID="Label1" runat="server" Visible="false" CssClass="timerlbl" Font-Size="XX-Large">60</asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick" Enabled="false">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
I'm looking for a way to make the timer NOT to reset on every page refresh. I need the timer to still count down until it reach 0 even if the client is not on the same page. I tried Sleep methods but think this is not the solution. Please make any kind of suggestions.
Store the timeout in the session:
Add to page load:
if (Session["timer"] == null)
{
InitTimer(120); // or whatever initial value is
}
Add method:
public void InitTimer(int secs)
{
Session.Add("timer", secs);
Timer1.Enabled = true;
}
Change tick method:
protected void Timer1_Tick(object sender, EventArgs e)
{
int seconds = (int)Session("timer");
if (seconds > 0)
{
seconds--;
Session["timer"] = seconds;
Label1.Text = seconds.ToString();
}
else
Timer1.Enabled = false;
}

Categories