About the author

Vijay Kodali
E-mail me Send mail

Recent comments

Authors

Disclaimer

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

© Copyright 2024

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 4, 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 2, 2009 2:48 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Microsoft releases CTP of Visual studio 2010 and Dot net framework 4.0

According to Scott Guthrie VS2010 was built using the Windows Presentation Foundation. VS2010 will offer features like multi-monitor support, richer code editing and richer code visualization.

Check this .Net 4.0 framework poster


Tags:
Categories: General
Posted by vijay on Thursday, October 30, 2008 7:36 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Disable Backspace to Previous Page in Asp.Net

The following code will allow backspace in textbox not on form. This code works perfectly in IE7/8,FireFox,Chrome

<script language=javascript>   
            
    function cancelBack()   
    {   
        if ((event.keyCode == 8 ||    
           (event.keyCode == 37 && event.altKey) ||    
           (event.keyCode == 39 && event.altKey))   
            &&    
           (event.srcElement.form == null || event.srcElement.isTextEdit == false)   
          )   
        {   
            event.cancelBubble = true;   
            event.returnValue = false;   
        }   
    }   
  
</script>   
<body onkeydown=cancelBack()>   

Tags:
Categories: ASP.Net 3.5 | JavaScript
Posted by vijay on Tuesday, September 2, 2008 9:50 AM
Permalink | Comments (6) | Post RSSRSS comment feed

Removing empty spaces and HTML tags from TextBox text on client side

Here is a small code to remove spaces from textbox's text in onblur event.

 

<asp:TextBox ID="TextBox2" runat="server" onblur="javascript:value=value.replace(/\s/g,'');"></asp:TextBox>

 

To remove HTML tags..

<asp:textbox id="TextBox2" runat="server" onblur="this.value = this.value.replace(/<\/?[^>]+>/gi, '');">
</asp:textbox>

 

Please let me know, if you have any issues.


Tags:
Posted by vijay on Thursday, June 12, 2008 1:24 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Change back ground color of Asp.net Textbox on validation failure

Here is a way of changing back ground color for Textbox on validation failure. The key here is using Page_ClientValidate function in javascript.

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Please enter a value"
    ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="btnClick();"
    OnClick="Button1_Click1" />

<script type="text/javascript"> 

    function btnClick() 
    { 
        if (!Page_ClientValidate()) 
        { 
            document.getElementById("TextBox1").style.backgroundColor="red"; 
        } 
    } 

    function ClearBackGround() 
    { 
        document.getElementById("TextBox1").style.backgroundColor=""; 
    } 

</script>
In Code behind

TextBox1.Attributes.Add("onkeypress", "ClearBackGround()");


Tags:
Categories: ASP.NET | JavaScript
Posted by vijay on Thursday, June 5, 2008 9:08 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Detecting Session Timeout and Redirect to Login Page in ASP.NET

HTTP(web page) is stateless, so we cannot know whether the Session has really expired without sending a page request back to the server. If you want to redirect the page immediately(with out any user action) after session expires consider this approach.

 

Response.AppendHeader("Refresh",Convert.ToString((Session.Timeout * 60)+ 10)+";URL=Login.aspx");

 

Add this line of code to page_Load.


Tags:
Categories: ASP.NET | ASP.Net 3.5
Posted by vijay on Friday, April 11, 2008 6:35 PM
Permalink | Comments (2) | Post RSSRSS comment feed

Detecting Asp.Net page close event

Sometimes we have to capture page close event or navigation event to alert users. For example, Alerting user for navigating away from input page without saving it. Check this java script code..

window.onbeforeunload= function(){
if((window.event.clientX<0) || (window.event.clientY<0))
    {
      event.returnValue = "Are you sure you want to navigate away from this page? You haven't saved this form.";
    }
};

This code works only in Ie6/7. And also keep in mind, we can never catch the browser close event for 100%. For example, what if the user kills the browser process or shut down OS.


Tags:
Posted by vijay on Thursday, March 20, 2008 2:49 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Add, Delete Items in DropDownList, ListBox using Javascript

I have seen lots of questions in Asp.Net forums for adding/deleting items in drop down list or list box using JavaScript. Here is the code...

<asp:DropDownList ID="DropDownList1" runat="server" Width="182px"> 
<asp:ListItem value="1" Text ="Approve"></asp:ListItem> 
<asp:ListItem value="2" Text ="Accept"></asp:ListItem> 
<asp:ListItem value="3" Text ="Test1"></asp:ListItem> 
<asp:ListItem value="4" Text ="Test2"></asp:ListItem> 
</asp:DropDownList> 

<input type="button" value="Remove selected item" onclick="JavaScript: DeleteItem();" /> 
<input type="text" id="ddlText" name="ddlText" /> 
<input type="text" id="ddlValue" name="ddlValue" /> 
<input type="button" value="Add item" onclick="JavaScript: AddItem();" /> 
<input type="hidden" id="ddlElements" name="ddlElements" runat="server" /> 
<asp:Button ID="Button1" runat="server" Text="Button" />
    <script type="text/javascript"> 
    function DeleteItem() 
    { 

        var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>'); 
        var optionsList = ''; 

        if ( dropDownListRef.value.length > 0 ) 
        { 
            var itemIndex = dropDownListRef.selectedIndex;
       if ( itemIndex >= 0 ) 
            dropDownListRef.remove(itemIndex); 
        } 
        else 
        { 
            alert('Please select an item'); 
            dropDownListRef.focus(); 
            dropDownListRef.select(); 
        } 
          

        for (var i=0; i<dropDownListRef.options.length; i++) 
        { 
        var optionText = dropDownListRef.options[i].text;
        var optionValue = dropDownListRef.options[i].value; 
     
        if ( optionsList.length > 0 )
            optionsList += ';'; 
            optionsList += optionText; 
            optionsList += ';'; 
            optionsList += optionValue; 
        } 
        document.getElementById('<%= ddlElements.ClientID %>').value = optionsList; 
    } 


    function AddItem() 
    { 

        var dropDownListRef = document.getElementById('<%= DropDownList1.ClientID %>'); 
        var ddlTextRef = document.getElementById('ddlText'); 
        var ddlValueRef = document.getElementById('ddlValue'); 
        var optionsList = ''; 

        if ( ddlTextRef.value !="" && ddlValueRef.value!="" ) 
        { 
            var option1 = document.createElement("option"); 
            option1.text= ddlValueRef.value; 
            option1.value= ddlTextRef.value ; 
            dropDownListRef.options.add(option1); 
        } 
        else 
            alert('Please enter values'); 
          
        for (var i=0; i<dropDownListRef.options.length; i++) 
        { 

        var optionText = dropDownListRef.options[i].text;
        var optionValue = dropDownListRef.options[i].value; 
          
        if ( optionsList.length > 0 )
        
            optionsList += ';'; 
            optionsList += optionText; 
            optionsList += ';'; 
            optionsList += optionValue; 
        } 
            document.getElementById('<%= ddlElements.ClientID %>').value = optionsList; 
       
    } 

</script>

In Code behind Page_Load, add following code..

if (IsPostBack)
{
    DropDownList1.Items.Clear();
    string[] DropDownListArray = ddlElements.Value.Trim().Split(';'); 
    
    for (int i = 0; i < DropDownListArray.Length; i = i + 2)
    {
        string itemText = DropDownListArray[i];
        string itemValue = DropDownListArray[i + 1]; 
        DropDownList1.Items.Add(new ListItem(itemText, itemValue));
    }

}

string optionsList = string.Empty; 
for (int i = 0; i < DropDownList1.Items.Count; i++)
{
   string optionText = DropDownList1.Items[i].Text;
   string optionValue = DropDownList1.Items[i].Value;
          
    if (optionsList.Length > 0) 
      
    optionsList += ";";
    optionsList += optionText;
    optionsList += ';';
    optionsList += optionValue;
}

ddlElements.Value = optionsList; 

Update:  Client-side changes to a DropDownList/ListBox are not persisted server-side, so any changes made will be lost if a PostBack occurs. Added server-side persistence to code. (Thanks to tip form NC01)

 


Tags:
Posted by vijay on Friday, December 14, 2007 9:40 PM
Permalink | Comments (0) | Post RSSRSS comment feed