ASP Notification Mechanism - c#

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.

Related

real time server to client communication asp.net 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.

subscribing takes too long for users to wait on webpage for confirmation... solutions?

On our .NET 3.5 website in c# a user clicks submit on our webpage, they are subscribed by email address to our reports. Unfortunately, this action takes about 5 minutes and the user has to sit and wait for confirmation. What I would like to do is change it so that when they click submit, they get a pop up that says they will be notified by email when their subscription goes through, meanwhile i would queue up the subscribe action somewhere else on the server so that it doesnt exist in the web code. Can you give me some ways to do this? The basic idea is that I want to split into two different lines of execution where one will allow them to still browse our website and the other will subscribe them. I was thinking split into a new thread but I think that the web code would still have to wait for that thread to finish before they could do anything else. I'm looking for ideas, preferably something that can run on the same server. thanks!
There's many options, but the basic approach will be to decouple the site from the provider. Instead you'll write out a record saying "User X is waiting to subscribe", a seperate process will then read the record and perform the actual subscription, while marking the record as "in-progress". Once the process has complete the record will again be updated with the completed information.
You can achieve this with databases, message queues, or other approaches. But fundamentally your site will only be responsible for creating the record and checking it's status--the actual interaction with the provider will be handled separately.
If you have something that takes this long and you want to true and ensure the action goes through, then your best bet is going to be to queue it up.
Basically, when they submit the request, store that in a database table and let them move on. Meanwhile, have another process that monitors that table to process the requests. When they come in just have this second process send the request on to the part that takes 5 minutes to complete.
Once it finishes, send them a "welcome to such and such email list" message. That will serve as their confirmation that it worked.
Jeff Atwood blogged on a relevant topic here a while back. Since you are using c#, I assume you're using ASP.NET and can take advantage of the cache mechanisms to kick off a periodic worker job. On the user's request, you can persist details of the subscription to some data store. In that job, you can examine the queue to determine what subscriptions need to be created and then execute them.
https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/

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?

Session Variable being created and access before long process?

I have a page that executes a long process, parsing over 6 million rows from several csv files into my database.
Question is just as when the user clicks "GO" to start processing and parsing 6 million rows I would like to set a Session Variable that is immediately available to the rest of my web site application so that any user of the web site knows that a user with a unique ID number has started parsing files without having to wait until the end of the 6 million rows processed?
Also with jQuery and JSON, I'd like to get feedback on a webpage as to which csv file is being processed and how many rows have been processed.
There could be other people parsing files at the same time, how could I track all of this and stop any mix up etc with other users even though there is no login or user authentication on the site?
I'm developing in C# with .NET 4.0 Entity Framework 4.0, jQuery, and MS SQL 2008 R2.
I was thinking of using Session Variables however in my static [WebMethod] for my jQuery JSON calls I am not able to pull back my Session unless I'm using HttpContext.Current.Session but I am not sure how if this solution would work?
Any guidance or ideas would be mostly appreciated.
Thanks
First of all: Session variables are not supposed to be seen for any user everywhere.
when some client connects to the server, there is a session made for them by the server, and next time the same user requests (within the expiration time of the session), the session (and it's variables) are usable.
You can use a static class for this if you intend to.
for example
public static class MyApplicationStateBag
{
public static Dictionary<string,object> Objects {get; private set;}
}
and for your progress report. you can use a asp:Timer to check the progress percentage every second or two.
here is a sample code that I have written for asp:Timer within an UpdatePanel:
Writing a code trigger for the updatepanel.
I suggest you use a Guid for identifying the current progress as the key to your state bag.
The correct way of doing this is via services, for example WCF services. You don't want to put immense load on the web server, which is not supposed to do that.
The usual scenario:
User clicks on GO button
Web server creates a job and starts this job on a separate WCF service
Each job has ID and metadata (status, start time, etc.) that is persisted to the storage
Web server returns response with job ID to the user
User, via AJAX (JQuery) queries the job in the storage, once completed you can retrieve results
You can also save Job ID to the session
P.S. it's not a direct answer to your question, but I hope it helps

ASP.NET - Comet Pushing messages from server to all clients

I'm making an application with server sided variables that change every second. Every second those new variable need to be shown at all the clients that have the webpage open.
Now most people told me to go with comet because I need to push/pull the data every second, now I've got a few questions:
What would be a better solution looking at the fact that I need the new data EVERY SECOND, pulling from the client or pushing with the server?
Also the item ID's that are on the server side (with the variable's that ID got) can change and when the client refreshes the page he needs to get the oldest (and living) ID's. This would mean that my jquery/javascript on the client side must know which ID's he got on the page, what is best way to do this?
Last thing is that I can't find a good (not to expensive) comet library/api for asp.net (C#). Anyone ever used a comet library with good results? We're looking at a site that should be able to have 2000 comet connections at every moment.
There is a SendToAll function in PokeIn ASP.NET ajax library.
WebSync by Frozen Mountain is a full-fledged scalable comet server for IIS and ASP.NET. It integrates seamlessly into your application stack to support real-time data communications with thousands of clients per server node.
Check it out, there's a Community edition freely available.
What would be a better solution
looking at the fact that I need the
new data EVERY SECOND, pulling from
the client or pushing with the server?
I don't think it doesn't matter that much, as the time between requests and the time new data will be available is rather short. I would just instantiate a new XMLHttpRequest at the client after the previous one succeeded. You could send the server the last received data (if not too big) so it can compare that data with the current one available on the server and only send something back when new data is available.
Also the item ID's that are on the
server side (with the variable's that
ID got) can change and when the client
refreshes the page he needs to get the
oldest (and living) ID's. This would
mean that my jquery/javascript on the
client side must know which ID's he
got on the page, what is best way to
do this?
I'm not totally sure I understand what you mean, but if I'm right you can just store every name/value pair in an object. When a new variable arrives at the client, it doesn't overwrite existing data; when a certain variable is already present, it is updated with the latest value. It could look like:
{ first_variable: 345,
second_one: "foo",
and_the_third: ["I", "am", "an", "array,", "hooray!"]
}
and when a new state of second_one arrives, e.g. "bar", the object is updated to:
{ first_variable: 345,
second_one: "bar",
and_the_third: ["I", "am", "an", "array,", "hooray!"]
}
Last thing is that I can't find a good
(not to expensive) comet library/api
for asp.net (C#). Anyone ever used a
comet library with good results?
I don't have any experience with ASP.NET, but do you need such a library for this? Can't you just program the server-side code yourself, which, as I said, leaves the connection open and periodically (continually) compares the current state with the previous sent state?
UPDATE: To show it's not that difficult to keep a connection open at the server side, I'll show you a long-polling simulation I wrote in PHP:
<?php
sleep(5);
?>
<b>OK!</b>
Instead of letting the process sleep a few seconds, you can easily test for changes of the state in a loop. And instead of sending an arbitrary HTML element, you can send the data back, e.g. in JSON notation. I can't imagine it would be that hard to do this in ASP.NET/C#.

Categories

Resources