Execute C# Code

POST
/tools-api/code/csharp

Description

This endpoint allows you to dynamically execute C# code on the server. It provides a powerful way to run custom C# code to interact with Windows applications, manipulate data, or perform complex operations that aren't covered by other API endpoints.

Security Note: This endpoint executes arbitrary C# code on the server. It should only be used in secure environments where you trust the source of the code being executed. The execution is sandboxed, but still has access to many system APIs.

Request Format

{
  "code": "string"       // C# code to execute
}
            

Parameters

Parameter Type Required Description
code string Yes The C# code to execute. This should be a complete, compilable C# program or snippet.

Response Format

{
  "success": boolean,      // Whether the execution was successful
  "message": "string",     // Status message or error description
  "result": "string",      // Combined output from the code execution
  "timestamp": "string"    // The timestamp when the execution occurred
}
            

Response Fields

Field Type Description
success boolean Indicates whether the code executed successfully without exceptions.
message string A status message or error description if the execution failed.
result string Combined output from the code execution.
timestamp string The timestamp when the code was executed.

Code Examples

import requests
import json

def execute_csharp_code(code, api_key=None):
    """
    Execute C# code on the server.
    
    Args:
        code (str): The C# code to execute
        api_key (str, optional): Your API key for authentication
        
    Returns:
        dict: The execution results
    """
    url = "http://localhost:5000/tools-api/code/csharp"
    
    headers = {
        "Content-Type": "application/json"
    }
    
    # Add authorization header if API key is provided
    if api_key:
        headers["Authorization"] = f"Bearer {api_key}"
    
    data = {
        "code": code
    }
    
    response = requests.post(url, headers=headers, data=json.dumps(data))
    return response.json()

# Example: Simple hello world
code = """
using System;

public class Program
{
    public static object Main()
    {
        Console.WriteLine("Hello from C#!");
        return new { Message = "Success", Value = 42 };
    }
}
"""

result = execute_csharp_code(code)
print(f"Success: {result['success']}")
print(f"Message: {result['message']}")
print(f"Result: {result['result']}")
print(f"Timestamp: {result['timestamp']}")
                    
interface ExecuteCSharpRequest {
  code: string;
}

interface ExecuteCSharpResponse {
  success: boolean;
  message: string;
  result: string;
  timestamp: string;
}

/**
 * Execute C# code on the server.
 * 
 * @param code - The C# code to execute
 * @param apiKey - Optional API key for authentication
 * @returns A promise that resolves to the execution results
 */
async function executeCSharpCode(
  code: string,
  apiKey?: string
): Promise {
  const url = 'http://localhost:5000/tools-api/code/csharp';
  
  const headers: Record = {
    'Content-Type': 'application/json'
  };
  
  // Add authorization header if API key is provided
  if (apiKey) {
    headers['Authorization'] = `Bearer ${apiKey}`;
  }
  
  const request: ExecuteCSharpRequest = {
    code
  };
  
  const response = await fetch(url, {
    method: 'POST',
    headers,
    body: JSON.stringify(request)
  });
  
  return await response.json();
}

// Example usage
(async () => {
  const API_KEY = 'your_api_key_here';
  
  try {
    // Example 1: Simple hello world
    const code = `
using System;

public class Program
{
    public static object Main()
    {
        Console.WriteLine("Hello from C#!");
        return new { Message = "Success", Value = 42 };
    }
}`;
    
    const result = await executeCSharpCode(code, API_KEY);
    console.log(`Success: ${result.success}`);
    console.log(`Message: ${result.message}`);
    console.log(`Result: ${result.result}`);
    console.log(`Timestamp: ${result.timestamp}`);
    
  } catch (error) {
    console.error('Error executing C# code:', error);
  }
})();
                    
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class ExecuteCSharpRequest
{
    public string Code { get; set; }
}

public class ExecuteCSharpResponse
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public string Result { get; set; }
    public string Timestamp { get; set; }
}

public class ToolsServerClient
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey;
    
    public ToolsServerClient(string apiKey = null)
    {
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new Uri("http://localhost:5000/");
        _apiKey = apiKey;
        
        if (!string.IsNullOrEmpty(apiKey))
        {
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
        }
    }
    
    /// 
    /// Execute C# code on the server.
    /// 
    /// The C# code to execute
    /// The execution results
    public async Task ExecuteCSharpCodeAsync(string code)
    {
        var request = new ExecuteCSharpRequest
        {
            Code = code
        };
        
        var json = JsonSerializer.Serialize(request);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        
        var response = await _httpClient.PostAsync("tools-api/code/csharp", content);
        response.EnsureSuccessStatusCode();
        
        var responseBody = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize(responseBody, new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        });
    }
}

// Example usage
class Program
{
    static async Task Main(string[] args)
    {
        var client = new ToolsServerClient("your_api_key_here");
        
        try
        {
            // Example 1: Simple hello world
            var code = @"
using System;

public class Program
{
    public static object Main()
    {
        Console.WriteLine(""Hello from C#!"");
        return new { Message = ""Success"", Value = 42 };
    }
}";
            
            var result = await client.ExecuteCSharpCodeAsync(code);
            Console.WriteLine($"Success: {result.Success}");
            Console.WriteLine($"Message: {result.Message}");
            Console.WriteLine($"Result: {result.Result}");
            Console.WriteLine($"Timestamp: {result.Timestamp}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}
                    

Examples

Example 1: Simple Hello World

This example demonstrates a basic C# program that writes to the console and returns a simple object:

// Request
POST /tools-api/code/csharp
{
  "code": "using System;\n\npublic class Program\n{\n    public static object Main()\n    {\n        Console.WriteLine(\"Hello from C#!\");\n        return new { Message = \"Success\", Value = 42 };\n    }\n}"
}

// Response
{
  "success": true,
  "message": "Execution successful",
  "result": "Hello from C#!\n",
  "timestamp": "2025-01-01T12:00:00.000Z"
}
            

Example 2: Working with Windows UI Automation

This example demonstrates how to use the Windows UI Automation framework within the executed C# code:

// Request
POST /tools-api/code/csharp
{
  "code": "using System;\nusing System.Windows.Automation;\n\npublic class Program\n{\n    public static object Main()\n    {\n        // Get the desktop element\n        AutomationElement desktop = AutomationElement.RootElement;\n        \n        // Find all calculator windows\n        var condition = new PropertyCondition(AutomationElement.NameProperty, \"Calculator\");\n        AutomationElementCollection calculators = desktop.FindAll(TreeScope.Children, condition);\n        \n        // Return the count and information about found calculators\n        var count = calculators.Count;\n        Console.WriteLine($\"Found {count} calculator instances\");\n        \n        return new { CalculatorCount = count };\n    }\n}"
}

// Response
{
  "success": true,
  "message": "Execution successful",
  "result": "Found 1 calculator instances\n",
  "timestamp": "2025-01-01T12:00:00.000Z"
}
            
Important: The C# code execution has a default timeout of 30 seconds. Long-running operations may be terminated before completion.