Saturday, May 30, 2015

Logout user after browser close in ASP.NET C# using web services

Introduction:
Keeping a track of user's time in your web application is one of the most important issue to maintain. It not only helps to keep the track of user's but also it helps to solve any other analytical problems with application's data, like average in time, average out time, average time spent in your application etc. So how to keep the users login logout information of your web application.

By clicking on the login button you can easily get the login time, and I hope you have kept your session checking active during logging of your users. On other hand by clicking on the Logout button you can also trace the logout time. But what happen when user close the browser, then how will you keep the track of user's logout time. Here in this post we will discuss about this serious issue.

Using of Web Services
Instead of using  normal methods we will use Web services to get the logout time for the user.

What is Web Services?
According to MSDN
Web services are components on a Web server that a client application can call by making HTTP requests across the Web. ASP.NET enables you to create custom Web services or to use built-in application services, and to call these services from any client application.
Key Concept:
There is a function named onbeforeunload of javascript. This is called at the time of unloading the web page, whether you are closing the browser or closing the tab or redirecting to any other web page from that particular page, where it is coded. Do not use an alert() within onbeforeunload, it will not work.

Using this we are getting the login session id and passes it to the web services. And in web service we are doing our necessary thing(sql server entry or putting it in any notepad with login id etc.).

Using the code:
 Lets create a project named it whatever you want. Add a new web form and design it according to you.

On the aspx page's head section write down the following code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
        window.onbeforeunload = function (evt) {
            var message = 'You have started writing or editing a post.';
            var loginId = '<%= Session["LoginId"].ToString() %>';
            console.log('in');

            $.ajax({
                url: "Logout.asmx/LogoutMethod",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                success: function (data) {
                    alert(data);
                },
                error: function (x, y, z) {
                    alert(x.responseText + "  " + x.status);
                }
            });
        }
</script>

On body you do whatever your design or work. In the web services write down again the following code. And make sure that [System.Web.Script.Services.ScriptService] is uncommented


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Logout : System.Web.Services.WebService
{
   [WebMethod (EnableSession = true)]
   public string LogoutMethod()
   {
       // take a log.txt and write on there with time
       string a = Session["LoginId"].ToString();
       File.AppendAllText(Server.MapPath("~/log.txt"),"Login id loges out "+a+ " at "+ DateTime.Now.ToString()+ Environment.NewLine);

        return "";
    }
}

Before run this create a log.txt file in your solution explorer, where all your log out log will be stored.

You can down the full source code here.  Now its your turn to do. Try it in your machine.

0 comments:

Post a Comment

Follow by Email

Popular Posts

Pageviews