Force a PostBack - asp.net

I have an asp form in which on_button_click a thread a being executed following a finite number of loops. So I want after every single loop completion a postback should occur. So would you please help me out to find the way of doing post back by coding after single loop completion.
Thread tt = new Thread (mainProcess);
Button1_Click() {
tt.start();
}
void mainprocess()
{
while(true)
{
//do this
if(Condition)
break;
//do postback
}
}

From the moment you fire a thread on code behind, the thread did not have any control/connection with the page to make some how a postback or refresh.
You need to redesign your page some other way. One possible is to use ajax to make your call to the page and get the results when they are ready, or to make using ajax time to time call to code behind and see if the data are ready to gets them. Or make every 20 seconds a page refresh and again check if the loop has ended and get and show the data.

Related

Forcing an ASP.NET page_load

I have an ASP.NET (4.5+) app that calls an asynchronous task from Page_Load in order to obtain data for the page. I want to refresh that data every 15 minutes with out any user input.
First I tried using a timer and calling Page.ExecuteRegisteredAsyncTasks() in the timer function. No error but my async task never gets called. Just during Page_Load.
Then I tried various techniques for force a reload of the page figuring that would cause Page_Load to get called again but each attempt resulted in an exception being thrown saying that technique could not be used at that time.
The C# method I want to call every 15 minutes is defined as a private async Task.
What is the best way to call this method every 15 minutes? As I wrote above it is getting called successfully from Page_Load but never again.
You will need to use a worker of some kind. If you had a timer then every time you refreshed the page, the timer would reset, you could use possibly a session variable to keep track. This is just the nature of the page lifecycle.
One alternative is to create a service, you could use an ASMX service for this and pull the data from the client-side. Using HTML5 Local Storage to keep track of the time last updated, or even "nextTimeToUpdate" store 15+ minutes from now. Set a time out of every 1 minute to check the current DateTime and if >= nextTimeToUpdate then trigger the request via AJAX.
Since local storage persists even after the browser is closed, when the user next visits the page and the data will still be there. The data is only lost if the user shuts down their machine/cleans their browser.
Edit
Assuming you want to trigger these events server-side. Move the async task into a new class, instantiate or inject it on the page you want.
Scott Hanselman has an article on How to run Background tasks in ASP.NET. A noteworthy library Hangfire
You have to use Timer, it is best way, I think.
Just follow next steps:
In design page:
<asp:ScriptManager ID="manager" runat="server" />
<asp:Timer ID="timer" runat="server" Interval="900000" OnTick="timer_Tick" />
Then create some function (e.g. MyFunc()), and your code behind:
protected void Page_Load(object sender, EventArgs e){
MyFunc();
}
protected void timer_Tick(object sender, EventArgs e){
MyFunc();
}
protected void MyFunc(){
//do all actions, what you need, here
}

How to prevent calling of function on every postback request

I have bind complete menu on postback now every post back request function
call and bind menu again i want to call it only first time please suggest
here below is my code
if (!Page.IsPostBack)
{
objCommon = new Common();
Common.UpdateLoginSession();
if (hiddenMenuFlag.Value == "S")//used hidden field but not working as is
//does not retain value on post back please suggest
{
BindMenu("0");//here is function for binding menu
hiddenMenuFlag.Value="";
}
}
use
if (!IsPostBack)
{
--------------------------;
--------------------------;
}
All functions or code inside this condition will run only for the first time, when page is requested. It won't execute on reload.
If you want to run a code only once; when the user request the page then you can use some session as suggested above.
If you want to run a code only for the first time when application runs, then you can use Application state to control your code
You could create a session variable and then check that variable to ensure your code will execute only once.
You create session variable like this:
Session["myVar"] = "myText";
And then you could check it value like below:
((string)Session["myVar"]) == "myText"

Asp.net webforms autosave

I understand this may be an elementary question, but I'm new to Asp.net webforms, so please bear with me.
I have a lengthy form on a page that I would like to autosave when users type in a field, or make a selection. The problem is, all I've been able to find online is autosaves that work on a timer. I'd prefer that it saves as the user makes their edits. Also I would like just the individual form element being edited to be sent to the server to avoid sending the entire page back each time.
I've read that I should use a webservice to accomplish this, but since I want to autosave individual items and not the whole form on a timer, how would I set up a webservice to accomplish this? I'm new to webservices I'd like to know what to read up on. Any links are appreciated.
Also, how is the autosave functionality effected when using asp.net validation controls? I've looked around but can't tell if the entire page needs to be valid to make a trip to the server, or if just a single valid item can be sent itself.
Thanks for any help!
If you set AutoPostBack=True on the field, and you add an OnChange event for it (this will vary depending on the type of field the user is interacting with), you can execute a save. Don't call Page.Validate in the methods where you're doing these updates. Call it when you hit the Submit button.
This could cause a LOT of round trips to the server, and it's a lot of code to write and debug.
The Timer approach is one call to one method on a repetitive basis. If you can I'd recommend going with a timer, but sometimes that's not an option.
Generally speaking this is what you'll want to setup on the client-side. Ideally, you will end up with lots of tiny requests which do not require much power on the back-end. This however depends on lots of variables including the database engine you're using.
$(document).ready(function () {
$("input").blur(OnFieldChanged);
});
function OnFieldChanged()
{
var $this = $(this);
var isValid = ValidateField($this);
if (isValid)
{
SaveField($this);
}
}
function SaveField($field)
{
if ($this.val() === $this.prop("oldVal")) return;
var data = {
id: $("idfield").val()
};
data[$field.attr("id")] = $field.val();
$.post({..}).done(function() {
NotifySaved($this);
$this.prop("oldVal", $this.val());
});
}
function ValidateField($field)
{
// Validate the field with your method of choice, manually call Microsoft's client-side validate function or switch to jquery validate.
return true;
}

Actionscript 3: How to do multiple async webservice call requests

I am using Flex and Actionscript 3, along with Webservices, rpc and a callResponder. I want to be able to, for example, say:
loadData1(); // Loads webservice data 1
loadData2(); // Loads webservice data 2
loadData3(); // Loads webservice data 3
However, Actionscript 3 works with async events, so for every call you need to wait for the ResultEvent to trigger when it is done. So, I might want to do the next request every time an event is done. However, I am afraid that threading issues might arise, and some events might not happen at all. I don't think I'm doing a good job of explaining, so I will try to show some code:
private var service:Service1;
var cp:CallResponder = new CallResponder();
public function Webservice()
{
cp.addEventListener(ResultEvent.RESULT, webcalldone);
service = new Service1();
}
public function doWebserviceCall()
{
// Check if already doing call, otherwise do this:
cp.token = service.WebserviceTest_1("test");
}
protected function webcalldone(event:ResultEvent):void
{
// Get the result
var result:String = cp.lastResult as String;
// Check if other calls need to be done, do those
}
Now, I could ofcourse save the actions in an arraylist, but whose to say that the addToArrayList and the check if other calls are available do not mess eachother up, or just miss each other, thereby halting execution? Is there something like a volatile Arraylist? Or is there a completely different, but better solution for this problem?
Use an AsyncToken to keep track of which call the returned data was for http://flexdiary.blogspot.com/2008/11/more-thoughts-on-remoting.html
When I want to store data in an async manor I put it in an array and make a function that will "pop" the element as I send it off.
This function will be called on complete and on error events.
Yes I know there could be an issue with the server and data lost but oh well. That can also be handled
Events will always fire however, it may not be a complete event that gets fired but could be an error event.
Once the array is empty the function is done.

Asp.Net / Ajax updating update panel automatically how to?

I have an Asp.net page which requires certain sections to be partially updated automatically at an interval of 5 seconds.
I was planning to use the good old Timer control with the AJAX Update Panel for this purpose, but after a bit of reading on this control i found out that it may have some problems especially if,
1) The time difference between the async event performed ( 4 seconds ) by the update panel and the Timer's tick interval ( which is 5 seconds ) are quite small, the update panel will be held up in the async operation all the time.
2) Also, the fact that timer control doesn't work very well with Firefox.
I just wanted to get your opinion as to whether if i should go ahead with the timer and update panel approach, write some custom javascript that does the partial page update or some other strategy altogether.
Personally, I tend to think that the DIY approach is better -- easier to debug and easier to write.
You can use a javascript setInterval for a timer, and every time the function is called, you can initiate an ajax request to your asp.net code-behind to fetch whatever data needs to be updated.
For example, let's say you simply need to, every 5 seconds, update the current time on a page. Let's assume you have a span of ID currentTime on your page, something like:
<asp:Label id="CurrentTime" runat="server" CSSClass="currentTimeLabel" />
In your initial PageLoad event, you set the time:
protected void PageLoad(...)
{
CurrentTime.Text = DateTime.Now.ToString();
}
Now you need to define some javascript on your page that will, every 5 seconds, call the code-behind and get the new date/time value.
Doing this with something like jQuery is very simple:
$(document).ready(function() {
setInterval(5000, updateTime);
});
function updateTime() {
url: "myPage.aspx/SomePageMethod",
success: function(data) {
$(".currentTimeLabel").text(data);
});
}
In ASP.NET, getting the PageMethod to work is the trickiest part (for me, anyway). You need to create a public function in your code-behind with a 'WebMethod' attribute. Something like this:
[WebMethod]
public static string GetCurrentTime()
{
return DateTime.Now.ToSTring();
}
I didn't test any of this code, but the basic premise is sound and should work fine.
Now, this may seem more complicated than using an UpdatePanel, but I find it easier when I know what code is actually running on my page.
If you need to update a series of controls instead of just one control, you can use a more complicated web method that returns xml or json data, and then parse that using javascript.

Resources