Click here to Skip to main content
Click here to Skip to main content
Go to top

Adding Try/Catch Block using AddIn For Visual Studio .NET 2003

, 8 Jul 2005
Rate this:
Please Sign up or sign in to vote.
This add-in adds try/catch blocks inside your method automatically on clicking it.

Introduction

This is an extensibility of VS.NET 2003.This add-in adds try/catch blocks inside your method. This will save development time. Basically it checks whether it is a method and also whether a try/catch block already exists. If not it adds a try/catch inside your method. Usually programmers forget to write try/catch during development time and at the slast minute they will add it in all the pages. That time this will be very useful .They can just execute this add-in which will automatically add try/catch blocks inside your method.

Installation Steps

  1. Run the Setup.exe from the AddTryCatchInstall.zip.
  2. Select the installation folder where you want to install the setup.
  3. Click Close to finish the installation.

Using the Tool

After you install the add-in, it will be listed in the Tools menu automatically. To use this you have to place your cursor inside the method and click this add-in. Adding to the ToolBar: to add it to your toolbar, go to Tools -> Customize -> Select Command tab, then choose AddIn and drag AddTryCatch to the toolbar and drop it.

Source Code Overview

You have to declare this struct which contains the caret position, function name, start and end position of the function.

private struct SFunction
{
    public string FuncName;
    public int StPtr;
    public int EndPt;
    public int CaretPos;
    public bool SearchDone;
}
private SFunction OneFunction;

This method checks for the active document and calls GetWholeProcedure() to add the try/catch block. Add AddingTryCatch() method call in the Exec method (e.g.) handler = AddingTryCatch();

public bool AddingTryCatch()
{
    if (applicationObject.ActiveDocument !=null)
    {
        GetWholeProcedure();
    }
    return true;
}

Code listed below checks for the function in the current window and fetches the function where the cursor is placed. Then it checks if try/catch block exists already. Then it inserts a try at the start of the function and catch/finally at the end of the function.

public void GetWholeProcedure()
{
    TextSelection ts = (TextSelection) applicationObject.ActiveDocument.Selection;
    EditPoint ep = ts.ActivePoint.CreateEditPoint();
    OneFunction.CaretPos=ep.Line;
    OneFunction.SearchDone= false;

    SearchForFunctionInCurrentWindow();
    // if we found the function, get the code
    if (OneFunction.SearchDone)
    {
        ep.MoveToLineAndOffset(OneFunction.StPtr,1);
        string s = ep.GetLines(ep.Line,OneFunction.EndPt+1);
        // Check for Try/Catch Exists
        int found = s.IndexOf("try"); 
        int foundcatch = s.IndexOf("catch("); 
        int position = 2;
        // If not Try/Catch Exists
        if(found == -1 || foundcatch == -1 )
        {
            TextSelection ts1 = 
              (TextSelection)applicationObject.ActiveDocument.Selection;
            // Sets the Insertion point based on webservice or webform file
            if(applicationObject.ActiveDocument.Name.IndexOf("asmx.cs") 
                      != -1 && s.IndexOf("[WebMethod]") != -1 )  
                position = 3;
            else
                position = 2;
            ts1.GotoLine((OneFunction.StPtr + position),true);
            ts1.Copy();
            // Inserts Try at start of the function
            EditPoint e =ts1.TopPoint.CreateEditPoint();
            e.Insert("\t\t\ttry\n\t\t\t{\n");
            ts1.Paste(); 
            // Indents the lines 
            int currentposition = OneFunction.StPtr + position + 1 ;
            for(int intLoop = 1 ; intLoop <=(OneFunction.EndPt - 
                           (OneFunction.StPtr+position));intLoop++)
            {
                ts1.GotoLine((currentposition + intLoop),true);
                if(ts1.Text.Equals("") != true )
                {
                    ts1.SelectLine();
                    ts1.Indent(1);
                }
            }
            // Goes to the end of the function and inserts Catch/Finally Block.
            e.LineDown(OneFunction.EndPt-(OneFunction.StPtr+position));
            e.Insert("\t\t\t}\n\t\t\tcatch(Exception ex)\n\" + 
                     "t\t\t{\n\t\t\t\tthrow ex;\n\t\t\t}\n\" + 
                     "t\t\tfinally\n\t\t\t{\n\t\t\t}\n");
        }
        else
        {
            System.Windows.Forms.MessageBox.Show("Try/Catch Block already exists"); 
        }
    }
}

The below functions are the major things which find out the function in the active window. It checks for the function in the caret position and returns the starting and ending point of the function and sets the searchDone flag to true. Some of the extensibility classes used are:

  • ProjectItem - Represents an item in a project.
  • FileCodeModel - Allows access to programmatic constructs in a source file.
  • CodeElements - Represents a code element or construct in a source file.
  • CodeNamespace - Represents a namespace construct in a source file.
  • CodeClass - Represents a class in source code.
// enumerates all classes in all namespaces in a window 
private void SearchForFunctionInCurrentWindow()
{
    ProjectItem pi = (ProjectItem) applicationObject.ActiveWindow.ProjectItem;
    FileCodeModel fcm = pi.FileCodeModel;

    if ( fcm!=null) 
        GetFunction(fcm.CodeElements);
} 
private void GetFunction(CodeElements elements)
{
    // Looks for the function and returns the code.
    CodeElements members;
    foreach (CodeElement elt in elements)
    {
        if(OneFunction.SearchDone)
            return ;

        if (elt.Kind==vsCMElement.vsCMElementFunction )
        {
            OneFunction.FuncName=elt.Name;
            OneFunction.StPtr=elt.StartPoint.Line;
            OneFunction.EndPt=elt.EndPoint.Line;
            if(OneFunction.CaretPos>= OneFunction.StPtr && 
               OneFunction.CaretPos <= OneFunction.EndPt)
            {
                OneFunction.SearchDone=true;
                return;
            }
        }
        else
        {
            members = GetMembers(elt);
            if (members != null )
                GetFunction(members);
        }
    }
}
private CodeElements GetMembers(CodeElement elt)
{
    CodeElements members = null ;
    if(elt!= null)
    {
        switch ( elt.Kind)
        {
            case (vsCMElement.vsCMElementNamespace ):
            {
                CodeNamespace cdeNS = (CodeNamespace) elt;
                members = cdeNS.Members;
                break ;
            }
            case (vsCMElement.vsCMElementClass):
            {
                CodeClass cdeCL = (CodeClass) elt;
                members = cdeCL.Members;
                break;
            }
            case (vsCMElement.vsCMElementFunction):
            {
                // functions dont have members
                members=null;
                break;
            }
        }
    }
    return members;
}

Conclusion

Hope this tool would be useful. Good day...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Santhi.M

India India
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberitsho18-Jan-11 22:14 
Question2005 PinmemberEric Fleet6-Sep-07 3:11 
GeneralGood tool for the .NET devs Pinmemberharikaran28-Jul-05 18:36 
GeneralNice Article PinmemberVasudevan Deepak Kumar27-Jul-05 22:39 
GeneralIt is Nice Add-On utility Pinmembersengu2van26-Jul-05 18:25 
GeneralException Handling PinmemberSantosh Sinha24-Jul-05 18:59 
GeneralHi PinmemberSanthi.M10-Jul-05 19:53 
GeneralCant download source. Pinmembermellospank8-Jul-05 1:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 8 Jul 2005
Article Copyright 2005 by Santhi.M
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid