Click here to Skip to main content
Click here to Skip to main content

C# Code Runner Macro for Visual Studio 2003

By , 26 Sep 2007
 

Introduction

Many a times, programmers want to execute a small code snippet to see the output of some simple calculations. They have to waste time creating a new project, writing the sample code and executing it on some form.

For instance, we want to check the output in the following cases:

  1. int i = 2, j; 
    j = i * 3; 
    return j; 
  2. DateTime dt = new DateTime();
    return dt;

The Problem

A simple solution to get the output is to code a macro that can compile just the code snippet and give you the solution, all in the same code window you are using now.

So, here is a list of requirements for the macro I can think of:

  1. It should display the value of a variable that is a result of a calculation or a simple code execution.
  2. A programmer doesn't have to create a new project/form. The programmer will just select the code snippet that he/she wants to execute.
  3. There must be some facility to include namespaces.
Screenshot - UsageSample1.jpg

Using the Code

To solve the problem of execution of the code snippet, I use reflection. I also assume some custom keywords for identifying the return variable.

Following are the steps involved in the macro:

  1. Firstly, before compiling the code, we need to convert the code snippet into a complete class.
  2. Then we compile the code snippet. Report any errors directly from here.
  3. Then we create an object of the newly compiled class.
  4. Execute the dummy function containing the code snippet.
  5. Output the result to the Output Window. Here I assume that when we want to include any namespace in the compilation, we use the keyword using. The keyword return is used to identify the return variable.

Here, we have a snippet that picks up the user selected source code to execute.

'Check if any special using is used in code
        For i As Integer = iStart To iEnd

            ActiveDocument().Selection.GotoLine(i)
            ActiveDocument().Selection.SelectLine()

            'Check if the user wants to include some special namespace
            If (ActiveDocument().Selection.Text.Trim().IndexOf("using") >= 0) Then

                'add the assembly to the future code
                strUsing += ActiveDocument().Selection.Text.Trim()
            ElseIf (ActiveDocument().Selection.Text.Trim().IndexOf("return") >= 0) Then

                'Set the return string for the function
                strReturn = ActiveDocument().Selection.Text.Trim().Replace(";", "") + _
                                                               ".ToString();"

            ElseIf (ActiveDocument().Selection.Text.Trim().IndexOf("refer") >= 0) Then

                compilerOptions.ReferencedAssemblies.Add(ActiveDocument(). _ 
            Selection.Text.Trim().Replace(";", "").Replace("refer", "").Trim())

            Else

                'else add it as source
                strSource += ActiveDocument().Selection.Text.Trim()

            End If

        Next

As seen in the above code snippet, we get the user selection and loop through all the lines. In case we find the two keywords, using and return, we make the appropriate settings. All other lines are considered as statements to be directly executed.

After this step, we compile the dummy code and make an object of the newly compiled class:

'Get the Assembly from the compiled code
        newAssembly = compilerResults.CompiledAssembly()

        'Get the method and call it
        Dim objTypes() As Type = newAssembly.GetTypes()
        Dim t As Type = newAssembly.GetType("TestNamespace.TestClass")
        Dim obj As Object = Activator.CreateInstance(t)
        Dim method As MethodInfo = t.GetMethod("TestMe")

        'Call the output of the method
        owpane.OutputString("Output = " + method.Invoke(obj, Nothing))    

We simply run the function and use the ToString() method to get the text of the variable.

We also use a simple function to get a handle to the Output window in Visual Studio where we display the output to the user.

    Function GetOutputWindowPane(ByVal Name As String, _
        Optional ByVal show As Boolean = True) As OutputWindowPane
        Dim win As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput)
        If show Then win.Visible = True
        Dim ow As OutputWindow = win.Object
        Dim owpane As OutputWindowPane
        Try
            owpane = ow.OutputWindowPanes.Item(Name)
        Catch e As System.Exception
            owpane = ow.OutputWindowPanes.Add(Name)
        End Try
        owpane.Activate()
        Return owpane
    End Function

Drawbacks

  • Some major drawbacks in this macro are that it does not have much of error handling.
    It only works for C# but can be easily modified to work for VB.NET too.
  • Complex objects cannot be calculated. e.g. Datatable, Dataset.

Update History

  • 27/09/2007: Posted the article (Code with lot of bugs:)
  • 28/09/2007: Changed the files bundled in the Zip (Imports and common function added)

License

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

About the Author

Amol M Vaidya
Web Developer
India India
Member
My computer career started as an Avid Gamer Smile | :) . I loved the old times Xatax and Wolf. But, curiosity took over my gaming side and I started to search on ways to create all the mesmerising programs that I used.
I started programming in Qbasic and then moved on to every possible programming language I could lay my hands on. Qbasic, Pascal, C, C++, Win32 SDK, VB 6.0, VB.NET, C#, Struts, Core Java, Javascript, VbScript, Unix Shell Programming, SQL SERVER PROGRAMMING, WMI scripting....are some of the languages I can boast of being proficient in.
My formal introduction to computers was when I took the Bachelor of Computer Sciences (Pune, India) degree.Later on I got Masters from the same university.
My Professional Certifications include
MCP SQL Server 2000 (70-229)
Brainbench Certified MS SQL Server Programmer
Brainbench Certified MS SQL Server Administrator
Brainbench Certified ASP.NET Programmer
Brainbench Certified Javascript Programmer
Brainbench Certified RDBMS Concepts
 
Currently I am working in Japan. Unofficially, My programming experience is now 7+ years.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMuch bettermembermrchief_200026 Dec '07 - 9:47 
GeneralI don't manage to integrate it...memberromlel5926 Sep '07 - 21:52 
GeneralRe: I don't manage to integrate it...memberAmol M Vaidya27 Sep '07 - 4:00 

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 26 Sep 2007
Article Copyright 2007 by Amol M Vaidya
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid