Friday , 29 August 2014
Home » Silverlight » Tips

Tips

Silverlight Auto logout user after 10 minutes of inactivity

 

Many projects have requirement to logout a user after some time of Inactivity user has not performed any activity for past 10 minutes we need to auto logout the user.

Solution

Use

DispatcherTimer SMNetworkTimer = new DispatcherTimer();

Sample implementation

App.xaml.cs

 

Declare a timer in app file as as follows
public static System.Windows.Threading.DispatcherTimer _Logouttimer = new System.Windows.Threading.DispatcherTimer();
private static DateTime App.timer=DateTime.Now; // this variable helps in finding the user interaction time in master page

public Timer
(
set{};
get{};
)

 

public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            _Logouttimer.Tick += new EventHandler(_Logouttimer_Tick);
            __Logouttimer.Interval = TimeSpan.FromSeconds(60);
            InitializeComponent();
        }


this timer will check for every 60 seconds for timeout logout

void __Logouttimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if ((DateTime.Now - App.Timer) > new TimeSpan.Minutes(20))
                {
                    
App app = (App)Application.Current;


            
            
                // Remove the displayed page
                app.root.Children.Clear();

                // Show the next page
                app.root.Children.Add(new LoginPage); //load the loginpage or the specific page you want to naviagte the user after timeout
            }
                
            }
            catch (Exception ex)
            {

            }
        }
           



Keep this event in master page to get the users last interaction time with the application

void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                App.Timer = DateTime.Now;
            }
            catch (Exception ex)
            {
            }
        }