real time server to client communication asp.net c# - c#

Hello I am researching some solutions to the following problem any advice would be appreciated.
I have an application that is in c# asp.net web forms application. I need to be able to do real time updates between clients here is the scenario:
Client one is updating page 1 let's say a page that has a text box and a grid view. The user is enters some text in the text box and when submitted it saves in a SQL server db and updates the grid view. At the same time client two is look at page 1 I need to have the server push the update to the second client when the db is updated. I am looking for a solution that does not require JavaScript and can possibly push from the server and call a code behind function in c# on client 2.
Performance is a concern because there is potentially high use on the SQL sever and high level of users. So I would prefer not to poll the db from every client.
Thanks for your help. Any suggestions would be great.
Update: here is my solution for now:
html
$(function() {
var updater = $.connection.updateHub;
//Create broadcast function
updater.client.broadcastMessage = function () {
__doPostBack("upNotes", "");
};
//Start the connection to the hub
$.connection.hub.start().done(function() {
$(<%= btnNotesSubmit.ClientID %>).click(function () {
updater.server.send();
});
});
});
<asp:UpdatePanel ID="upNotes" runat="server" UpdateMode="Conditional" OnLoad="ReloadNotes">
<ContentTemplate>
<asp:GridView ID="gvNotes" runat="server">
ect...
OnLoad calls a codebehind function in C# that checks the db for changes and then rebinds the grid

Well, you may not be too successful.
Without Javascript keeping an open socket, there is no way to actually push changes back to the client though continual polling of a web page will at least refresh. With Javascript, you can make a long-lasting AJAX call (with timeout and error handling please), and updating the web page when the call finally succeeds.
That web does does not necessary have to hit the database each time it is polled though.
If you don't want to involve the database each time the page is polled, you can either signal a pending change via a different method, or you can have the database update something that can be check without "hitting the database".
For example, if everything is running on the same web server, you can simple write a timestamp whenever you at the same time you update the database to shared memory, and then examine that shared memory when you poll the webpage and reload from the database when the timestamp is updated. I am not recommending this method per se, just giving a simple example.
I would encourage you to drop the rule about "no javascript", if you real-time page is valuable to the customer at all, they can whitelist your service to allow javascript. And continually polling of the entire web page is uglier than a butt pimple.

Related

ASP Notification Mechanism

I am creating a website, where people can add each other as friend.
For example I got 2 users:
User ONE with UserID = 1
User TWO with UserID = 2
When User One adds User Two, I write this to a database, with an Integer to track the status:
0 = waiting
1 = accepted (are now friends)
If denied -> I just delete that record from the database.
When User One add User Two, I want to send a notification to User Two.
So User Two should get a notification about that User One has added him, without refreshing the page.
What can I use to create notifications after adding someone as friend?
Should I look to a kind of trigger on the database that sends something to the website after a record is added, or are there other mechanisms that you guys recommend me?
It's a ASPX website, without MVC.
The same mechanism I would like to use for a Message System.
There are 3 ways of achieving this, from simplest to most complex:
Polling
Write a javascript that calls a rest service on your site every x minutes and updates the DOM of the page
Long Polling
Similar to polling but keeping an open connection to have instant replies without waiting between polls. Requires having an api that can keep a pool of open connection and a background thread on the server that polls the database for changes, which it percolates up to the javascript if needed
Web Sockets
Upgrades the connection to a full two ways connection (websocket protocol). Similar to long polling server side.
As you can see any other option than 1. is fairly complex, but you can take a look at the SingalR library to get you started.
You can use AJAX to poll the database for such updates, AJAX is mainly used to refrain from forms submissions by acting asynchronously.
Here is a simple jQuery example of AJAX polling:
function doPoll(){
$.post('ajax/test.html', function(data) {
alert(data); // process results here
setTimeout(doPoll,5000);
});
}
Also, as Brad M commented, you can "cache" the "Friends" table into the memory and poll against it rather than the DB - It would be much faster.

Detect when user exits the browser or tab and insert into database

I want to insert some data into database when user cuts/exits the browser or tab.
This is the statement which I want to be executed.How is this possible
_objQ117.insert();
I'm in no way a C# guru, but I'll try to explain the general principle.
Browsers are pretty protective of the user's data these days, though there are possibilities.
You may use something akin to onunload or onclose to send an AJAX request to the server, executing the query.
However, support of this may be spotty in certain browsers. By sending AJAX requests, say every minute or so, the server will be aware that your client is still connected--until the requests stop. An AJAX request is nothing more than a standard HTTP request created by javascript and returned as a variable(i.e. without necessarily loading an entire page, as the server only returns a small amount of result data)

web-development: how to display an increasing number of messages?

I want to build a website that display changing text-messages.
The server gets the text-messages from a DB.
I wanted to grab a chunck of msgs, shufle them and send them to the client to present each of them. When the client is done with the current chunck he asks the server for the next chunck.
can some one help me with client side psudou-code?
I though to use asp.net ans JS but I'm newbie to JS.
I think (based on your question) you want to periodically check the server for messages ? this will require you to communcate between the client and the server. The best method for doing this is AJAX.
AJAX is a method of sending a query to the server and retrieving information back - you can then display the retrieved information to the user (the messages).
A good introduction to AJAX is here -> http://www.w3schools.com/ajax/ajax_intro.asp
To get the delay between requests you can use setInterval -> http://www.w3schools.com/jsref/met_win_setinterval.asp
Create a function in javascript to fetch and display the messages - then setup the setInterval function to call this method every x seconds / minutes as desired
It's not clear what you mean when you say 'when the client is done'. Do you mean a user physically asks for more messages by clicking on a button? Or is it that the user scrolls/clicks through the messages, and then the client-side software asks for more when they've all been seen?

WCF / ASP.NET - protected against misuse such as DOS

We currently host a lengthy form on our ASP.NET website, which makes use of a public facing facade WCF service to submit information over SSL into our network through a number of other facade services, etc.
We've experienced some issues with downtime on the service chain, and because of this some users have been very frustrated that they complete the lengthy form, only to find out after the fact that the service isn't up. Because of this, we are implementing a type of ping functionality on the form that will ping the service before the form is started, to ensure the service is up.
If the Ping() method is simply called during OnLoad of the form web page, there is potential for DOS attacks through for example a script that continually makes HTTP GET requests against the page.
My question is - From a conceptual level, what is the best way to ensure human interaction with the page while keeping it useable. For example, a CAPTCHA before the Ping() is called and form is started is way too intrusive even though it would be effective at ensuring the form is used properly. On the other hand simply allowing Ping() to fire OnLoad is far too risky for attacks.
One option I've considered is to have a button available to users which allows them to verify service availability and enable the form in one shot. This would at least be a balance between the two. I'm asking for your input on ideas for how best to balance this approach. Any asp.net, c#, or javascript/ajax based answers are fine.
Lastly - I also know there are flaws to this approach of checking service availability as there is no guarantee the service will be available by the time the form is filled out - but the decision has been made to use this approach so please keep your answers on point.
Thanks for the help and input in advance!
UPDATE 1:
In response to Josh's answer below - I should clarify that the form data submitted is sensitive and cannot be cached on the server or stored locally for later submission if the service fails. This is why it is very important to give the user a preemptive heads up. The issues we've had with the services are not intermittent so if the Ping() comes back true, there is an extremely good chance the user will not experience issues submitting the form a few minutes later.
UPDATE 2:
The Ping() Method is currently a server-side c# method, not javascript.
The public facing WCF service is IP-restricted to only allow requests from the public web server
Why don't you just call Ping() when the submit button is pressed and if the service doesn't respond then don't submit the form and show an error.
Something like this in jQuery. This assumses that Ping() returns true if the service is up, false otherwise:
$('#myformid').submit(function() {
var svcUp = Ping();
if(!svcUp)
alert("Sorry, there was an error submitting, please try again.");
return svcUp;
});
Unfortunately any public facing web service that has a low calling cost but high processing cost will be vulnerable to DOS attacks without some type of throttling.
Thankfully WCF has some useful settings for controlling throttling, take a look at MaxConcurrentCalls, MaxConcurrentInstances, and MaxConcurrentSessions
There is really no good solution on the client-side to prevent a DOS attack - I can create a script using your Ping js method that will call it a million times in a loop. You can prevent it on the server side though, by tracking calls per second form the same ip/session/user/otherclient-side identifier. If number of calls per second is over some reasonable limit, you temporarily ban that client.
You can look at http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx - scroll down to "Prevent Denial of Service (DOS) Attack" for an example
Call your function on page load and prior to the submit button. If you have any logging you are using you could insert into a log table for this particular aspx page view and include the IP address of the visitor. Set a threshold and if the IP makes more requests than what you required as proper usage, then put up some type of human-validation item.

Running server-side function as browser closes

Background: I'm creating a very simple chatroom-like ASP.NET page with C# Code-Behind. The current users/chat messages are displayed in Controls located within an AJAX Update Panel, and using a Timer - they pull information from a DB every few seconds.
I'm trying to find a simple way to handle setting a User's status to "Offline" when they exit their browser as opposed to hitting the "Logoff" button. The "Offline" status is currently just a 1 char (y/n) for IsOnline.
So far I have looked into window.onbeforeunload with Javascript, setting a hidden form variable with a function on this event -> Of course the trouble is, I'd still have to test this hidden form variable in my Code-Behind somewhere to do the final Server-Side DB Query, effectively setting the User offline.
I may be completely obfusticating this likely simple problem! and of course I'd appreciate any completely different alternative suggestions.
Thanks
I suspect you are barking up the wrong tree. Remember, it is possible for the user to suddenly lose their internet connection, their browser could crash, or switch off their computer using the big red switch. There will be cases where the server simply never hears from the browser again.
The best way to do this is with a "dead man's switch." Since you said that they are pulling information from the database every few seconds, use that opportunity to store (in the database) a timestamp for the last time you heard from a given client.
Every minute or so, on the server, do a query to find clients that have not polled for a couple of minutes, and set the user offline... all on the server.
Javascript cannot be reliable, because I can close my browser by abending it.
A more reliable method might be to send periodic "hi I'm still alive" messages from the browser to the server, and have the server change the status when it stops receiving these messages.
I can only agree with Joel here. There is no reliable way for you to know when the HTTP agent wants to terminate the conversation.

Categories

Resources