Recently, I was tasked with implementing a client side javascript based timeout routine. By the time I was done, it worked beautifully until we started up multiple browsers on the same site. If one browser was in the background, it was oblivious to the activity in the other browser window. This can be accomplished by the famed Ctrl-N. Browser copy 1 would count down, display the warning message and then log everyone out which would be quite a shock to the user who was in the other browser at the time. This is because the timeout hinged on a javascript variable, which is not shared between browser sessions. So, in order to fix this, I went the cookie route. This post is to detail how I solved this problem. The only code presented here is the code to implement and check the cookie and some basic UI.

First, I will deal with the cookies. I created (ok, borrowed) some code for the cookies.

The text box "secondsLeft" is used for debugging to see the status of our timer at any given point. The button reset again, helps us test our code. The idea behind the reset is that we want to reset the timer any time the user interacts with the page. Again, I am using JQuery here so let's look at how the page is setup.

When the document loads, we will setup each of the input devices to renew the session whenever they receive input or even a mouse move event. This let's our routine know that the user is alive and well. You can tailor this to suit your needs. The next thing we do is create the JQuery UI dialog. Note the close button on the dialog also Renews the session. Finally we call renew session to set the point from which the ticker can operate and then start up the ticker to 'CheckSession' every second or so. Again, you can tailor this for your needs. Now, let's look at the CheckSession and RenewSession functions.

// This function sets the renewal cookie to the current time, //as a result, any window basing their// timeout on this cookie should also get reset.
function RenewSession()
{
// This will record the getTime value of the date when the // function is invoked. Draws a line in the sand.
setCookieWithExpire(renewalVars.secondsLeftCookieName,
(new Date()).getTime() / 1000, 1);
}
// This function is what fires every so often to check the status of the timeout,// display the window if necessary and if no action is taken, transfer the user to// the logout screen.
function CheckSession()
{
// This will get the elapsed seconds since we "drew the line in the sand" // and then subtract it from the timeout value to get the seconds remaining.var savedSeconds = getCookie(renewalVars.secondsLeftCookieName);
var elapsedSeconds = ((new Date()).getTime() / 1000) - savedSeconds;
var secondsLeft = renewalVars.timeoutValue - elapsedSeconds;
$("#TimeoutMessage").html('You Currently Have ' + secondsLeft.toFixed(0)
+ ' second(s) left.<br/>Press OK to not be logged out.');
$("#txtSecondsLeft").val(secondsLeft.toFixed(0));
// This is the case where we are less than the warning but haven't shown the box.if (secondsLeft <= renewalVars.warningValue && !renewalVars.confirmDialogShowing)
ConfirmSessionTimeout();
// This is the case where we are showing the box, but our timeout // is reset, perhaps by another browser instance. (edge case)if (secondsLeft > renewalVars.warningValue && renewalVars.confirmDialogShowing)
{
RenewSession();
renewalVars.confirmDialogShowing = false;
renewalVars.TimeoutDialog.dialog("close");
}
// Now, if nothing was done and the seconds left go to 0, then we // log the user out (which effectively logs all sessions out)if (secondsLeft <= 0)
{
// This is to prevent the countdown from continuing if the // browser is a bit slow to respond.
clearInterval(renewalVars.intervalID);
window.location.href = "http://www.google.com";
}
}

The RenewSession simply takes the current date and stores it in the cookie. Whenever the timer fires, the CheckSession will do the following.

go get the last cookie saved. This can be by this browser or another browser session.

Determine how many seconds have elapsed.

Determine how many seconds we have left.

Update message

Next bit will check to see if we are below our threshold and the dialog has not been shown, then show the dialog.

If we are above our threshold and the dialog is shown, hide the dialog. This is the case when another browser session renews.

Finally, if our timer has fallen to zero or below, we can stop the timer and then invoke whatever function you wish. In this case, I have simply transferred to Google. You can invoke your logout controller/action or whatever you wish to do.

We only have a little bit more to wrap up so let's show that code.

// This structure will hold some of the data needed to manage the timeout.var renewalVars =
{
// This is the cookie that will store the exact time a refresh happened.
secondsLeftCookieName: "Timeout.ResetSnapshot",
// Amount of time in seconds till the timeout happens.
timeoutValue: 12,
// Amount in seconds when the dialog will appear. This is // X seconds before the timer runs out.
warningValue: 10,
// Flag that indicates whether or not the Confirmation Dialog is showing.
confirmDialogShowing: false,
// Stores the interval ID so the timer can be shut off before exiting.
intervalID: null,
// Dialog Variable itself.
TimeoutDialog: null
}
// This function shows a dialog that will display to the user that their // session is about to time out.
function ConfirmSessionTimeout()
{
// Show the window.
renewalVars.TimeoutDialog.dialog("open");
// Indicate to the rest of the program that the dialog is shown.
renewalVars.confirmDialogShowing = true;
}

The renewalVars structure is just a handy place to keep the variables that I need. Confirm session timeout is responsible for invoking and showing the dialog and setting the confirmDialogShowing variable to true.

If you would like to see the entire page working, you can go get it here.

In finishing, if you try and get this to work on your local development machine, it will likely not work. The reason is, in order to share cookies, there must be at least one "." in the domain name. For example, www.IgnorantTillProvenGuilty.com has dots in the name, localhost does not. In order to get around this, add the following to your hosts file.

127.0.0.1 dev.localhost.com

Once you do that, then you can refer to your site with this alias and it should work. Of course, once deployed to real domain, no worries. This is a good Stack Overflow article with more details on this.

This post is to highlight a fairly useful script I came up with to break down differences between dates. I was originally trying to use DATEDIFF to do my work but there is something a little quirky about DATEDIFF that made my goal tougher to reach. In short, what I was trying to do was to get the "Quantity" of time between two dates. For example, say I have the following two dates:

March 1, 2015 and April 3, 2015

If I were to ask SQL what the difference between these two dates were in Years, I would get a zero.

Print DateDiff(yy, 'March 1, 2015','April 3, 2015')

Results in 0. This is totally expected. If I were to ask for the months in between, then I get the following.

Print DateDiff(mm, 'March 1, 2015','April 3, 2015')

Results in 1. Eureka, he cried, I have found my functions. I can just do a little math in the background and presto, I can build a string that is much more readable. However, during this development, I found the an interesting quirk. Suppose I were to run this.

Print DateDiff(yy, 'December 1, 2014','April 3, 2015')

Results in 1. Wait a friggin second. I know that there is not 1 full year between 1/1/2014 and 4/3/2015. That's only about 4 months. So I did a little digging and found this.

It basically states the following. "datepart: Is the part of startdate and enddate that specifies the type of boundary crossed...." What the.... So according to TSQL if I ask for the difference between 12/30/2014 at 11:59 PM and 1/1/2015 at 12:01, it is going to tell me 1 Year because we happened to cross a boundary. Correct me if I am wrong, but this is bit misleading. I want the Difference in the date (Hence the name DateDiff). So back to my problem, I want to know how many years, months, days, hourse, minutes, etc... have passed between the two dates. If I can't use DateDiff to get the actual difference in the dates, then how do I do it? What I came up with was to use the DateAdd function. Here is how it works...

Suppose I have two dates and I want to know if there is a year between them. I can Add a year to date one and check to see if has surpassed date 2. If it has (or it is equal), then I know there is at least one year between them. If not, then I know there is less than a year between them. So I can create a User Function that takes two dates, and then using While loops, I can move the original date forward until the "Next" advance would move past the second date. Once I do that, I switch to the next unit of time. I keep going until I have reached the precision I want. I can then format the output any way I like and there you have it, a more readable listing of the time passed between two dates, regardless of boundaries. So without further delay, here is the function I wrote.

Have you ever wanted to know how much time a process takes in your code? I was recently working on a project where I wanted to compare different techniques of file access and wast trying to remove bottlenecks in the process. Now of course you have to be very careful with any type of observer in your code as the observer can have adverse effects and wind up reporting back inaccurate information. As I was just trying to get a relative feel for how long things were taking, I didn't worry too much. Now on with the class.

What I decided to do was to create a timing class which would initialize on creation and record the system time. The idea is that I want to profile a particular portion of code, then log the results. Here is the class and we can talk about each part and why.

At the top of the class, you have two methods for identifying the instance. You can set the name of the instance so that when the results are logged, you will know what it is you are profiling. I have also included an optional Guid for further identification but haven't used it in this instance. Moving on, you have two private fields called _startTime and log. _startTime records when the class is instantiated and the log is the instance of log4net we are using. Of course, you can change the code to use your own logging mechanism. Taking a look at the constructor, we see that it sets the name of the instance, generates a new Guid and then captures the system date and time through DateTime.Now. So far, we have setup the class, now let's get into the meat of it which happens in the Dispose method. You may have noticed that the ProcessTimer class implements the IDisposable interface. This allows us to participate in a using block and have the Dispose method called upon leaving the using block. I will demonstrate this later. The first thing we do in the Dispose method is to capture a timespan between the current datetime and the datetime that we captured earlier. I could use the TimeSpan.TotalMilliseconds method, log that and be done but I wanted to get a little more fancy. The math that follows breaks the millisecond count up into Hours, Minutes, Seconds and Milliseconds. For Example, if the result is 23,568 milliseconds, wouldn't it be nicer if it read 23 secs, 568 MSecs. That is not that big of an issue but what happens when we get into longer processes that take perhaps minutes or even hours. For example, how long is 4,567,213 milliseconds. It is not obvious right at first but when you break it down, you get 12 Hours, 4 Minutes, 7 seconds and 213 milliseconds. That to me seems more useful. So the way that this is calculated is to make a determination as to first how many hours are represented by the milliseconds by doing integer division by 360,000. Take the number of hours, * 360,000 and subtract that from the original milliseconds. YOu can then do the same with minutes (using 60000) and then seconds (using 1000) and you should get a nice breakdown. Step through the code to see this in action. Now, on to how you would use this in code. It's very simple.

As you can see, anything that needs to be timed, can simply be wrapped with a using statement. The constructor will get called at the top and the Dispose is called automatically when you leave the block. Anything you want to time, just wrap it in the process timer and it will be called and logged. Finally, let's see what the log looks like. This is the sample line from the log4net file.

This is a paper I wrote for one of my testing requirements. I had published it on my site but thought I would share it here as well.

Introduction Most every martial art that I have had the pleasure of practicing or at least observing includes an aspect of training which involves sequences of movements designed to practice just that; movement. In my karate study, one such exercise is called a kata. Kata, in Japanese karate is a series of movements that mimic actual techniques and build a scenario around an imaginary confrontation which is always (conveniently) won by the performer of the kata. There are many papers and writings on the benefits of kata, so it wouldn't be appropriate in this paper to go over all that. Instead, this paper is about a similar concept that we find in our Aikido practice, Ki No Taiso.

Ki No Taiso, or just taiso, is a collection of exercises that we perform at the beginning of every class. According to AikidoJournal.Com, taiso is defined as “Aiki exercises; refers to various movements and blending exercises practiced before training in techniques; designed to teach the principle of aiki.” The taiso that most people practice today originate with Koichi Tohei Sensei, one of O’Sensei’s senior students. He was one of the first to see that O’Sensei was not only teaching techniques, but that there were principles behind these techniques. Without a good understanding of the principles, the techniques would never make much sense. To this end, he developed many methods for teaching the four basic principles of ki, and one of the exercises he used was taiso.

Not all aikido schools perform these exercises, and in my opinion, they are missing out on a very important aspect of martial arts practice. The exercises that we perform comprise many of the movements that we find in the majority of our techniques. By practicing these movements ahead of time, we can teach the body the fundamentals in a more controlled environment. This way, when the stress of the attack comes, the body already knows about proper footwork, balance, posture, and other physical aspects basic to performing aikido techniques. Also, from a more esoteric point of view, these exercises help to train our spiritual side so that we can harness the power of ki and more effectively execute the techniques the way they were designed to be executed.

When I first started Aikido, I hated the taiso. I admit it without shame. I hated it so much that I contemplated coming to class late to avoid it. Unfortunately, I have met several students who do seem to show up late to class, seemingly just to avoid these exercises. To miss this part of class is to be incomplete as a practitioner of Aikido. Over the years, I have learned to see their value. Do I like them? The answer to that is no not really. I suppose I should clarify that. I don't dislike them but they are not my favorite part of class. I do, however, understand that they play a vital role in my aikido training and for that, I am happy to practice taiso and learn what they have to teach me.

What is Taiso?Taiso is a set of exercises performed by the student while standing alone or in a line. These exercises are simple, repetitive movements that reinforce movements that are taught in class. No one is grabbing or attacking at this point. It is just you and your body, moving and feeling. For example, we go through a variety of wrist stretches, which teach us what it feels like to have a wrist lock performed, at the same time warming up our joints to receive these locks while minimizing risk of injury. We have other movements that stress good posture while moving your hips, legs and feet in the right way.

Our school has about 28 separate taiso that teach posture, stretching, concentration, relaxation, movement, ki extension and other basic principles of aikido. Some of the taiso are exactly like a corresponding technique, while others are simply movement drills designed to help you learn to move from the hip. In all, they encompass many of the principles we learn in class.

What are the benefits?As a teacher, I have come to love the taiso as a teaching aide that make my job easier. Let me give you an example. In our taiso, we do what I like to call the Aiki-Two-Step. This movement is where you step forward with one foot, and then spin to bring your now back foot around behind you, winding up facing the other way. We do this with Ikkyo Undo, Kokyu Ho, Ude Furi and other techniques. When I start to teach a technique that involves this foot work, I often notice people don’t understand how I am moving the way I move. This is when I relate what we are doing in the technique back to what they are doing in the taiso. At this point, I like to see the light bulb go on. They now have a link between what they practice at the beginning of class with what they are doing on the mat right then.

If we take all this to the next step, then what I hope to accomplish as a teacher is to use the taiso to teach the basics. That way, when I am showing how to move into Kote-gaeshi, I don’t have to focus so much on the footwork. I can show them the specifics of a joint lock and how the hand positions relate to each other. I also don’t have to worry about posture. If the taiso are done with appropriate posture, then it is not as big of an issue during the practice of the techniques.

How should you practice Taiso:When practicing taiso, it should be done with concentration and treated with as much respect as a technique. Taiso is a vital part of your training. When going through the motions, try focusing on the following things.

Move your feet properly. This is a great chance to see what your feet are doing. Remember, if your foot is 2 inches off the ground or 2 feet off the ground, it is still off the ground. You are not stable when your feet are not touching the ground.

Watch your posture. Pay attention to the way your body is positioned during the practice. Make sure that you are not moving your head out from over your body and your body out from over your hips. The farther your body parts are away from your center, the harder it is to keep your balance.

Pay attention to the people around you. While working on these skills, you should use this time to practice being aware of the people around you. Awareness is probably one of the most important skills in any martial art. You should never tunnel in and tune out the rest of the class

Watch your breathing. One of the things that does us in before class is over is when we run out of steam. This is exacerbated by not breathing properly. During the taiso, you don’t have anyone attached so relax, settle and breathe. The more you practice proper breathing, the greater chance you will have of it happening when you are not thinking about it.

Do this outside of class. Most Aikido needs to be done with a partner. Taiso gives you the opportunity to improve your Aikido movements without the need for a partner. Use them to improve the basic principles and you will find that when you do the techniques in class, you will have a better understanding of them and consequently, have more fun in class.

Focus on the four basic principles. This is an opportune time to focus on practicing the four basic principles as outlined by Koiechi Tohei Sensei: Focus on the one point, Relax completely, Keep weight underside, and Extend Ki.

One saying that I have grown to embrace over the years, I learned from Shihan David Isgett. He told me “Practice does not make perfect. Perfect practice makes perfect. Practice makes permanent.” If we engage in less than perfect practice, then that is what we will become. So the lesson here is to practice as close to perfection as we can get, so that what becomes permanent is what we desire to become permanent.

What do others think of Taiso:While putting together this paper, I have reviewed many posts online concerning Taiso and found that there are varying opinions of whether or not this type of practice is beneficial or worthy of our time. Understand that these exercises were developed by one of O’sensei’s senior students in an effort to better understand and teach the basic principles of aikido. Learn them well and your time in class will be much better spent.

Other benefits:Taiso also has other benefits in class. Some of them provide certain stretches that help the student warm up. Other benefits include a good cardio vascular warm up. I have even found some of the gentler movements, while holding your infant child, can sooth them back to sleep at two-thirty in the morning. Learn to enjoy taiso and your efforts will be rewarded.

About the Author

My name is Scott Kelley. I am a software engineer in the Atlanta area. I am also into martial arts and music. I have been practicing karate since 1984 and aikido since 1991. This blog is my ramblings on life, liberty and the pursuit of happyness. Anything I say here should be verified by outside sources. Always consider this informatoin ignorant until proven guilty.