Real-time updates like Twitter - c#

How do you implement a real-time update like Twitter does ("423 more tweets since you started searching")? I need to refresh my page at least every 10 seconds. I'm using ASP.NET MVC and jquery.

You could use the setInterval javascript function which allows you to poll the server for updates at regular intervals using AJAX:
window.setInterval(function() {
// This will be executed each 5s
// TODO: query your server for updates probably using AJAX
// example with jquery:
$.getJSON('/arethereanyupdates', function(data) {
if (data.isupdates) {
alert('yeap there are updates');
}
});
}, 5000);
There's also a push technology in HTML5 called WebSockets which allows the server to notify the client for updates but of course you will need an HTML5 compatible browser which nowadays is not difficult to find and a WebSocket API compliant server.

You can do an AJAX call to your server asking for updates, if the answer is positive (there are new things) you can show a javascript windows advising the user or just update the page content you need.
regards.
UPDATE: This how-to implements similar behavior

In the absence of long-polling (aka COMET) support in todays browsers (this should, however, change soon, with HTML5), I'm polling the server every n seconds using AJAX request and sending the timestep of the latest visible entry/item/tweet/whatever. Then the backend count the number of newer items and returns it back to the browser.

Related

ASP.NET WebAPI Ajax with progress

I have a really long webAPI request that basically does the follow :
1. retrieves a list of item categories from the db
2. for each category, retrieve all the items in the category
Now, the entire process takes a very long time and I don't want the user to wait till the entire process is over, if a category has finished loading I want it to return to the client
Does anyone know how I can do that? Send a request and get progress notifications by the server whenever a part of the request has finished?
You could use SignalR to send the data from the server to the client when it's available.
The other option is polling from the client. The client makes the initial request, which triggers a server side process that prepares the data and keeps it somewhere (in memory, in a database). Then the client polls the server for new available data until the server process finishes.
you need to break your request. use for loop. if elements from first category are downloaded then do something with them before going for second category.
so your request will go inside some loop. You can use Jquery or page methods if you are using asp.net webforms
PushStreamContent might help you:
http://weblogs.asp.net/andresv/asynchronous-streaming-in-asp-net-webapi

Send The Client a Notification after Postback ASP.NET

I have an UPDATE SQL transaction that connects to a SQL Server database using C# .NET 4.0 (I'm currently using SqlCommand.ExecuteNonQuery which is not Async so I'm sure I'm gonna need to change it). The transaction execution time is long (about a minute). I have ASP.NET application (Web Forms) and I wish to execute the transaction asynchronously while keeping the user able to interact with the application (navigating through pages). After the execution is finished, I wish to push kind of a notification to the user telling him that the transaction is finished.
I realize that my problem has two parts: the ADO.NET Async part and the part of triggering the application to push a notification to the client when the transaction is complete.
What's the best approach to implement both parts?
SignalR will fulfill your requirement
http://www.codeproject.com/Articles/315938/Real-time-Asynchronous-Web-Pages-using-jTable-Sign
or after SQl operation you can get response from Executenonquery and save it into hidden field, in client side you can use Jquery setInterval to check th hidden field value
Actually You can use jquery to do asynchronous call to the method that execute SQL transactions then you will return a message to the user after code execution has been finished.
For more information check the following example
Jquery Code
$.post( "PageName.aspx/UpdateMethodName", {}) //you can replace method name
.done(function( data ) {
alert(data);
});
Now in your ASPX page you must have a static method decorated with [WebMethod] attribute
[WebMethod]
public static string UpdateMethodName() //method name will be called from jquery
{
// your
return "Message";
}
More Information can be found here
JQuery.Post()
Using jQuery to directly call ASP.NET AJAX page methods
I hope that help

How to send data from C# to JavaScript/AJAX webpage

Basically, I have a need for a c# server to be able to send data back to an HTML5 webpage which has previously send data to the server. The server is retrieving data from another application and this data then needs to be send to the webpage to be displayed.
This c# server is running on .NET CF 3.5 so websockets are not an option (not supported).
I have seen some suggestions elsewhere but nothing which fits the necessary criteria for this particular situation. Most other implementations seem to work on the basis that the webpage will only be waiting for this data to be sent over.
Any and all suggestions welcome!
If websockets are not an option then you are left with Comet.
Client-side you could do something like this :
(function poll(){
$.ajax({
url: "url",
success: function(data) { /*display data*/ },
complete: poll,
timeout: 30000 });
})();
Which means an ajax request will be sent every 30 seconds.
This is not as performant as websockets but it works quite well.
Create an .aspx page and remove all the HTML from it. Call it GetData.aspx
In the code behind of GetData.aspx.cs you can receive the POST data from the HTML5 page.
Do work.
Use jquery.
$.post("GetData.aspx",{name: value},function(json){
// put processing instructions here.
});
There are two ways to do this :
Using a ASP.NET web-page
Create HTML element that calls a javascript function
Inside of the javascript function, use ajax to make a POST to a ASP.NET Web Page (that uses C# as back-end)
Get the returned value in the ajax "success" block.
Use as you wish...
Using a jSON string return
Create HTML element that calls a javascript function
Inside of the javascript function, use ajax to make a POST to a Web Service (that uses C# as back-end), that returns a jSON string.
Use the returned jSON data in which ever way needed.
I personally prefer jSON, as it emulates a data set, and works well with HTML and ajax.

how to call javascript function at backend in asp.net?

If I want to call a javascript function after some code has been run in backend, how to do that? I don't want to add onclientclick event in frontend. I need to run the frontend function after a certain backend code has been run. Thanks in advance.
The best bet is to use Page.RegisterStartupScriptBlock.
When you submit to the server, the server is going to process your request and any other event / code that is required. It will then send back to the client the response.
If you want a user to invoke an action / event (say a button click), have it hit the server and then do some Java Script action after that please look at the following posts:
http://forums.asp.net/t/1003608.aspx/1
http://wiki.asp.net/page.aspx/1574/differences-between-registerclientscriptblock-amp-registerstartupscript-and-how-they-work-with-ajax-update-panel/
http://www.codeproject.com/KB/aspnet/ClientServer.aspx
The way (I) would do this is to refactor my code so that the code behind is called from a jQuery post to an ashx code file.
then on return of that function i can run whatever I like.
If you want details, let me know.
However, if this is not useable, then you could either place a property in your aspx page;
public string Action { get; set; }
then in your html;
var action = '<%= this. Action %>';
and perform an action.
Or you might set a hidden field to a value and check against that.
edit
this largely depends on when in the life cycle the code behind is being run. On ajax postback, on initial execution? When?
Client Script in ASP.NET Web Pages is the MSDN reference that you probably want.
The best way i can think of to do this is with web sockets. There are a few c# web socket implimentations around, such as Nugget. This allows you to open a socket with your client and allows for the possibility of the server proactively contacting and sending data to the client. There are other techniques to have the server talk to the client such as long polling. This way you can have the server call the client once something has happened on the server.

How would you overcome this issue? Jquery + ajax + server timeout

I am using asp.net mvc, C# and jquery. My site is uses ajax heavily. This has lead to a problem and I am not sure how to fix it (well fix it better than my current solution).
Scenario.
User logins into my site - cookie set, server has timeout of 30mins
User walks away for 30 mins
User comes back and clicks on one my ajax enabled jquery tabs
Request sent to server
Server goes nope user timed out send them back to signin page.
since it is a an ajax request the redirect gets rendered in the tab. It look ugly(an entire page rendered in a tab), user is probably extremely confused at this point.
Problem
As far as the server and ajax is concerned the ajax request is valid and success response is sent back. So I can't go check for an error as the request was successful just not the right data coming back.
Solution 1
User logins into site.
Jquery ajax request made to find out users timeout
timeout is 60 seconds less than server timeout
Once timeout on javascript side is hit. Jquery dialog box comes up and tell them their session expired and forces them to be redirect to sign in pack.
A user can't click on anything as the dialog box blocks that. If some users firebug or something they can remove it but then server timeout will still be effect and they will get the ugly version(don't care then).
If a user makes an ajax request the timeout on the server side is reset as well as the one on the client side.
Problems
User could walk away and another person could come and the timeout message could be up but they still could have a potential of 45 seconds of trying to make a new request and reset the timeout. This is very low and not too worried about it.
Sometimes I have observed is it just times out( the client side) and I don't know why. I never can recreate the problem( seems to happen to other people but not when I am testing). So I am guessing something did not hit write or something else went wrong.
So number 2 is really the big reason why I would want to find another solution.
Solution 2 (speculation).
I was thinking maybe if I can make my own response header or something so if the server times out then I can send some 303 redirect or something in that nature that I could check for then do a jquery redirect based on that.
However I am not sure where to do that in my C# code or if I can do something like that.
You could always add a custom HTTP header in your LogOn action which could be intercepted by AJAX calls and act accordingly:
public ActionResult LogOn()
{
Response.AddHeader("X-LOGON", "LogOn");
return View();
}
And in the success callback check for the presence of this header:
$.ajax({
url: '/home/someaction',
success: function (data, textStatus, XMLHttpRequest) {
if (XMLHttpRequest.getResponseHeader('X-LOGON') === 'LogOn') {
// the LogOn page is being displayed
// probably timeout or unaithorized => act accordingly
}
}
});
I don't see why your authentication handler (action filter) can't handle this by returning 403 (forbidden) which AJAX handler will then process by setting window.location to /login.
I basically do solution 1, except that (1) I've encapsulated it into a plugin and (2) I inject the session timeout in the page when it renders. You can see details on my blog, http://farm-fresh-code.blogspot.com, in this article. One addition is that, when the client-side times out, it automatically invokes the logout action to actually terminate the session.

Categories