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

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?

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)

Run asynchronous operation in one controller method and get that operation's result in another

I have a long running operation you might read in couple of my another questions (for your reference here is first and second).
In the beginning of whole deal, project expose a form in which user should specify all necessary information about XML file and upload XML file itself. In that method all user input data caught and went to an WCF service that handles such king of files. Controller got only task id of such processing.
Then user got redirected to progress bar page and periodically retrieves status of task completeness, refreshes the progress bar.
So here is my issue comes. When processing of XML file if over, how can I get results back and show them to user?
I know that HTTP is stateless protocol but there is cookie mechanism that could help in this situation. Of course, I may just save processing results to some temporary place, like a static class in WCF server, but there is a high load on service, so it will eat all of supplied memory.
In other words, I would like to pass task to WCF service (using netNamedPipeBinding) and receive results back as fast as it really possible. I want to escape temporary saving result to some buffer and wait until client will gather it back.
As far as I go is using temporary buffer not on service side but at client's:
using (XmlProcessingServiceClient client = new XmlProcessingServiceClient())
{
client.AnalyzeXmlAsync(new Task { fileName = filePath, id = tid });
client.AnalyzeXmlCompleted += (sender, e) =>
{
System.Web.HttpContext.Current.Application.Lock();
// here is I just use single place for all clients. I know it is not right, it is just for illustrating purposes.
System.Web.HttpContext.Current.Application["Result"] = e;
System.Web.HttpContext.Current.Application.UnLock();
};
}
I suggest you to use a SignalR hub to address your problem. You have a way to call a method on the client directly to notify the operation completed. And this happen without having to deal with the actual infrastructure trouble there is in implementing such strategies. Plus SignalR plugs easily in an asp.net MVC application.
To be honest I didn't really get the part about the wcf server and stuff, but I think I can give you more of an abstract answer. To be sure:
You have a form with some fields + file upload
The user fills in the form and supplies an XML file
You send the XML file to an WFC services which procress it
Show in the mean time a progress bar which updates
After completion show the results
If this is not want you want or this is not what your question is about you can skip my answer, otherwise read on.
Before we begin: Step 3 is a bit ambiguous: It could mean that we send the data to the service and wait for it to return the result or that we send the data to the service and we donĀ“t wait for it to return the result.
Situation 1:
Create in a view the form with all the required fields
Create an action in your controller which handles the postback.
The action will send the data to the service and when the service returns the result, your action will render a view with the result.
On the submit button you add an javascript on click event. This will trigger an ajax call to some server side code which will return the progress.
The javascript shows some sort of status bar with the correct progress and repeats itself every x seconds
When the controller finishes it will show the result
Situation 2:
-
-
After sending the data to the service the controller shows a view with the progress bar.
We add an javascript event on document ready which checks the status of the xml file and updates a progressbar. (same as the onclick event in step 4 in situation 1)
When the progressbar reaches 100% it will redirect to a different page which shows the results
Does this answer your question?
Best regards,
BHD
netNamedPipeBinding will not work for cross-machine communication if this is what you have in mind.
If you want to host our service on IIS then you will need one of the bindings that use HTTP as their transport protocol. Have a look at the duplex services that allow both endpoints to send messages. This way the server can send messages to the client anytime it wishes to. You could created a callback interface for progress reporting. If the task is going to take a considerable amount of time to complete, then the overhead of the progress reporting through HTTP might be ok.
Also have a look at Building and Accessing Duplex Services if you want to use a duplex communication over HTTP with Silverlight (PollingDuplexHttpBinding).
Finally you could look for a Comet implementation for ASP.NET. In CodeProject you will at least a couple (CometAsync and PokeIn).
I'm not sure if this is the best solution but I was able to do something similar. This was the general setup:
Controller A initialized a new class with the parameters for the action to be performed and passed the user's session object
The new class called a method in a background thread which updated the user's session as it progressed
Controller B had json methods that when called by client side javascript, checked the user's session data and returned the latest progress.
This thread states that using the session object in such a way is bad but I'm sure you can do something similar with a thread safe storage method like sql or a temp file.

How to know if the other user is now writing a message in web chat website?

I am building a chat system in an ASP.Net MVC website, and I want the user see if the other chat user is now writing a message.
The same as it appear in gtalk or msn, when the other user start writing it says: "userA is writing ...." then it hide this message when the user stops.
What will be the concept behind this feature to implement on a website, and what I should know to build it the right way?
This is all done via AJAX
User1 sends a writing=true value to the server as soon as writing begins, and writing=false when message is submitted.
User2 polls the server every x seconds to see if(writing){display "User1 is writing a message"}
This is obviously two way, so User1 and User2 are both pushing and pulling the writing boolean from the server.
I'd suggest using jQuery and JSON for this process.
Look for an "on change" (or equivalent) for your edit text. Start a timer when it happens and send an ajax message to the chat server(s) to notify them. When the text is submitted or the timer runs out, clear the message.
Client-side, have a timer count to 500ms and a variable sentState set to false.
Whenever the client types something, reset that timer, the, if sentState is, send an AJAX request to the server indicating that the client is typing. Finally, set sentState to true.
If the timer reaches 500ms, send an AJAX request to the server indicating that the client is no longer typing and set sentState to false.

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