About the author

Vijay Kodali
E-mail me Send mail

Site Statistics

Site Meter

Recent comments

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2017

Asp.net session on browser close

How to capture logoff time when user closes browser?

Or

How to end user session when browser closed?

These are some of the frequently asked questions in asp.net forums.

In this post I'll show you how to do this when you're building an ASP.NET web application.

Before we start, one fact:

There is no full-proof technique to catch the browser close event for 100% of time. The trouble lies in the stateless nature of HTTP. The Web server is out of the picture as soon as it finishes sending the page content to the client. After that, all you can rely on is a client side script. Unfortunately, there is no reliable client side event for browser close.

Solution:

The first thing you need to do is create the web service. I've added web service and named it AsynchronousSave.asmx. 

 Open Dialog

Make this web service accessible from Script, by setting class qualified with the ScriptServiceAttribute attribute... 

clip_image004

Add a method (SaveLogOffTime) marked with [WebMethod] attribute. This method simply accepts UserId as a string variable and writes that value and logoff time to text file. But you can pass as many variables as required. You can then use this information for many purposes.

clip_image006

To end user session, you can just call Session.Abandon() in the above web method.

To enable web service to be called from page’s client side code, add script manager to page. Here i am adding to SessionTest.aspx page

clip_image008

When the user closes the browser, onbeforeunload event fires on the client side. Our final step is adding a java script function to that event, which makes web service calls. The code is simple but effective

clip_image010

My Code

HTML:( SessionTest.aspx )

clip_image012

C#:( SessionTest.aspx.cs )

clip_image014

That’s’ it. Run the application and after browser close, open the text file to see the log off time.

clip_image016

The above code works well in IE 7/8. If you have any questions, leave a comment.


Posted by vijay on Thursday, April 29, 2010 6:09 PM
Permalink | Comments (22) | Post RSSRSS comment feed

Visual Studio 2008 short cuts

I know there are many posts dedicated to this topic. For example, Sara Ford posted about 290 shortcuts on her blog. Check Zain Naboulsi blog for VS 2010 tips.

But it’s almost impossible to use all of them on daily basis. And further most of them are really not that useful. Here are 10 of my favorite Visual Studio keyboard shortcuts, ones I use most..

1) Double TAB

If you know snippet key name, write and click double Tab.

For example: Write

If

and then click tab key twice to get

if (true)
{
    
}

Similarly write try then click tab key twice to get

try
{

}
catch (Exception)
{
    
    throw;
}

2) CTRL + TAB to switch open windows in visual studio

3) CTRL+K and CTRL+D to format code

4) CTRL+SHIFT+V to cycle through clipboard

5) SHIFT+ALT+ENTER for full screen mode

6) F7 to switch between code behind and .aspx files

7) CTRL+H or CTRL+SHIFT+H for find and replace

8) Ctrl+F5 to run without debugging. F5 only will run in debugging mode

    F11 to step into a method. SHIFT+F11 to step out of a method. F10 to step over a method.

9) F9 toggle and un-toggle breakpoints

10)F12 to go to definition

 

What’s your favorite Visual Studio keyboard shortcut/hidden feature/trick..?


Tags:
Posted by vijay on Thursday, March 04, 2010 9:42 PM
Permalink | Comments (1) | Post RSSRSS comment feed

Auto save Asp.net form values Asynchronously

In this article, I will explain how to save Asp.Net page values asynchronously (aka Gmail style of saving mail drafts).  

Introduction:

In the past, Web applications were known for having less usable, less responsive user interfaces. AJAX changed all of that. The application can work asynchronously and the user doesn't have to sit and wait for pages to refresh. :

What is Ajax?

Ajax (Asynchronous JavaScript and XML) is an approach to web development that uses client-side scripting to exchange data with a web server. 

Solution:

There are several ways of achieve it. In this article I am using AJAX functionality to call ASP.NET Web services from the browser by using client script. Yes, no updatepanel.  

Start by adding a web service to the project as shown below, name it as AsynchronousSave.asmx. Make this web service accessible from Script, by setting class qualified with the ScriptServiceAttribute attribute...  

[System.Web.Script.Services.ScriptService]    
public class AsynchronousSave : System.Web.Services.WebService 


Here is the AsynchronousSave webservice class: 
// 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 WebService2 : System.Web.Services.WebService
{

    [WebMethod]
    public string HelloWorld()
    {

        return "Hello World";

    }

    [WebMethod]
    public string SaveInput(String input)
    {
        string StrInput = Server.HtmlEncode(input); if (!String.IsNullOrEmpty(StrInput))
        {

            string[] strFields = StrInput.Split('+');

            //code to save all input values
            // you can easily savethese values to temp DB table, temp file or xml file
            //Dispaly last saved values

            return String.Format("Last saved text: FirstName {0} ,<br/> Last name {1} <br/> Last "

            + "saved draft {2} at {3}.", strFields[0], strFields[1], strFields[2], DateTime.Now);

        }

        else
        {

            return ""; //if input values are empty..retrun empty string
        }
    }
}
 
Nothing fancy here, just methods marked with [WebMethod] attribute. The Saveinput method takes an input string with “+” as delimiter between form values.  

To enable web service to be called from client side, add script manager to page  

<asp:ScriptManager runat="server" ID="scriptManager">
    <Services>
        <asp:ServiceReference Path="~/AsynchronousSave.asmx" />
    </Services>
</asp:ScriptManager>


And here is HTML of page

<div>
    First Name:<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></br> 
    LastName:<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></br> 
    Draft :<asp:TextBox ID="txtDraft" runat="server"></asp:TextBox></br></div>
<div id="Preview">

The following example shows the java script that makes service calls

<script language ="javascript" >
    //This function calls the web service    
    function SaveUserInput() {
        var fName = document.getElementById("txtFirstName");
        var lName = document.getElementById("txtLastName");
        var draft = document.getElementById("txtDraft");
        //Saving all input in a single value         
        var input = fName.value + "+" + lName.value + "+" + draft.value;
        //ProjName.WebServiceName.WebMethod         
        SampleApplication1.AsynchronousSave.SaveInput(input, SucceededCallback);
    }
    // This is the callback function that processes the Web Service return value.     
    function SucceededCallback(result) {
        var divPreview = document.getElementById("Preview");
        divPreview.innerHTML = result;
    }
    // execute SaveUserInput for every 10 sec, timeout value is in miliseconds
    window.setInterval('SaveUserInput()', 10000); 
    
</script>

Reference:

http://msdn.microsoft.com/en-us/library/bb398998.aspx

         


Tags:
Posted by vijay on Monday, November 23, 2009 2:17 PM
Permalink | Comments (0) | Post RSSRSS comment feed

ASP.Net AJAX AsyncFileUpload Control

AsyncFileUpload is a new ASP.NET AJAX Control (Ajax Control Toolkit (v 3.0.30930) released for .NET 3.5 SP1) that allows you asynchronously upload files to server. You don’t need a separate upload button for this control.  Add the AsyncFileUpload control and a label to the web form for the uploading and displaying messages respectively.  HTML:

<asp:ScriptManager ID="ScriptManager1" runat="server"> 
</asp:ScriptManager> 
<cc1:AsyncFileUpload ID="AsyncFileUpload1" runat="server" CompleteBackColor="White" 
OnUploadedComplete="AsyncFileUpload1_UploadedComplete" OnUploadedFileError="AsyncFileUpload1_UploadedFileError" 
OnClientUploadComplete="Success" OnClientUploadError="Error" /> 
<asp:Label ID="Label1" runat="server"></asp:Label> 

Server side events:

protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e) 
{ 
 //Fired on the server side when the file successfully uploaded 
   if (AsyncFileUpload1.HasFile) 
   { 
         AsyncFileUpload1.SaveAs(@"C:\Images\" + AsyncFileUpload1.FileName ); 
         Label1.Text = "Received " + AsyncFileUpload1.FileName + " Content Type " + AsyncFileUpload1.PostedFile.ContentType ; 
   } 
 } 
protected void AsyncFileUpload1_UploadedFileError(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e) 
 { 
 //Fired on the server side when the loaded file is corrupted 
 //Display some error message here 
 } 

Client side events:

OnClientUploadError - The name of a javascript function executed in the client-side if the file uploading failed  

OnClientUploadComplete - The name of a javascript function executed in the client-side on the file uploading completed

function Success() { 
document.getElementById("Label1").innerHTML = "File Uploaded Successfully !!"; 
} 
function Error() { 
document.getElementById("Label1").innerHTML = "File upload failed"; 
} 

We can use  OnClientUploadComplete to clear fileupload control selction,

function Success() { 
document.getElementById ("Label1").innerHTML = "File Uploaded Successfully !!"; 
var fu = document.getElementById("AsyncFileUpload1"); 
document.getElementById("AsyncFileUpload1").innerHTML = fu.innerHTML; 
} 

Reference:  http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AsyncFileUpload/AsyncFileUpload.aspx


Posted by vijay on Friday, October 02, 2009 2:48 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Formatted Date based on the browser language setting

One of new feature that was added in Asp.net 3.5  is script globalization and localization. We can display date based on language setting of browser. Here is code snippet of displaying date in local language using script..

[code:c#]

   <script type="text/javascript">
        function formatDate() {
            var d = new Date();
            try {
                $get('Label1').innerHTML = d.localeFormat("dddd, dd MMMM yyyy HH:mm:ss");
            }
            catch (e) {
                alert("Error:" + e.message);
            }
        }
        window.onload
        {
            formatDate();
        }
    </script>

[/code]


Posted by vijay on Saturday, August 16, 2008 7:31 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Web Application Project vs Web Site Project in Visual Studio

Web Site Project is deployed with source code to the server and all compilation takes place at runtime.

Web Application Projects, the code behind classes are compiled to dll. That dll is deployed and at runtime, the compiled code in the dll and the markup is combined to create a class which is used by the server to render output.

Update:

Good post by anthony on this

post by Stephen on this topic


Posted by vijay on Sunday, July 06, 2008 9:04 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Lambda Expressions

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.Lambda Expressions provide a more concise, functional syntax for writing anonymous methods.

Categories: .Net 3.5 | C# | LINQ
Posted by vijay on Tuesday, January 22, 2008 8:43 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Anonymous Types

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type.

 This is an important feature for the LINQ feature that will be integrated into C#. Since anonymous types do not have a named typing, they must be stored in variables declared using the var keyword, telling the C# compiler to use type inference for the variable.


Categories: .Net 3.5 | C#3.0
Posted by vijay on Monday, January 21, 2008 10:57 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Implicitly Typed Local Variables-“Var”

In C# 3.0, you can declare an integer  as –

[code:c#]

var first = 7;

Console.WriteLine("First variable is of type: {0}", first.GetType());

[/code]

It will return”Int32” as DateType, even though we declare it as “var”. So what  is “var”?

from MSDN..

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

To put it simply "var" is a keyword that results in variable being of the same data type, of the initializer. It works similar to “object” type in older version. But there is great difference between “Object” and “var”. Check following code snippet-

[code:c#]

object newObj = 58;  

int test = newObj; //this line result in an error "Cannot implicitly convert type object to int"

 int test = (int)newObj; // this line will work. But result in boxing..additional overhead

[/code]

So Objects have boxing and unboxing issues. Now consider same instance with “var”- 

[code:c#]

var newObj = 22;

int test = newObj; //no boxing involved. It is type-safe

[/code]

C# is still strongly typed. “Var” is NOT a variant, everything is known by the compiler at compile-time.

Tags:
Posted by vijay on Friday, January 18, 2008 9:11 PM
Permalink | Comments (0) | Post RSSRSS comment feed

ListView

One of the new controls in ASP.NET 3.5 is ListView. It resembles the GridView control, except that it displays data by using user-defined templates instead of row fields.

The ListView control supports the following features:

ü  Support for binding to data source controls such as SqlDataSource, LinqDataSource, and ObjectDataSource.

ü  Customizable appearance through user-defined templates and styles.

ü  Built-in sorting capabilities.

ü  Built-in update and delete capabilities.

ü  Built-in insert capabilities.

ü  Support for paging capabilities by using a DataPager control.

ü  Built-in item selection capabilities.

ü  Programmatic access to the ListView object model to dynamically set properties, handle events, and so on.

ü  Multiple key fields.

 


Categories: .Net 3.5 | ASP.Net 3.5 | C#
Posted by vijay on Monday, January 14, 2008 8:13 PM
Permalink | Comments (0) | Post RSSRSS comment feed