### Manually Start Agent with NewRelic.StartAgent() Source: https://context7.com/newrelic/newrelic-dotnet-agent/llms.txt Starts the agent if it was not configured to auto-start (i.e., `autoStart="false"` in `newrelic.config`). Safe to call even if the agent is already running. ```csharp using NewRelic.Api.Agent; // In application startup, after any pre-initialization: public class Startup { public void Configure(IApplicationBuilder app) { // Ensure agent is running before serving traffic NewRelic.StartAgent(); app.UseRouting(); app.UseEndpoints(endpoints => endpoints.MapControllers()); } } ``` -------------------------------- ### Install aiohttp for Python Tests Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/docs/integration-tests.md Install the aiohttp library using pip for Python-based integration tests. ```bash pip install aiohttp ``` -------------------------------- ### Start Unbounded Integration Test Infrastructure Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/claude.md Before running unbounded integration tests, ensure the necessary infrastructure containers are running. Navigate to the integration tests directory and start the Docker Compose services. ```bash cd tests/Agent/IntegrationTests/UnboundedServices docker compose up -d ``` -------------------------------- ### Prepare for Comparison Run Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/PerformanceTests/README.md Copy an example configuration file to 'compare.yml' to set up a performance comparison run. This file should then be edited with specific test parameters. ```bash cp compare.example.yml compare.yml ``` -------------------------------- ### Build Profiler for Windows x64 Debug Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/docs/development.md Example of building the profiler in debug mode specifically for Windows x64 architecture. ```powershell build.ps1 -Platform x64 -Configuration Debug ``` -------------------------------- ### Run All Docker Services Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/IntegrationTests/UnboundedServices/README.md Starts all containerized services required for the unbounded integration tests. This can take a significant amount of time and system resources. ```bash docker compose up ``` -------------------------------- ### Method Naming Conventions Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/CONTRIBUTING.md Methods should be named using PascalCase, and parameters should use camelCase. Example shows a private string method. ```csharp private string GetUserNameFromId(int userId) ``` -------------------------------- ### Run Individual Docker Service Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/IntegrationTests/UnboundedServices/README.md Starts a specific containerized service. Replace `` with the name of the desired service, as listed in the docker-compose.yml file. ```bash docker compose up ``` -------------------------------- ### Copy Local Profiler DLL for Testing Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/docs/development.md Example of copying a locally built profiler DLL to the agent's home directory for testing. This overwrites the NuGet version. ```powershell # Example shown for the Windows 64-bit profiler, testing with the Windows CoreCLR (.NET Core/.NET) version of the agent copy C:\workspace\newrelic-dotnet-agent\src\Agent\_profilerBuild\x64-Release\NewRelic.Profiler.dll C:\workspace\newrelic-dotnet-agent\src\Agent\newrelichome_x64_coreclr\ ``` -------------------------------- ### Run Unbounded Integration Tests Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/claude-tests.md Execute unbounded integration tests after starting the required services. ```powershell dotnet test tests/Agent/IntegrationTests/UnboundedIntegrationTests/UnboundedIntegrationTests.csproj ``` -------------------------------- ### NewRelic.StartAgent() Source: https://context7.com/newrelic/newrelic-dotnet-agent/llms.txt Manually starts the New Relic agent. This is useful if the agent was not configured to auto-start (e.g., `autoStart="false"` in `newrelic.config`). It is safe to call this method even if the agent is already running. ```APIDOC ## NewRelic.StartAgent() ### Description Starts the agent if it was not configured to auto-start (i.e., `autoStart="false"` in `newrelic.config`). Safe to call even if the agent is already running. ### Method ```csharp NewRelic.StartAgent() ``` ### Request Example ```csharp // In application startup, after any pre-initialization: public class Startup { public void Configure(IApplicationBuilder app) { // Ensure agent is running before serving traffic NewRelic.StartAgent(); app.UseRouting(); app.UseEndpoints(endpoints => endpoints.MapControllers()); } } ``` ``` -------------------------------- ### Run S3 Indexer Tool Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/deploy/linux/deploy_scripts/s3-index/README.md Use this command to run the S3 indexer tool directly using Go. Ensure you have the AWS SDK for Go installed. ```sh GOPATH=$(pwd) go run src/indexer/main.go ``` -------------------------------- ### Method with Annotation Source: https://github.com/newrelic/newrelic-dotnet-agent/wiki/Agent-Coding-Standards Methods can be marked with annotations, such as [Serializable], placed on the line before the property definition. This example shows a method with the [Serializable] attribute. ```cs [Serializable] public string ToEncodedAppDataHttpHeader(bool shouldrecordTransactionTrace = false) { if (string.IsNullOrEmpty(TransactionName)) throw new ArgumentException("TransactionName must be set prior to calling ToEncodedAppDataHttpHeader"); var appDataJson = ToAppDataJsonString(); Log.DebugFormat("Creating {0} header with data: {1}", AppDataHttpHeader, appDataJson); return Strings.Base64Encode(appDataJson, EncodingKey); } ``` -------------------------------- ### Invoking a Library Method Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/IntegrationTests/SharedApplications/ConsoleMultiFunctionApplicationFW/README.md Invoke a library method by specifying the library name, method name, and any required parameters. This example demonstrates calling the 'Test' method of the 'PerformanceMetrics' library. ```bash 10:04:28 AM >PerformanceMetrics Test 4 282 123 10:04:53 AM :EXECUTING: 'PerformanceMetrics Test 4 282 123' 10:04:53 AM :Setting Threadpool Max Threads: 282 worker/123 completion. 10:04:53 AM :Instrumented Method to start the Agent 10:04:54 AM :Forcing a GC.Collect 10:04:55 AM :Forcing a GC.Collect 10:04:56 AM :Forcing a GC.Collect 10:04:57 AM :Forcing a GC.Collect 10:04:58 AM > ``` -------------------------------- ### Basic MVC Integration Test Example Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/claude-tests.md Demonstrates a typical integration test structure using NUnit for an ASP.NET MVC application. It checks for a successful HTTP response and verifies that a specific web transaction metric is logged by the agent. ```csharp public class BasicMvcTests : NewRelicIntegrationTest { private readonly AspNetFrameworkBasicMvcApplication _fixture; public BasicMvcTests() => _fixture = new AspNetFrameworkBasicMvcApplication(); [Test] public void HomeIndexCreatesWebTransaction() { var result = _fixture.Get("Home/Index"); var metrics = _fixture.AgentLog.GetMetrics(); Assert.Multiple(() => { Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK)); Assert.That(metrics, Does.Contain("WebTransaction/MVC/Home/Index")); }); } } ``` -------------------------------- ### Example of Injected Code for Method Instrumentation Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/README.md This pseudo-code illustrates the logic injected into methods to capture tracing information. It includes error handling for tracer retrieval and invocation, and ensures the original method's return value or exception is preserved. ```cs try { try { // GetTracer is invoked reflectively by calling Assembly.LoadFrom(path), Type.GetMethod(..) finishTracerDelegate = AgentShim.GetFinishTracerDelegate(tracerFactoryName, tracerFactoryArgs, metricName, assemblyName, type, typeName, functionName, argumentSignatureString, this, /**/); } catch (Exception) {} // original method body here, with RET instruction changed to NOP result = // return value of original method or null for VOID } catch (Exception ex) { try { // the finish delegate is directly invoked as an `Action` delegate if the CLR > 2 finishTracerDelegate(null, ex); } catch (Exception) {} rethrow; } try { finishTracerDelegate(result, null); } catch (Exception) {} return result; ``` -------------------------------- ### Abstract Base Test Fixture with Dynamic Method Invocation Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/IntegrationTests/SharedApplications/ConsoleMultiFunctionApplicationCore/README.md Create an abstract generic test fixture that inherits from NewRelicIntegrationTest and accepts a ConsoleDynamicMethodFixture type parameter. Use Fixture.AddCommand() to register commands to invoke, and Fixture.Actions() to configure setup callbacks before test execution. ```csharp public abstract class DotNetPerfMetricsTests : NewRelicIntegrationTest where TFixture:ConsoleDynamicMethodFixture { public DotNetPerfMetricsTests(TFixture fixture, ITestOutputHelper output) { Fixture = fixture; Fixture.TestLogger = output; /////////////////////////////////////////////////////////////////////////////////////// //Here is where you would add the commands you would like to invoke //You can add as many as you want. /////////////////////////////////////////////////////////////////////////////////////// Fixture.AddCommand($"PerformanceMetrics Test {COUNT_GC_INDUCED} {THREADPOOL_WORKER_MAX} {THREADPOOL_COMPLETION_MAX}"); Fixture.Actions ( setupConfiguration: () => { Fixture.RemoteApplication.NewRelicConfig.SetLogLevel("finest"); } ); Fixture.Initialize(); } [Fact] public void Test1() { ... } } public class DotNetPerfMetricsTestsCore : DotNetPerfMetricsTests {} public class DotNetPerfMetricsTestsFW : DotNetPerfMetricsTests {} ``` -------------------------------- ### Configure New Relic Agent Log Directory Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/Miscellaneous/azure-app-services.md Specify the directory where the New Relic agent should write its log files by modifying the `newrelic.config` file. This example sets the log directory to `D:\Home\LogFiles\NewRelic`. ```xml ``` -------------------------------- ### Minimal C# Wrapper Implementation Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/claude-source.md Provides a basic C# implementation of the IWrapper interface for custom instrumentation. Use 'true' for IsTransactionRequired if the wrapper only adds a segment to an existing transaction; use 'false' if the wrapper should start a new transaction. ```csharp public class MyFrameworkWrapper : IWrapper { // true = wrapper is skipped if no transaction is in progress // (use when the wrapper only adds a segment to an existing tx) // false = wrapper runs regardless; typically it creates a transaction // itself (entry points: request handlers, message consumers, // lambda handlers, background job starts) public bool IsTransactionRequired => true; public CanWrapResponse CanWrap(InstrumentedMethodInfo methodInfo) => new CanWrapResponse(methodInfo.RequestedWrapperName == nameof(MyFrameworkWrapper)); public AfterWrappedMethodDelegate BeforeWrappedMethod( InstrumentedMethodInfo methodInfo, IAgent agent, ITransaction transaction) { var segment = transaction.StartTransactionSegment( methodInfo.MethodCall, "MyFramework"); return Delegates.GetDelegateFor(segment); } } ``` -------------------------------- ### Displaying Help and Usage Information Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/IntegrationTests/SharedApplications/ConsoleMultiFunctionApplicationFW/README.md Use the 'Help', 'Usage', or '?' command to display a list of registered libraries, their available methods, and required parameters. This is useful for understanding the application's capabilities. ```bash $ dotnet run --framework netcoreapp2.2 Console Multi Function Application Process Info: dotnet 5880 10:00:00 AM >usage 10:00:02 AM :USAGE: 10:00:02 AM : 10:00:02 AM :Here's a list of registered Library Methods: 10:00:02 AM : 10:00:02 AM : PERFORMANCEMETRICS 10:00:02 AM : 10:00:02 AM : PerformanceMetrics Test {countGCCollect:Int32} {countMaxWorkerThreads:Int32} {countMaxCompletionThreads:Int32} 10:00:02 AM : 10:00:02 AM : SAMPLELIBRARY 10:00:02 AM : 10:00:02 AM : SampleLibrary SampleLibrarymethod {howManyTimes:Int32} 10:00:02 AM : 10:00:02 AM > ``` -------------------------------- ### Configure Docker Buildx Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/IntegrationTests/ContainerApplications/CustomBaseContainerBuild/README.md Set up Docker's buildx plugin to enable multi-platform builds. This command creates and selects a new builder instance. ```bash docker buildx create --use ``` -------------------------------- ### xml_base::parent Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Gets the parent of the node. Returns a pointer to the parent of the node, or 0 if there is no parent. ```APIDOC ## xml_base::parent ### Description Gets parent of the node. ### Returns Pointer to the parent of the node, or 0 if there is no parent. ### Synopsis `xml_base* parent() const;` ``` -------------------------------- ### Build and Push Fedora Base Images Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/IntegrationTests/ContainerApplications/CustomBaseContainerBuild/README.md Build custom Fedora base images with specified .NET versions and push them to the container registry for both amd64 and arm64 architectures. ```bash docker buildx build --build-arg BASE_IMAGE="fedora:latest" --build-arg DOTNET_VERSION="8.0" --build-arg DOTNET_QUALITY="GA" -f Dockerfile.CustomBaseImage --tag $acrName/fedora-aspnet:8.0 --platform linux/amd64,linux/arm64/v8 --push . ``` ```bash docker buildx build --build-arg BASE_IMAGE="fedora:latest" --build-arg DOTNET_VERSION="10.0" --build-arg DOTNET_QUALITY="GA" -f Dockerfile.CustomBaseImage --tag $acrName/fedora-aspnet:10.0 --platform linux/amd64,linux/arm64/v8 --push . ``` -------------------------------- ### Build Profiler for All Platforms (Release) Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/docs/development.md Build the profiler in release mode for all target platforms. Docker Desktop is required for building the Linux binary. ```powershell build.ps1 ``` -------------------------------- ### xml_attribute::document Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Gets the document of which the attribute is a child. Returns a pointer to the document that contains this attribute, or 0 if there is no parent document. ```APIDOC ## xml_attribute::document ### Description Gets document of which attribute is a child. ### Returns Pointer to document that contains this attribute, or 0 if there is no parent document. ### Synopsis `xml_document* document() const;` ``` -------------------------------- ### Compact Namespaces in C++ Source: https://github.com/newrelic/newrelic-dotnet-agent/wiki/Agent-Coding-Standards Use compact namespaces for C++ code to improve readability. This deviates from the WebKit style guide. ```c++ namespace NewRelic { namespace Profiler { namespace Logger }}} OR namespace NewRelic::Profiler::Logger { ... } ``` -------------------------------- ### xml_attribute::next_attribute Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Gets the next attribute, optionally matching the attribute name. Returns a pointer to the found attribute, or 0 if not found. ```APIDOC ## xml_attribute::next_attribute ### Description Gets next attribute, optionally matching attribute name. ### Parameters - **name** (const Ch *) - Name of attribute to find, or 0 to return next attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero - **name_size** (std::size_t) - Size of name, in characters, or 0 to have size calculated automatically from string - **case_sensitive** (bool) - Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters ### Returns Pointer to found attribute, or 0 if not found. ### Synopsis `xml_attribute* next_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;` ``` -------------------------------- ### Run Performance Comparison Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/PerformanceTests/README.md Execute the performance comparison runner script with a specified configuration file. ```bash python run-perf-comparison.py --config compare.yml ``` -------------------------------- ### xml_attribute::previous_attribute Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Gets the previous attribute, optionally matching the attribute name. Returns a pointer to the found attribute, or 0 if not found. ```APIDOC ## xml_attribute::previous_attribute ### Description Gets previous attribute, optionally matching attribute name. ### Parameters - **name** (const Ch *) - Name of attribute to find, or 0 to return previous attribute regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero - **name_size** (std::size_t) - Size of name, in characters, or 0 to have size calculated automatically from string - **case_sensitive** (bool) - Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters ### Returns Pointer to found attribute, or 0 if not found. ### Synopsis `xml_attribute* previous_attribute(const Ch *name=0, std::size_t name_size=0, bool case_sensitive=true) const;` ``` -------------------------------- ### Generate Configuration.cs with Xsd2Code Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/build/Tools/xsd2code/README.md Run this PowerShell command from the repository root to generate the Configuration.cs file from its XSD. Ensure Xsd2Code is accessible in the build tools directory. ```powershell $rootDirectory = Resolve-Path ".\"; .\build\Tools\xsd2code\xsd2code.exe "$rootDirectory\src\Agent\NewRelic\Agent\Core\Config\Configuration.xsd" NewRelic.Agent.Core.Config Configuration.cs /cl /ap /sc /xa ``` -------------------------------- ### Compare.yml Configuration Structure Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/PerformanceTests/README.md Define test parameters, including duration, user load, and .NET version, along with configurations for multiple agent runs. ```yaml test: duration: 2m locust_users: 10 locust_spawn_rate: 2 dotnet_version: "10.0" runs: - label: no-agent attach_agent: false - label: latest-release attach_agent: true agent_source: type: github_artifact # or: local, url run_id: 12345678901 # all_solutions.yml run ID - label: local-build attach_agent: true agent_env: NEW_RELIC_LOG_LEVEL: debug agent_source: type: local path: /path/to/newrelichome_x64_coreclr_linux ``` -------------------------------- ### Add GPG Signing Keys Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/deploy/linux/README.md Place the necessary GPG signing keys into the `./deploy_scripts` subfolder. These keys are required for signing the packages during deployment. ```bash cp private-key-1.gpg ./deploy_scripts cp private-key-2.gpg ./deploy_scripts ``` -------------------------------- ### Run All Docker Services in Background Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/IntegrationTests/UnboundedServices/README.md Starts all containerized services in detached mode, allowing you to continue using the terminal without following the service output. ```bash docker compose up -d ``` -------------------------------- ### xml_node::previous_sibling Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Gets the previous sibling node, optionally matching a specific name. It's important to check if the node has a parent before calling this function. ```APIDOC ## xml_node::previous_sibling ### Description Gets previous sibling node, optionally matching node name. Behaviour is undefined if node has no parent. Use [parent()](#classrapidxml_1_1xml__base_798e8df7ea53ade4d9f0701017dce80e_1798e8df7ea53ade4d9f0701017dce80e) to test if node has a parent. ### Parameters * **name** (const Ch *) - Name of sibling to find, or 0 to return previous sibling regardless of its name; this string doesn't have to be zero-terminated if name_size is non-zero * **name_size** (std::size_t) - Size of name, in characters, or 0 to have size calculated automatically from string * **case_sensitive** (bool) - Should name comparison be case-sensitive; non case-sensitive comparison works properly only for ASCII characters ### Returns Pointer to found sibling, or 0 if not found. ``` -------------------------------- ### Create Docker Environment File Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/deploy/linux/README.md Create and populate the `docker.env` file with required environment variables for the Docker deployment. Ensure all values, especially sensitive ones like keys and version numbers, are correct. ```bash echo "AGENT_VERSION=10.0.0" >docker.env echo "S3_BUCKET=s3://your-s3-bucket" >>docker.env echo "AWS_ACCESS_KEY_ID=AKAKAKAKAKAKAKA" >>docker.env echo "AWS_SECRET_ACCESS_KEY=6SQ6SQ6SQ6SQ6SQ6SQ6SQ6SQ6SQ6SQ6SQ" >>docker.env echo "OLD_PRIVATE_KEY=/data/deploy_scripts/private-key-1.gpg" >> docker.env echo "NEW_PRIVATE_KEY=/data/deploy_scripts/private-key-2.gpg" >> docker.env echo "NEW_PRIVATE_KEY_PASSPHRASE=xxxxxxxxxxxxxx" >> docker.env echo "OLD_KEY_ID="0123456789ABCFEF" >> docker.env echo "NEW_KEY_ID="FEDCBA9876543210" >> docker.env ``` -------------------------------- ### xml_base::value_size Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Gets the size of the node value, not including the terminator character. This function works correctly irrespective of whether the value is or is not zero terminated. ```APIDOC ## xml_base::value_size ### Description Gets size of node value, not including terminator character. This function works correctly irrespective of whether value is or is not zero terminated. ### Synopsis `std::size_t value_size() const;` ``` -------------------------------- ### xml_base::name_size Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Gets the size of the node name, not including the terminator character. This function works correctly irrespective of whether the name is or is not zero terminated. ```APIDOC ## xml_base::name_size ### Description Gets size of node name, not including terminator character. This function works correctly irrespective of whether name is or is not zero terminated. ### Synopsis `std::size_t name_size() const;` ``` -------------------------------- ### Interface Declaration with Generics and Constraints Source: https://github.com/newrelic/newrelic-dotnet-agent/wiki/Agent-Coding-Standards Define interfaces using PascalCase prefixed with 'I'. This example shows a generic interface with a type constraint and a method signature. ```cs public interface IAttributeFilter where T : IAttribute { string MyString; IEnumerable FilterAttributes([NotNull] IEnumerable attributes, AttributeDestinations destination); } ``` -------------------------------- ### Build Core.UnitTest Project with SolutionDir Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/claude.md When building or testing the Core.UnitTest project from the CLI, explicitly pass the SolutionDir path to MSBuild. This is required because plain `dotnet` does not set it, unlike Visual Studio. ```powershell $sln = "$((Resolve-Path .).Path)\" dotnet build tests/Agent/UnitTests/Core.UnitTest/Core.UnitTest.csproj ` -f net10.0 -p:SolutionDir="$sln" dotnet test tests/Agent/UnitTests/Core.UnitTest/Core.UnitTest.csproj ` -f net10.0 -p:SolutionDir="$sln" ` --filter "FullyQualifiedName~SomeTest" ``` -------------------------------- ### Build Profiler Script Syntax Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/docs/development.md Use this Powershell script to build the native profiler component. Specify platform and configuration options as needed. ```powershell ./build.ps1 [-Platform ] [-Configuration ] ``` -------------------------------- ### Variable Naming Conventions: Constant Fields Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/CONTRIBUTING.md Use PascalCase for constant fields and public class-level fields. Example shows a private constant string. ```csharp private const string MyConst = "NewRelic"; ``` -------------------------------- ### WIX Component for Wrapper Assembly Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Agent/Extensions/Providers/Wrapper/README.md Defines a WIX component to include the custom wrapper DLL in the agent installation. Replace `{name_of_your_wrapper}` with the actual name of your wrapper. ```xml ``` -------------------------------- ### Configure .NET Core / .NET 5+ Agent via Environment Variables Source: https://context7.com/newrelic/newrelic-dotnet-agent/llms.txt Environment variables for enabling and configuring the .NET Core / .NET 5+ agent. Essential for containerized deployments where newrelic.config may not be used. ```bash # .NET Core / .NET 5+ export CORECLR_ENABLE_PROFILING=1 export CORECLR_PROFILER={36032161-FFC0-4B61-B559-F6C5D41BAE5A} export CORECLR_PROFILER_PATH=/opt/newrelic/libNewRelicProfiler.so export CORECLR_NEWRELIC_HOME=/opt/newrelic export NEW_RELIC_LICENSE_KEY=your_license_key_here export NEW_RELIC_APP_NAME="MyApp;AllApps" export NEW_RELIC_DISTRIBUTED_TRACING_ENABLED=true export NEW_RELIC_LOG_LEVEL=info ``` -------------------------------- ### Simple Class Declaration Source: https://github.com/newrelic/newrelic-dotnet-agent/wiki/Agent-Coding-Standards Classes should be written in PascalCase and be singular. Use this for simple POCOs. ```cs public class ClassTitle { // ... } ``` -------------------------------- ### Print XML Document to Output Streams with RapidXML Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Demonstrates various methods for printing an XML document to standard output or a string using RapidXML's print function or the overloaded '<<' operator. Flags can be used to control printing behavior. ```cpp using namespace rapidxml; xml_document<> doc; // character type defaults to char // ... some code to fill the document // Print to stream using operator << std::cout << doc; // Print to stream using print function, specifying printing flags print(std::cout, doc, 0); // 0 means default printing flags ``` ```cpp // Print to string using output iterator std::string s; print(std::back_inserter(s), doc, 0); ``` ```cpp // Print to memory buffer using output iterator char buffer[4096]; // You are responsible for making the buffer large enough! char *end = print(buffer, doc, 0); // end contains pointer to character after last printed character *end = 0; // Add string terminator after XML ``` -------------------------------- ### WIX Component for Wrapper Instrumentation File Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Agent/Extensions/Providers/Wrapper/README.md Defines a WIX component to include the custom XML instrumentation file in the agent installation. Replace `{name_of_your_wrapper}` with the actual name of your wrapper. ```xml ``` -------------------------------- ### Build RPM Package Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/build/Linux/linux_packaging.md Creates an RPM package for Red Hat-based systems. Ensure Docker Compose is built first. ```bash docker compose run build_rpm ``` -------------------------------- ### Running Integration Tests with Settings File Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/claude-tests.md Configure test execution parameters such as timeout and parallelization using a `test.runsettings` file. ```powershell dotnet test --settings test.runsettings ``` -------------------------------- ### NewRelic Static Class Methods Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/tests/Agent/UnitTests/PublicApiChangeTests/PublicApiTest.PublicApiHasNotChanged.verified.txt Provides static methods for interacting with the New Relic agent, such as starting the agent, setting application names, recording metrics, and reporting errors. ```APIDOC ## NewRelic Static Class ### Description Provides static methods for interacting with the New Relic agent. ### Methods - `StartAgent()`: Initializes the New Relic agent. - `GetAgent()`: Returns an instance of the `IAgent` interface. - `SetApplicationName(string applicationName, string? applicationName2 = null, string? applicationName3 = null)`: Sets the application name for reporting. - `GetBrowserTimingHeader()`: Gets the JavaScript snippet for browser monitoring. - `GetBrowserTimingHeader(string nonce)`: Gets the JavaScript snippet for browser monitoring with a nonce. - `DisableBrowserMonitoring(bool overrideManual = false)`: Disables browser monitoring. - `IgnoreApdex()`: Ignores the current transaction for Apdex calculation. - `IgnoreTransaction()`: Ignores the current transaction. - `IncrementCounter(string name)`: Increments a custom counter metric. - `NoticeError(System.Exception exception)`: Reports an exception to New Relic. - `NoticeError(System.Exception exception, System.Collections.Generic.IDictionary? parameters)`: Reports an exception with additional parameters. - `NoticeError(System.Exception exception, System.Collections.Generic.IDictionary? parameters)`: Reports an exception with string parameters. - `NoticeError(string message, System.Collections.Generic.IDictionary? parameters)`: Reports a message with additional parameters. - `NoticeError(string message, System.Collections.Generic.IDictionary? parameters)`: Reports a message with string parameters. - `NoticeError(string message, System.Collections.Generic.IDictionary? parameters, bool isExpected)`: Reports a message with parameters and expected status. - `NoticeError(string message, System.Collections.Generic.IDictionary? parameters, bool isExpected)`: Reports a message with string parameters and expected status. - `RecordCustomEvent(string eventType, System.Collections.Generic.IEnumerable> attributes)`: Records a custom event. - `RecordMetric(string name, float value)`: Records a custom metric. - `RecordResponseTimeMetric(string name, long millis)`: Records a response time metric. - `SetErrorGroupCallback(System.Func, string> callback)`: Sets a callback for error grouping. - `SetLlmTokenCountingCallback(System.Func callback)`: Sets a callback for LLM token counting. - `SetTransactionName(string? category, string name)`: Sets the name of the current transaction. - `SetTransactionUri(System.Uri uri)`: Sets the URI for the current transaction. - `SetUserParameters(string? userName, string? accountName, string? productName)`: Sets user-related parameters for the transaction. - `GetRequestMetadata()`: Gets metadata for the current request. - `GetResponseMetadata()`: Gets metadata for the current response. - `RecordLlmFeedbackEvent(string traceId, object rating, string category = "", string message = "", System.Collections.Generic.IDictionary? metadata = null)`: Records an LLM feedback event. ``` -------------------------------- ### Generate Extension.cs with Xsd2Code Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/build/Tools/xsd2code/README.md Execute this PowerShell command from the repository root to generate the Extension.cs file from its XSD. This command is similar to the Configuration.cs generation but targets the Extension XSD. ```powershell $rootDirectory = Resolve-Path ".\"; .\build\Tools\xsd2code\xsd2code.exe "$rootDirectory\src\Agent\NewRelic\Agent\Core\Extension\Extension.xsd" NewRelic.Agent.Core.Extension Extension.cs /cl /ap /sc /xa ``` -------------------------------- ### Configure .NET Framework Agent via Environment Variables Source: https://context7.com/newrelic/newrelic-dotnet-agent/llms.txt Environment variables for enabling and configuring the .NET Framework agent. Essential for containerized deployments where newrelic.config may not be used. ```bash # .NET Framework export COR_ENABLE_PROFILING=1 export COR_PROFILER={71DA0A04-7777-4EC6-9643-7D28B46A8A41} export COR_PROFILER_PATH=/opt/newrelic/NewRelic.Profiler.dll export NEWRELIC_HOME=/opt/newrelic export NEWRELIC_LICENSE_KEY=your_license_key_here ``` -------------------------------- ### Obtain IAgent Instance and Access Transaction/Span Data Source: https://context7.com/newrelic/newrelic-dotnet-agent/llms.txt Get the singleton IAgent instance to access the current transaction, span, and trace metadata. Linking metadata can be retrieved for log correlation. ```csharp using NewRelic.Api.Agent; // In any instrumented method or service: IAgent agent = NewRelic.GetAgent(); ITransaction currentTransaction = agent.CurrentTransaction; ISpan currentSpan = agent.CurrentSpan; ITraceMetadata metadata = agent.TraceMetadata; Dictionary linkingMetadata = agent.GetLinkingMetadata(); Console.WriteLine($"TraceId: {metadata.TraceId}"); Console.WriteLine($"SpanId: {metadata.SpanId}"); Console.WriteLine($"Sampled: {metadata.IsSampled}"); // linkingMetadata can be added to log events for log-in-context correlation foreach (var kv in linkingMetadata) logger.LogInformation("{Key}={Value}", kv.Key, kv.Value); ``` -------------------------------- ### Run Integration Tests on Linux VM Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/docs/integration-tests.md Execute integration tests on a Linux environment using `dotnet test`. Ensure the agent repository is copied to the VM and specify the target framework and runtime. ```bash cd {DOTNET_AGENT_REPO_PATH}/tests/Agent/IntegrationTests/IntegrationTests sudo dotnet test -f net10.0 -c Release --filter RuntimeFramework=NetCore ``` -------------------------------- ### Field Usage with `this` Keyword in C# Source: https://github.com/newrelic/newrelic-dotnet-agent/wiki/Agent-Coding-Standards Shows an example where using the `this` keyword to access a field can be potentially dangerous if a parameter has the same name, leading to ambiguity. Omitting `this` might encourage better design. ```cs public class MyClass { public MyClass() {} public int MyPublicID = 0; private void SetMyPubilcID(int MyPublicID) { this.MyPublicID = MyPublicID; ... } } ``` -------------------------------- ### Attach .NET Framework Agent Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/claude.md Environment variables for attaching the .NET Framework profiler. Ensure COR_PROFILER_PATH points to the correct NewRelic.Profiler.dll and NEWRELIC_HOME is set. ```bash COR_ENABLE_PROFILING=1 COR_PROFILER={71DA0A04-7777-4EC6-9643-7D28B46A8A41} COR_PROFILER_PATH=\NewRelic.Profiler.dll NEWRELIC_HOME= NEWRELIC_LICENSE_KEY=... ``` -------------------------------- ### Build DEB Package Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/build/Linux/linux_packaging.md Creates a DEB package for Debian-based systems. Ensure Docker Compose is built first. ```bash docker compose run build_deb ``` -------------------------------- ### xml_base::value Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Gets the value of the node. Interpretation of value depends on type of node. Note that value will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. Use value_size() function to determine the length of the value. ```APIDOC ## xml_base::value ### Description Gets value of the node. Interpretation of value depends on type of node. Note that value will not be zero-terminated if [rapidxml::parse_no_string_terminators](#namespacerapidxml_9cae3801e70437cbc410c24bf6be691c_19cae3801e70437cbc410c24bf6be691c) option was selected during parse. Use [value_size()](#classrapidxml_1_1xml__base_aed5ae791b7164c1ee5e649198cbb3db_1aed5ae791b7164c1ee5e649198cbb3db) function to determine length of the value. ### Returns Value of node, or empty string if node has no value. ### Synopsis `Ch* value() const;` ``` -------------------------------- ### xml_base::name Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Gets the name of the node. Interpretation of name depends on the type of node. Note that the name will not be zero-terminated if rapidxml::parse_no_string_terminators option was selected during parse. Use name_size() function to determine the length of the name. ```APIDOC ## xml_base::name ### Description Gets name of the node. Interpretation of name depends on type of node. Note that name will not be zero-terminated if [rapidxml::parse_no_string_terminators](#namespacerapidxml_9cae3801e70437cbc410c24bf6be691c_19cae3801e70437cbc410c24bf6be691c) option was selected during parse. Use [name_size()](#classrapidxml_1_1xml__base_0dae694c8f7e4d89f1003e2f3a15a43c_10dae694c8f7e4d89f1003e2f3a15a43c) function to determine length of the name. ### Returns Name of node, or empty string if node has no name. ### Synopsis `Ch* name() const;` ``` -------------------------------- ### Create and Modify XML Elements with RapidXML Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/src/Agent/NewRelic/Profiler/RapidXML/manual.html Shows how to create new XML nodes and attributes using RapidXML's allocation functions. It's important to allocate strings from the document's memory pool for proper lifetime management. ```cpp xml_document<> doc; xml_node<> *node = doc.allocate_node(node_element, "a", "Google"); doc.append_node(node); xml_attribute<> *attr = doc.allocate_attribute("href", "google.com"); node->append_attribute(attr); ``` ```cpp xml_document<> doc; char *node_name = doc.allocate_string(name); // Allocate string and copy name into it xml_node<> *node = doc.allocate_node(node_element, node_name); // Set node name to node_name ``` -------------------------------- ### Full Powershell Script for Windows Features Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/docs/integration-tests.md This comprehensive PowerShell script enables a wide range of IIS and MSMQ features required for .NET integration testing. Run this script to ensure all necessary Windows features are installed. ```powershell Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServer Enable-WindowsOptionalFeature -Online -FeatureName IIS-NetFxExtensibility45 Enable-WindowsOptionalFeature -Online -FeatureName IIS-ApplicationDevelopment Enable-WindowsOptionalFeature -Online -FeatureName IIS-CommonHttpFeatures Enable-WindowsOptionalFeature -Online -FeatureName IIS-DefaultDocument Enable-WindowsOptionalFeature -Online -FeatureName IIS-DirectoryBrowsing Enable-WindowsOptionalFeature -Online -FeatureName IIS-HealthAndDiagnostics Enable-WindowsOptionalFeature -Online -FeatureName IIS-HostableWebCore Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpCompressionStatic Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpErrors Enable-WindowsOptionalFeature -Online -FeatureName IIS-HttpLogging Enable-WindowsOptionalFeature -Online -FeatureName IIS-ISAPIExtensions Enable-WindowsOptionalFeature -Online -FeatureName IIS-ISAPIFilter Enable-WindowsOptionalFeature -Online -FeatureName IIS-ManagementConsole Enable-WindowsOptionalFeature -Online -FeatureName IIS-Performance Enable-WindowsOptionalFeature -Online -FeatureName IIS-RequestFiltering Enable-WindowsOptionalFeature -Online -FeatureName IIS-Security Enable-WindowsOptionalFeature -Online -FeatureName IIS-StaticContent Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerManagementTools Enable-WindowsOptionalFeature -Online -FeatureName IIS-WebServerRole Enable-WindowsOptionalFeature -Online -FeatureName MSMQ-Container Enable-WindowsOptionalFeature -Online -FeatureName MSMQ-Multicast Enable-WindowsOptionalFeature -Online -FeatureName MSMQ-Server Enable-WindowsOptionalFeature -Online -FeatureName MSMQ-Triggers Enable-WindowsOptionalFeature -Online -FeatureName MSRDC-Infrastructure Enable-WindowsOptionalFeature -Online -FeatureName WCF-Services45 Enable-WindowsOptionalFeature -Online -FeatureName WCF-TCP-PortSharing45 Enable-WindowsOptionalFeature -Online -FeatureName IIS-ASPNET45 ``` -------------------------------- ### Build Profiler for Linux Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/docs/development.md Build the profiler for Linux. This requires Docker Desktop and will build the profiler within a Linux container. ```powershell build.ps1 -Platform linux ``` -------------------------------- ### Build Docker Container Source: https://github.com/newrelic/newrelic-dotnet-agent/blob/main/deploy/linux/README.md Build the Docker container using `docker compose build`. This command prepares the container environment for the deployment process. ```bash docker compose build ```