Users time tracking on websites/web application - c#

I have a requirement to track how much time the user spending time on web sites/web application. Its like a time tracking tool for websites, I have wpf application which will open the websites on IE/Chrome/Firefox. I need to track the how much time user works on the website.
Chrome and firefox provides the history which i can get from sqlite database that stores in the user system but IE doesn't provide any information about the history.
Is there a better way i can track all browser activity with the user spending time on each websites?

I have wpf application which will open the websites on
IE/Chrome/Firefox. I need to track the how much time user works on the
website
It's a very important Feature Request by many for web 2.0 applications. So, I write a detailed, working and simple solution on the subject here.
You are requesting a feature already created for this workflow. It's a plugin you can include in any website. It's none other than time-on-site tracking in timeonsite.js
Look at the following code (Use latest version; don't just copy/paste),
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/timeonsite/1.2.0/timeonsitetracker.js"></script>
<script>
var config = {
// track page by seconds. Default tracking is by milliseconds
trackBy: 'seconds',
trackHistoryChange: true, //Single-page React/Angular app
callback: function(data) { /* callback denotes your data tracking is real-time */
console.log(data);
var endPointUrl = 'http://example.com' //Replace with your actual backend API URL http://localhost/tos
if (data && data.trackingType) {
if (data.trackingType == 'tos') {
if (Tos.verifyData(data) != 'valid') {
console.log('Data abolished!');
return;
}
}
// make use of sendBeacon if this API is supported by your browser.
if (navigator && typeof navigator.sendBeacon === 'function') {
data.trasferredWith = 'sendBeacon';
var blob = new Blob([JSON.stringify(data)], {type : 'application/json'});
navigator.sendBeacon(endPointUrl, blob);
}
}
}
};
var Tos;
if (TimeOnSiteTracker) {
Tos = new TimeOnSiteTracker(config);
}
</script>
</head>
Then, when you refresh, reload or navigate the React app page,
You'll see following object directly saved into your table/printed in browser console. Select "persist" in logs,
{
TOSId: 1129620185532,
TOSSessionKey: "14802525481391382263",
TOSUserId: "anonymous",
title: "Test application - Home page",
URL: "http://nature-blogs/pages/home.php"
entryTime: "2021-11-27 13:15:48.663",
currentTime: "2021-11-27 13:17:31.663",
timeOnPage: 103,
timeOnSite: 103,
timeOnPageTrackedBy: "second",
timeOnPageByDuration: "0d 00h 01m 43s",
timeOnSiteByDuration: "0d 00h 01m 43s",
trackingType: "tos",
}
As you can see, the actions
"entryTime" is captured
"exitTime" is captured in seconds/milliseconds depending upon configuration
"type:time_on_site" is captured
"timeOnPage" is captured // individual page time
"timeOnSite" is captured // session overall page time
What else you need? Since it's stored in SQL DB table, you can do analysis/reporting queries yourself. This works in any RDBMS DB smoothly.
On top of it, 1.Minimize tab, 2.Inactive tab and 3.Switch tab's idle time are all computed and ignored automatically by the tracker itself.
The only thing to note in configuration part is,
trackHistoryChange: true
If the page routing depends on Location Hash or also known as single-page app, include this setting. On the other hand if your web application is a normal page like Wikipedia, avoid setting this line. You are done. For showing the real-time stay time on screen, check this SO post. It's using Jquery to show the results. You can customize it for your React app.
This tracker can be plugged-in in any library VueJs, React, Angular, Jquery, MooTools etc. since it's plain vanilla JS library.
Let me know if you need more input on the subject. I can assist you on this.

Related

calling another http request upon changing page

I'm working with windows phone apps and I'm using here rest places api for my data and i retrieving data as json that give me information about location nearby like this
position: [ 37.77704 , -122.39494 ]
distance: 1241
title: Caltrain-San Francisco
averageRating: 0.0
category: { Public transport }
icon: http://download.vcdn.nokia.com/p/d/places2/icons/categories/11.icon
vicinity: 700 4th St<br/>San Francisco, CA 94107
having: [ ]
type: urn:nlp-types:place
href: http://demo.places.nlp.nokia.com/places/v1/places/8409q8yy-a7395cccbfc4474ba469f3ddc03e041b;context=Zmxvdy1pZD00OWQxZDY0Zi0zODc5LTVlNDAtOWY4ZC04ZGFmNWMyMGZhZDFfMTM4OTg4NDQxMzUxNV8wXzM1MjkmcmFuaz0w?app_id=lp3VaO8uhOFe0akZ4J1m&app_code=JwL7MNaSarML92oqEDshAg
id: 8409q8yy-a7395cccbfc4474ba469f3ddc03e041b
and i notice that if i open
href: http://demo.places.nlp.nokia.com/places/v1/places/8409q8yy-a7395cccbfc4474ba469f3ddc03e041b;context=Zmxvdy1pZD00OWQxZDY0Zi0zODc5LTVlNDAtOWY4ZC04ZGFmNWMyMGZhZDFfMTM4OTg4NDQxMzUxNV8wXzM1MjkmcmFuaz0w?app_id=lp3VaO8uhOFe0akZ4J1m&app_code=JwL7MNaSarML92oqEDshAg
i will go into other page that contain much detailed information about that location, so how can i get all of this data?the general and detailed data from that href
method that i using to get general data is using this
WebClient client = new WebClient();
Uri uri = new Uri(transportURL1 + latitude + "%2C" + longitude + transportURL2, UriKind.Absolute);
client.DownloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
RootObject result = JsonConvert.DeserializeObject<RootObject>(e.Result);
hereRestProperty = new ObservableCollection<Item>(result.results.items);
}
else
{
MessageBox.Show(e.Error.ToString());
}
};
client.DownloadStringAsync(uri);
so my app scenario is mainpage showing general location data and when I tap one of the location data it will navigate to detailpage that contain information from that href
how to do that?
edit: my work around is getting href and using that href to calling http request but i have no idea how to do all that...
edit2: after looking around I come up with idea of having mainpage with list of general information and if I click into one of the item in list it will navigate me to detailpage that will request from that href but i just don't know how to execute that in mvvm aproach...
If it is safe to assume that you are trying to add value to your app by adding a places feature, I would suggest that for Windows Phone 8 you would be better off launching HERE Maps directly using the HERE Maps Launchers API
For example, if your app is about hiking trails it would make sense to add a feature for finding details of places to eat or stay near that hiking trail - but you wouldn't need to create your own code to request, format and display the in-depth places data, just fire up the Maps app already on the device (passing in the href from the initial REST request if necessary). The advantage of doing this is threefold, firstly you can add this feature in four lines of code, secondly the user is presented with the places information in a familiar format, and finally information is retrieved from the device itself which alleviates the need to make additional HTTP requests.
One or more of the following tasks may be useful:
ExploremapsShowPlaceTask allows you to start the Maps application with the map centered to a place shown in the map.
ExploremapsSearchPlacesTask allows you to start the Maps application with the search view.
ExploremapsExplorePlacesTask allows you to start the Maps application where the nearby places of interest are shown.
PlacesShowDetailsByLocationTask allows you to start the Maps application with the places view for the selected place.
PlacesShowDetailsByIdHrefTask allows you to start the Maps application with the places view for the selected place.
Note that if HERE Maps is not installed on the Windows Phone 8 device, the user will be directed to download it for free from the app store.

Automated system for opening other website links in new window/tab

I have a website, in which when user clicks a link it opens up in the same window if it is of my website's page, else in new window if domain is different. But I am doing this manually like this:
Open Link
checkdomain() checks the domain name of the link and returns true if it's of my website else false. I used the code from [ HERE ] for this purpose.
My question is: Is there any efficient and client side way available for checking link domains and open up them in new windows/tab if of another website(domain)? Like a JavaScript solution will be better, but then again JavaScript can be disabled by user. So, is there any other solution? Even JS solution will be great. Ignoring the disabling by user.
Somewhere on the page, or in an external JS file:
function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href")
&& anchor.getAttribute("rel")
&& anchor.getAttribute("rel").indexOf("external") >= 0)
anchor.target = "_blank";
}
}
window.onload = function() {
externalLinks();
};
Then, any external links just need to have rel="external" in the markup. For example:
Click here!
The main advantages of this approach is that you're not going to cause any validation errors, even with an XHTML Strict doctype. Users are also able to easily prevent links opening in new windows by simply disabling JS.
If you need the decision of external/internal to be made automatically (and client-side), you can alter the logic of externalLinks to base the decision on the href attribute rather than the rel attribute. Of course, if you've already got the external/internal logic functioning in your codebehind, I would recommend using that information to render the anchor with the appropriate semantics (with rel), rather than re-writing almost identical code in your client-side JS.
Try comparing your link url's host part (www.wrangle.in) with following in you function logic.
string currentURL = HttpContext.Current.Request.Url.Host;
I do not recommend to compare the name (i.e http or https), you can split using substring function.
For Client side
var homeURL = document.location.hostname;
$('a').each(function() {
if ( $(this+'[href*='+homeURL+']')) {
$(this).attr('target','_self');
}else{
$(this).attr('target','_blank');
} });
This link may help you to understand Url Parts.

How to get data from a client on load?

I'm aware that data can be passed in through the URL, like "example.com/thing?id=1234", or it can be passed in through a form and a "submit" button, but neither of these methods will work for me.
I need to get a fairly large xml string/file. I need to parse it and get the data from it before I can even display my page.
How can I get this on page load? Does the client have to send a http request? Or submit the xml as a string to a hidden form?
Edit with background info:
I am creating a widget that will appear in my customer's application, embedded using C# WebBrowser control, but will be hosted on my server. The web app needs to pass some data (including a token for client validation) to my widget via xml, and this needs to be loaded in first thing when my widget starts up.
ASP.NET MVC 4 works great with jQuery and aJax posts. I have accomplished this goal many times by taking advantage of this.
jQuery:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "/{controller}/{action}/",
data: { clientToken: '{token}', foo: 'bar',
success: function (data, text) {
//APPEND YOUR PAGE WITH YOUR PARSED XML DATA
//NOTE: 'data' WILL CONTAIN YOUR RETURNED RESULT
}
});
});
MVC Controller:
[HttpPost]
public JsonResult jqGetXML(string clientToken, string foo)
{
JsonResult jqResult = new JsonResult();
//GET YOUR XML DATA AND DO YOUR WORK
jqResult.Data = //WHATEVER YOU WANT TO RETURN;
return jqResult;
}
Note: This example returns Json data (easier to work with IMO), not XML. It also assumes that the XML data is not coming from the client but is stored server-side.
EDIT: Here is a link to jQuery's Ajax documentation,
http://api.jquery.com/jQuery.ajax/
Assuming you're using ASP.NET, since you say it's generated by another page, just stick the XML in the Session state.
Another approach, not sure if it helps in your situation.
If you share the second level domain name on your two sites (i.e. .....sitename.com ) then another potential way to share data is you could have them assert a cookie at this 2nd level with the token and xml data in it. You'll then be provided with this cookie.
I've only done this to share authentication details, you need to share machine keys at a minimum to support this (assuming .Net here...).
You won't be able to automatically upload a file from the client to the server - at least not via a browser using html/js/httprequests. The browser simply will not allow this.
Imagine the security implications if browsers allowed you to silently upload a file from the clients local machine without their knowledge.
Sample solution:
Background process imports xml file and parses it. The background process knows it is for customer YYY and updates their information so it know the xml file has been processed.
A visitor goes to the customer's web application where the widget is embedded. In the markup of the widget the customer token has been added. This could be in JavaScript, Flash, iFrame, etc.
When the widget loads, it makes a request to you app which then checks to see if the file was parsed for the provided customer (YYY) if it has, then show the page/widget.
If the XML is being served via HTTP you can use Liqn to parse the data.
Ex.
public partial class Sample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string url = "http://news.yahoo.com/rss/";
var el = XElement.Load(url).Elements("channel");
StringBuilder output = new StringBuilder();
foreach (var c in el.Elements())
{
switch (c.Name.LocalName.ToLower())
{
case "title":
output.Append(c.Value);
output.Append("<br />");
break;
}
}
this.Label1.Text = output.ToString();
}
}
It is not exactly clear what the application is and what kind of options you have, and what kind of control over web server you have.
If you are the owner of the web server/application your options are way wider. You can first send a file to web-server with HTTP POST or PUT, including a random token, and then use the same token for GET with token in the query string
or use other options, applicable to third party-owned websites
if you are trying to consume some auth api, learn more about it. since you are hosting web browser control, you have plenty of options to script it. including loading whatever form, setting textarea or hidden field text with your xml and then simulating a submit button click. you can then respond to any redirects and html responses.
you can also inject javascript inside the page that would send it to server with ajax request.
the choice heavily depends on the interaction model.
if you need better advice, it would be most helpful if you provided sample/simplified url/url pattern, form content, and sequence of events that is expected from you from code/api/sdk perspective. they are usually quite friendly.
There are limited number of ways to pass data between pages. Personally for this I would keep in session during the generating page and clear it when it is retrieved in the required page.
If it is generated server side then there is no reason to retrieve it from client side.
http://msdn.microsoft.com/en-us/library/6c3yckfw(v=vs.100).aspx
Create a webservice that your C# app can POST the XML to and get back HTML in response. Load this HTML string into the WebBrowser control rather than pointing the control to a URL.

Facebook "fan gate" with C#/asp.net

The problem is that 1) Facebook seems so fluid with how it allows developers to interact with it (FBML, iFrame, different versions of SDKs) and 2) Everything I find is either PHP or Javascript and I have NO experience with those. What I am trying to do seems sooo simple, and I can't believe there isn't an easy way to do this.
What I have:
I used Visual Studio 2010 to create a simple web application (asp.net/C#) that asks the user for some info (first name, last name, email, etc.). I have a button on there called "Submit" that, when clicked, saves the entered data into a database. I have this hosted on GoDaddy (I know, I know...heh) and it works just fine. No problem here.
I created a "Facebook App" that uses the iFrame thingy so that basically I have a new tab on Facebook that displays my web app mentioned above. This works fine too. The tab is there, the web app is there, and users can enter the data and it is saved to the database. No problem here.
What I WANT:
I want the web app (the thing displayed by the facebook app) to only show the data entry part if the user currently "likes" the facebook entity. I DO NOT want to have to ask permission. I just want to know if they are a fan of the company's facebook "page" that has this app. So I need two things here, shown in my pseudo code below:
Part 1 (check if user is already a fan):
If (user is fan)
{
Show data entry area (unhide it)
}
else
{
Show "Click the like button to see more options"
}
Part 2 (listen for "like" event)
WhenLikeButtonPressed()
{
Show data entry area (unhide it)
}
I've seen stuff about "visible to connection", C# sdk, edge.create, etc. but I just can't make heads or tails of it. I don't mind putting in Javascript or PHP if someone could please give me exact, "Fan Gate for Dummies" steps. Please, I'm going crazy over here :-(
The key is is the signed_request that Facebook posts to your app when the user accesses the page. It contains the data on whether or not the user likes the page. You shouldn't need to worry about catching edge events on an actual tab FB page as it get's reloaded when the user likes/unlikes the page.
You'll need to decode the signed request with your app secret to get the like info. There are examples provided for PHP but I'm sure with a little google help you can find decode info for the signed_request for asp.net/c#.
Here's the php decode for reference:
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
and the link https://developers.facebook.com/docs/authentication/signed_request/ the like info will be contained in the page variable

How to do live update on section of page?

I need to refresh sections of my page to update when there is new data! what do i do? use jquery?
examples:
Yes, jQuery's great for this. Look into these methods:
http://api.jquery.com/category/ajax/
jQuery is usually not needed for basic AJAX. A simple example could be as follows:
liveSection = document.getElementById('latest-news');
request = new XMLHttpRequest;
request.open('GET', '/news-ajax', true);
request.send(null);
request.addEventListener('readystatechange', function() {
if (request.readyState == 4 && request.status == 200)
liveSection.innerHTML = request.responseText;
}, false);
If you're using Asp.NET, why not use an UpdatePanel? It's simple and reliable.
Edit
I just re-read your question and it looks (based on how you worded it) that you want to update a user's web page when the data changes on the server. I just want to make sure you understand that in a web app, the server can't trigger the browser to do anything. The server can only respond to browser requests, so you'll need to have the browser poll the server periodically.
I've created a simple example (using jQuery) to help you understand the breakdown of the things that will need to happen, which are:
1 - Periodically polling the server (via ajax) using Javascript's setTimeout to check that what is loaded into the browser is the latest content. We can achieve this by fetching the latest item ID or whatever and comparing it to a variable, which was initialised when the page first loaded.
2 - If the item ID does not match (a bit of an oversimplification) then we can assume that there has been an update, so we replace the content of some element with some content from some page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function getLatestStuff() {
// fetch the output from a context which gives us the latest id
$.get("isthereanupdate.aspx", function(response) {
// we have the response, now compare to the stored value
if(resp != lastItemId) {
// it's different, so update the variable and grab the latest content
lastItemId = response;
$("#latestStuffDiv").load("updates.aspx");
}
});
}
$(document).ready(function() {
// the value which initializes this comes from the server
var lastItemId = 7;
setTimeout(getLatestStuff, 10000);
});
</script>
If you want to update when there is new data, you should look into comet or pubsubhubbub. jQuery can help you display the data in a pretty way, but you'll need to write stuff on the serverside to send the data.

Categories

Resources