User closes the browser without logging out - asp.net-mvc-3

I am developing a social network in ASP.NET MVC 3. Every user has must have the ability to see connected people.
What is the best way to do this?
I added a flag in the table Contact in my database, and I set it to true when the user logs in and set it to false when he logs out.
But the problem with this solution is when the user closes the browser without logging out, he will still remain connected.

The only way to truly know that a user is currently connected is to maintain some sort of connection between the user and the server. Two options immediately come to mind:
Use javascript to periodically call your server using ajax. You would have a special endpoint on your server that would be used to update a "last connected time" status, and you would have a second endpoint for users to poll to see who is online.
Use a websocket to maintain a persistent connection with your server
Option 1 should be fairly easy to implement. The main thing to keep in mind that this will increase the amount of requests coming into your server, and you will have to plan accordingly in order handle the traffic this could generate. You will have some control over the amount of load on your server by configuring how often javascript timer calls back to your server.
Option 2 could be a little more involved if you did this without library support. Of course there are libraries out there such as SignalR that make this really easy to do. This also has an impact on the performance of your site since each user will be maintaining a persistent connection. The advantage with this approach is that it reduces the need for polling like option 1 does. If you use this approach it would also be very easy to push a message to user A that user B has gone offline.
I guess I should also mention a really easy 3rd option as well. If you feel like your site is pretty interactive, you could just track the last time they made a request to your site. This of course may not give you enough accuracy to determine whether a user is "connected".

Related

How to implement synchronization of browser-based online games when users refresh their browser

In implementing a browser-based simple game involving multiple users, I have the server save the game state at certain sync points (not time-based but event-specific). I identify each state by an integer.
When a user refreshes his browser, the server provides the latest state and restores the content in the browser. However, in those few seconds while the browser is loading the latest content after browser-refresh, the state could change again. I do not know how to handle this situation because sending the next state will again raise the same issue.
I want a seamless refresh so none of the other players are impacted when one user refreshes his browser (or for that matter leaves and comes back).
The implementation language is not relevant. I use websockets to communicate between the browser and the server. The server is the intermediary for all communication between users (I am not using WebRTC data channels). What is the best way to sync the application content in multiple browsers?
This is indeed a programming-based question though no code is provided.
Forget the fact that your client exists in a browser. Let's just talk about replication.
The usual approach in databases is to separate snapshots from Write Access Logging (WAL) logs. When you bring a new client up, you select a snapshot and transfer that. Then when the client is ready it asks for WAL logs from that snapshot forward. The same mechanism is used after crashes. The last available snapshot is loaded, then the WAL log is replayed, then the database comes up.
I would suggest the same strategy. This does require efficient storage of snapshots. Some kind of log. And some kind of replay mechanism. Which is a lot of easy to mess up code. If you can use something existing, that would be good.
The first thing that I looked into was using Emscripten to compile Redis to JS, and then try to use Redis' built-in asynchronous replication to replicate to your browser. That may be possible, but the fact that Redis is single-threaded and wants to be a client-server is probably a showstopper.
The next best option that I found is that you can use https://isomorphic-git.org/. Here is how that could build what you need. You simply maintain your current state in a git repository, and keep a WAL log of everything that you've done with it. When a client connects, it clones the repository. Once done it connects to the websocket, tells you what commit it is at, and you send it the WAL log from that point forward. Locally in the browser you run those git commands. If the client simply loses its connection and then rejoins, it can do a git pull, and then follow the same strategy.
This will be a bunch of work for you. But a lot less work than implementing everything from scratch.

Best way to initialize initial connection with a server for REST calls?

I've been building some apps that connect to a SQL backend. I use ajax calls to hit WebMethods, a WebAPI, etc.
I notice that the first initial call to the SQL backend retrieves the data fairly slow. I can only assume that this is because it must first negotiate credentials first before retrieving the data. It probably caches this somewhere, and thus, any calls made afterwards come back very fast.
I'm wondering if there's an ideal, or optimal way, to initialize this connection.
My thought was to make a simple GET call right when the page loads (grabbing something very small, like a single entry). I probably wouldn't be using the returned data in any useful way, other than to ensure that any calls afterwards come back faster.
Is this an okay way to approach fixing the initial delay? I'd love to hear how others handle this.
Cheers!
There are a number of reasons that your first call could be slower than subsequent ones
Depending on your server platform, code may be compiled when first executed
You may not have an active DB connection in your connection pool
The database may not have cached indices or data on the first call
Some VM platforms may take a while to allocate sufficient resources to your server if it has been idle for a while.
One way I deal with those types of issues on the server side is to add startup code to my web service that fetches data likely to be used by many callers when the service first initializes (e.g. lookup tables, user credential tables, etc).
If you only control the client, consider that you may well wish to monitor server health (I use the open source monitoring platform Zabbix. There are also many commercial web-based monitoring solutions). Exercising the server outside of end-user code is probably better than making an extra GET call from a page that an end user has loaded.

how to handle UI actions on front-end responsively while waiting for the processing in back-end?

Use a StackOverflow Q&A thread as an example - when you vote up, vote down, or favorite a question, you can see the UI quickly respond to that action with changes in the # of up-votes on the side.
How can we achieve that effect? If send every of such action to back-end for processing and use the returned response to update UI, you will see a slow update and feel the glitches. But if put some of the logic on the front-end, you will also need to take care of the fraud/abuse etc before reflecting the action on UI, i.e - before changing the # of up-votes, don't you need to make sure that's a valid click by an valid user first?
You make sure that a valid user is using the app before a user clicks on anything. This is done through authentication, and it must include various protection mechanisms against malicious users.
When a user clicks, a call is made to a server. In a properly architected app this call is lightweight, and the server responds very quickly. I don't know why you believe that "you will see a slow update and feel the glitches". Adding an upvote to the database should take a few hundred milliseconds at most (including the roundtrip from the client), especially if the commit is asynchronous or a memcache is used.
If a database update results in a need to do some complex operations, typically these operations are not done right away. For example, a cron job may run periodically to compute new rankings, etc., precisely because you do not want every user to wait. Alternatively, a task is created and put in a task queue to be executed when resources are available - again to make sure that a user does not wait.
In some apps a UI is updated immediately after the call to the server is made, before any response from a server arrives. You can do it when the consequences of a failed call are negligible. For example, if an upvote fails to be saved in the database, it's not a disaster, especially if it happens once in a million tries. Again, in a properly architected app calls fail extremely rarely.
This is a decision that an app developer needs to make. I would not update a UI before a server response if such an update may lead a user to believe that some other action is now possible. For example, if a user uploads a new photo, I would not show icons to edit or share this photo until I know that the photo is safely saved.

What's the recommended solution/technology to this use case?

I'm building a website which offers 1 on 1 coaching on various topics. The coaching is done over the web ( video call, document upload, stuff like this ), and one of the most important things is that the client pays by the minute. My problem is the following: how will I know when a coaching session ends ( so that I can correctly bill the customer )?
I'm planning to store the coaching session in the db roughly like this:
coach_id:integer
client_id:integer
created_at:datetime
updated_at:datetime
in_progress:boolean
At the session's end I will do a difference between updated_at and created_at, and get the length of the session.
Here are the potential problems I see:
coach loses internet access => in this case, the client will press a button on the website which will notify us that the session had a problem, and the session's updated_at will be updated, and in_progress will be set to false
client loses internet access => same workflow as if coach loses internet access
both lose internet access => this is the trickiest case. I am not sure how to notify the server that the session should be considered as finished. I am thinking of doing it via push, and have both the client's browser, and the coach's browser update the server every minute. Worst case scenario, the error would cause a difference of 1 minute to the bill, which is acceptable. The downside is that I think this could load the server a lot, and I don't know if this would still be a viable solution once we will have many users.
What do you think of this approach? In case it matters, the application will be built on Rails 3.2.
Why dont you look into HTML5 EventSource or WebSockets as possible means of detecting connectivity/loss of connection?
At least in .NET (and I would guess in all server environments) it is possible to see if the client is still connected (tcp wise). EventSource/WebSockets helps you to establish an always open connection (as opposed to request/response connection with a short period of being connected) that you can monitor if its still operational/open.
So essentialy the solution needs to be implemented at the websocket server.

Setup BOSH so that it allows for users to login without passwords for a long period of time?

I'm just wondering how one could set this up without the BOSH dying. I have the sid, rid, and everything but I was wondering how long i could automatically log people on for the time of lets say a cookie and how is this achieved.
Your answer depends on how long it takes for your BOSH session to timeout. It's usually 60 seconds until it throws away the session.
Just a note- you probably do not want to automatically log in a user, since the proper XMPP flow is not done. Here's a typical flow:
-> Login and establish a BOSH session.
-> Send Presence
---> Server sends a <presence/> packet to all entities in your roster, notifying them that you are available.
---> Server sends a presence probe to all of the entities in your roster's server, getting their current availability.
<- Presence packets come raining down on your session.
-> Request roster items
<- Server sends you a list of items in your roster.
With the approach of using the same session, you skip all of this initialization, which I assume is important to your application, as you will not get presence of any entities until they change their presence. Sending another <presence/> stanza will not send you the current presence of everyone in your roster. So... if that isn't important to you, go ahead and do it. I'm just providing some useful information before you go and implement the thing and find out that there are caveats to your solution.
What worked for us was to use localStorage, and automatically log them in via a "Save my password" button. That makes it simpler and less work. Also, it can be confusing when a user reloads the page and they get logged back in automatically, versus a user closing the page and coming back in 5 minutes to be greeted by the login page. It's just plain confusing.
Good luck!
You can do one of the following as per your need and convenience:
Auto detect about user login status via cookies. Do an http-pre-bind and issue new rid/sid to the user. This will generally be transparent to user on your page.
Instead of issuing new "sid" on every page refresh/reload which can be quite expensive under high traffic, you can pool the underlying xmpp tcp streams. Next time when a user need sid/rid to start again, these can be fetched from the connection manager pooling the sessions.

Resources