### Configure Serilog and PostSharp Logging (Initial Setup) Source: https://doc.postsharp.net/logging/serilog Initial setup for Serilog and PostSharp Logging before collecting Serilog events. This configures Serilog and sets a basic PostSharp backend. ```csharp // Configure Serilog ILogger logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.ColoredConsole() .CreateLogger(); // Configure PostSharp Logging to use Serilog LoggingServices.DefaultBackend = new SerilogLoggingBackend(logger); // Emit manual log records. Note that this logger will skip PostSharp Logging, so indentation // will not be respected. logger.Information("Hello, world."); ``` -------------------------------- ### Initial NLog and PostSharp Logging Setup (for collection) Source: https://doc.postsharp.net/logging/nlog This initial setup configures NLog with an XML file and PostSharp Logging to use NLog. It's used before modifying to collect NLog events. ```csharp // Configure NLog var configuration = new XmlLoggingConfiguration("nlog.config"); LogManager.Configuration = configuration; // Set it as the default configuration LogManager.EnableLogging(); // Configure PostSharp Logging to use NLog LoggingServices.DefaultBackend = new NLogLoggingBackend(new LogFactory(configuration)); // Emit manual log records. Note that this logger will skip PostSharp Logging, so indentation // will not be respected. NLog.Logger logger = LogManager.GetCurrentClassLogger(); logger.Info().Message( "Hello, {color} sky!", "blue" ).Write(); ``` -------------------------------- ### Example: Log Warning for Empty URL Source: https://doc.postsharp.net/logging/log-custom-messages This example demonstrates logging a warning message when an empty URL is provided to a method. It includes necessary imports and LogSource initialization. ```csharp using PostSharp.Patterns.Diagnostics; using static PostSharp.Patterns.Diagnostics.FormattedMessageBuilder; static class Hasher { private static readonly LogSource logSource = LogSource.Get(); public static async Task ReadAndHashAsync(string url) { if ( string.IsNullOrEmpty( url ) ) { logSource.Warning.Write( Formatted( "Empty URL passed. Skipping this method." )); return; } // Details skipped. } } ``` -------------------------------- ### Example: Implement INotifyPropertyChanging with PostSharp Source: https://doc.postsharp.net/model/notifypropertychanged/inotifypropertychanging This example demonstrates a class implementing INotifyPropertyChanging, including the event declaration, the required OnPropertyChanging method, and the PostSharp attribute for property change notifications. ```csharp [NotifyPropertyChanged] public class MyClass : INotifyPropertyChanging { public event PropertyChangingEventHandler PropertyChanging; protected void OnPropertyChanging( string propertyName ) { if ( this.PropertyChanging != null ) { this.PropertyChanging( this, new PropertyChangingEventArgs ( propertyName ) ); } } public string MyProperty { get; set; } } ``` -------------------------------- ### Property Id Source: https://doc.postsharp.net/api/postsharp-patterns-caching-implementation-cachingbackend-id Gets the Guid of the current CachingBackend. ```APIDOC ## Property Id ### Description Gets the Guid of the current CachingBackend. ### Declaration ```csharp public Guid Id { get; } ``` ### Property Value | Type | Description | |---|---| | Guid | | ``` -------------------------------- ### Property StartColumn Source: https://doc.postsharp.net/api/postsharp-extensibility-messagelocation-startcolumn Gets the starting column in the file that caused the message. ```APIDOC ## Property StartColumn ### Description Gets the starting column in the file that caused the message. ### Declaration ```csharp public int StartColumn { get; } ``` ### Property Value Type | Description ---|--- int | ``` -------------------------------- ### GET Property SourceId Source: https://doc.postsharp.net/api/postsharp-patterns-caching-implementation-cacheitemremovedeventargs-sourceid Retrieves the Guid of the CachingBackend that triggered a removal event. ```APIDOC ## Property SourceId ### Description Gets the Guid of the CachingBackend that caused the removal, or Empty if it cannot be determined or does not apply. ### Declaration ```csharp public Guid SourceId { get; } ``` ### Property Value - **Type**: Guid - **Description**: The unique identifier of the CachingBackend. ``` -------------------------------- ### Method Initialize Source: https://doc.postsharp.net/api/postsharp-patterns-dynamicadvising-idynamicadvice-initialize Initializes the current advice. ```APIDOC ## Method Initialize ### Description Initializes the current advice. ### Declaration ```csharp void Initialize(IQueryInterface parent, AdviceEnumerator nextAdvice) ``` ### Parameters #### Path Parameters - **parent** (IQueryInterface) - Required - The parent, dynamically-advisable object. - **nextAdvice** (AdviceEnumerator) - Required - The next advice in the chain. ``` -------------------------------- ### BeginCustomRecord Method Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-applicationinsights-applicationinsightslogrecordbuilder Initializes the LogRecordBuilder to emit a custom log record. Requires a LoggingContext and a CustomLogRecordInfo. ```csharp BeginCustomRecord(LoggingContext, ref CustomLogRecordInfo) ``` -------------------------------- ### Get Parent Object Source: https://doc.postsharp.net/api/postsharp-patterns-model-iaggregatable-parent Retrieves the parent of the current object. No setup or imports are required. ```csharp object Parent { get; } ``` -------------------------------- ### Property SourceId Source: https://doc.postsharp.net/api/postsharp-patterns-caching-implementation-cachedependencyinvalidatedeventargs-sourceid Gets the Guid of the CachingBackend instance that requested the invalidation, or Empty if this information is not available. ```APIDOC ## Property SourceId ### Description Gets the Guid of the CachingBackend instance that requested the invalidation, or Empty if this information is not available. ### Declaration ```csharp public Guid SourceId { get; } ``` ### Property Value | Type | Description | |---|---| | Guid | | ``` -------------------------------- ### InitializeAdvices Method Source: https://doc.postsharp.net/api/postsharp-patterns-dynamicadvising-dynamicallyadvisableobject-initializeadvices Initializes the list of dynamic advices for the PostSharp framework. ```APIDOC ## InitializeAdvices(IExecuteActionDynamicAdvice) ### Description Initializes the list of dynamic advices. ### Method protected void ### Parameters #### Path Parameters - **advice** (IExecuteActionDynamicAdvice) - Required - The last advice in the chain of responsibility, which does the actual work. ### Request Example InitializeAdvices(myAdvice); ``` -------------------------------- ### GET Property StartLine Source: https://doc.postsharp.net/api/postsharp-extensibility-messagelocation-startline Retrieves the starting line number in the source file that triggered a message. ```APIDOC ## Property StartLine ### Description Gets the starting line in the file that caused the message. ### Declaration ```csharp public int StartLine { get; } ``` ### Property Value - **Type**: int - **Description**: The line number in the source file. ``` -------------------------------- ### Initialize CommonLoggingLoggingBackendOptions Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-commonlogging-commonloggingloggingbackendoptions--ctor Use this constructor to create a new instance of CommonLoggingLoggingBackendOptions. No specific setup is required beyond having the Common.Logging library available. ```csharp public CommonLoggingLoggingBackendOptions() ``` -------------------------------- ### CacheInvalidator Prefix Property Source: https://doc.postsharp.net/api/postsharp-patterns-caching-implementation-cacheinvalidatoroptions-prefix Gets or sets the prefix for messages sent by the CacheInvalidator. Messages not starting with this prefix are ignored by OnMessageReceived. ```csharp public string Prefix { get; set; } ``` -------------------------------- ### Get Default RedisCacheDependencyGarbageCollectorOptions Source: https://doc.postsharp.net/api/postsharp-patterns-caching-backends-redis-rediscachedependencygarbagecollectoroptions-default Retrieves the default configuration options for Redis cache dependency garbage collection. No specific setup is required to use this property. ```csharp public static RedisCacheDependencyGarbageCollectorOptions Default { get; } ``` -------------------------------- ### Initialize MultiplexerBackend Source: https://doc.postsharp.net/logging/log-multiplexer Configure PostSharp to use multiple logging backends by passing them to the MultiplexerBackend constructor. ```csharp // Set up the first logging backend (console): LoggingBackend backend1 = new ConsoleLoggingBackend(); // Set up the second logging backend: Gibraltar.Agent.Log.StartSession(); LoggingBackend backend2 = new ApplicationInsightsBackend(); // Configure PostSharp Logging to use both backends: LoggingServices.DefaultBackend = new MultiplexerBackend(backend1, backend2); ``` -------------------------------- ### Get IsZero Property Value Source: https://doc.postsharp.net/api/postsharp-aspects-constructordepth-iszero Retrieves the value of the IsZero property to check if the current depth is zero. No setup or imports are required beyond having an instance of the relevant object. ```csharp public bool IsZero { get; } ``` -------------------------------- ### Initialize Redis Cache Invalidation Source: https://doc.postsharp.net/caching/caching-pubsub This example demonstrates initializing an in-memory caching backend and configuring it to use Redis Pub/Sub for cache invalidation. Ensure you have StackExchange.Redis installed and a Redis server running. ```csharp var localCache = new MemoryCachingBackend(); string connectionConfiguration = "localhost"; string channelName = "myCahnnel"; ConnectionMultiplexer connection = ConnectionMultiplexer.Connect( connectionConfiguration ); var redisCacheInvalidatorOptions = new RedisCacheInvalidatorOptions { ChannelName = channelName }; CachingServices.DefaultBackend = RedisCacheInvalidator.Create( localCache, connection, redisCacheInvalidatorOptions ); ``` -------------------------------- ### Constructor AdviceArgs(object) Source: https://doc.postsharp.net/api/postsharp-aspects-adviceargs--ctor Initializes a new instance of the AdviceArgs class. ```APIDOC ## Constructor AdviceArgs(object) ### Description Initializes a new AdviceArgs instance. ### Parameters #### Path Parameters - **instance** (object) - Required - The instance related to the advice invocation, or null if the advice is associated to a static element of code. ### Request Example public AdviceArgs(object instance) ``` -------------------------------- ### Create PostSharp Configuration File Source: https://doc.postsharp.net/deploymentconfiguration/licensing/licensing-shared-source-code Create a basic postsharp.config file in your project or solution root if it does not already exist. ```xml ``` -------------------------------- ### Get Property Getter Delegate Source: https://doc.postsharp.net/api/postsharp-aspects-advices-property-2-get Gets a delegate to invoke the get accessor of an imported property. This is useful for accessing property values programmatically. ```csharp public PropertyGetter Get { get; } ``` -------------------------------- ### Configure ASP.NET Core Logging Source: https://doc.postsharp.net/logging/logging-aspnetcore Initial setup for ASP.NET Core logging within the CreateHostBuilder method. ```csharp public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(loggingBuilder => { loggingBuilder.ClearProviders(); loggingBuilder.AddConsole(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); ``` -------------------------------- ### Install PostSharp Unattended with PowerShell Source: https://doc.postsharp.net/deploymentconfiguration/deployment/postsharp-unattended This PowerShell script automates the installation of PostSharp Visual Studio Tools and configures the license key. Ensure the variables for the VSIX file path, license key, and VSIX installer path are correctly set before execution. The script checks for installation errors and updates the registry. ```powershell # TODO: Set the right value for the following variables # Replace with the proper version number and add the full path. $postsharpFile = "PostSharpMetalama.2024.1.11.vsix" # Replace by your license key or license server URL. $license = "XXXX-XXXXXXXXXXXXXXXXXXXXXXXXX" # Replace the path to the Visual Studio installation with the actual path on your system. $vsixInstaller = "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\IDE\VsixInstaller.exe" # Install Visual Studio Tools for Metalama and PostSharp Write-Host "Installing Visual Studio Tools for Metalama and PostSharp" $process = Start-Process -FilePath $vsixInstaller -ArgumentList @("/q", $postsharpFile) -Wait -PassThru if ( $process.ExitCode -ne 0 -and $process.ExitCode -ne 1001) { Write-Host "Error: VsixInstaller exited with code" $process.ExitCode -ForegroundColor Red } # Install the license key Write-Host "Installing the license key" $regPath = "HKCU:\Software\SharpCrafters\PostSharp 3" if ( -not ( Test-Path $regPath ) ) { New-Item -Path $regPath | Out-Null } Set-ItemProperty -Path $regPath -Name "LicenseKey" -Value $license Write-Host "Done" ``` -------------------------------- ### Property Get Accessor Source: https://doc.postsharp.net/api/postsharp-aspects-advices-property-1-get Provides a delegate to invoke the 'get' accessor of an imported property. ```APIDOC ## Property Get ### Description Gets a delegate enabling invocation of the **get** accessor of the imported property. ### Method GET (Implicit) ### Endpoint N/A (This is a property accessor, not a REST endpoint) ### Parameters None ### Request Body None ### Response #### Success Response (200) - **PropertyGetter** (Type) - A delegate to invoke the 'get' accessor. ### Response Example ```csharp // Example usage would depend on the context where PropertyGetter is used. // This is a property, not a direct API call. ``` ### Declaration ```csharp public PropertyGetter Get { get; } ``` ### Property Value | Type | Description | |---|---| | PropertyGetter | | ``` -------------------------------- ### Initialize Logging Configuration Source: https://doc.postsharp.net/logging/logging-aspnetcore Placeholder for logging initialization within the CreateHostBuilder method. ```csharp public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(loggingBuilder => { // Logging initialization code goes here. }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }); ``` -------------------------------- ### Constructor AdviceInstance() Source: https://doc.postsharp.net/api/postsharp-aspects-advices-adviceinstance--ctor Details the protected constructor for AdviceInstance. ```APIDOC ## Constructor AdviceInstance() ### Description Initializes a new instance of the `AdviceInstance` class. This constructor is intended for internal use within the PostSharp framework. ### Method protected ### Endpoint N/A (This is a constructor, not an API endpoint) ### Parameters This constructor does not accept any parameters. ### Request Example N/A ### Response N/A (Constructors do not return values in the traditional sense) ### Error Handling N/A ``` -------------------------------- ### Get Message Prefix (C#) Source: https://doc.postsharp.net/api/postsharp-extensibility-messagedispenser-prefix Use this property to get the message prefix. It is a read-only string. ```csharp public string Prefix { get; } ``` -------------------------------- ### BeginCustomRecord Method Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-applicationinsights-applicationinsightslogrecordbuilder-begincustomrecord Initializes the current LogRecordBuilder to emit a custom record. ```APIDOC ## BeginCustomRecord(LoggingContext, ref CustomLogRecordInfo) ### Description Initializes the current LogRecordBuilder to emit a custom record. ### Method `override void` ### Endpoint N/A (Method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (void) N/A #### Response Example None ``` -------------------------------- ### Get Property Accessor Delegate Source: https://doc.postsharp.net/api/postsharp-aspects-advices-property-1-get Provides a delegate to invoke the get accessor of an imported property. ```csharp public PropertyGetter Get { get; } ``` -------------------------------- ### Initialize CommonLoggingLoggingBackend Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-commonlogging-commonloggingloggingbackend--ctor Initializes a new CommonLoggingLoggingBackend. This constructor does not require any parameters. ```csharp public CommonLoggingLoggingBackend() ``` -------------------------------- ### Get Property Database Index Source: https://doc.postsharp.net/api/postsharp-patterns-caching-backends-redis-rediscachingbackendconfiguration-database Gets the index of the database to use. The default value is -1 (automatic selection). ```csharp public int Database { get; set; } ``` -------------------------------- ### Get or Set SyntheticIdMaxLength Property Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-loggingbackendoptions-syntheticidmaxlength Use this property to get or set the maximal length of the SyntheticId property. The value is an integer. ```csharp public int SyntheticIdMaxLength { get; set; } ``` -------------------------------- ### Initialize CacheKeyBuilder with advanced compression settings Source: https://doc.postsharp.net/api/postsharp-patterns-caching-implementation-cachekeybuilder--ctor Configures the builder with a maximum key size, a specific hashing algorithm, and a compression threshold. ```csharp public CacheKeyBuilder(int maxKeySize, CacheKeyHashingAlgorithm hashingAlgorithm, int keyCompressingThreshold = 0) ``` -------------------------------- ### Example Log Output Source: https://doc.postsharp.net/logging/logging-aspnetcore Sample output format for methods annotated with LogAttribute. ```text dbug: WebSite1.Pages.RazorPage1[2] RazorPage1.HelloWorld() | Starting. dbug: WebSite1.Pages.RazorPage1[4] RazorPage1.HelloWorld() | Succeeded. ``` -------------------------------- ### Get or Set IndentLevel Property Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-contexts-loggingcontext-indentlevel Use this property to get or set the indentation level for the current context. It is of type int. ```csharp public int IndentLevel { get; protected set; } ``` -------------------------------- ### Unsynchronized Order Class Example Source: https://doc.postsharp.net/threading/reader-writer-synchronized An example of a class susceptible to data races in a multithreaded environment due to lack of synchronization. ```csharp class Order { int Amount { get; private set; } int Discount { get; private set; } public int AmountAfterDiscount { get { return this.Amount - this.Discount; } } public void Set(int amount, int discount) { if (amount < discount) throw new InvalidOperationException(); this.Amount = amount; this.Discount = discount; } } ``` -------------------------------- ### Initialize ManagedResourceIntroductionAspectConfiguration Source: https://doc.postsharp.net/api/postsharp-aspects-configuration-managedresourceintroductionaspectconfiguration--ctor Constructors for configuring managed resource introduction aspects using either static data or a data provider delegate. ```csharp public ManagedResourceIntroductionAspectConfiguration(string name, byte[] data) ``` ```csharp public ManagedResourceIntroductionAspectConfiguration(string name, Func dataProvider) ``` -------------------------------- ### AdviceInstance Class Source: https://doc.postsharp.net/api/postsharp-aspects-advices-adviceinstance Documentation for the abstract base class AdviceInstance. ```APIDOC ## Class AdviceInstance ### Description Base class for advice instances, which can be provided dynamically by the aspect thanks to the IAdviceProvider interface. ### Inheritance object AdviceInstance ImportMemberAdviceInstance IntroduceInterfaceAdviceInstance IntroduceMemberAdviceInstance ### Namespace PostSharp.Aspects.Advices ### Assembly PostSharp.dll ### Syntax ```csharp public abstract class AdviceInstance ``` ### Remarks The only supported dynamic advice currently is ImportLocationAdviceInstance. ### Constructors #### AdviceInstance() Description: ### Properties #### Description (string) - A human-readable description of the current advice instance. #### LinesOfCodeAvoided (int) - The number of lines of hand-written code avoided by this specific AdviceInstance. #### MasterAspectMember (System.Reflection.MemberInfo) - Gets the main field or method of the aspect class that the current AdviceInstance relates to. ``` -------------------------------- ### Get or Set Property Reason Source: https://doc.postsharp.net/api/postsharp-extensibility-suppresswarningattribute-reason This property allows you to get or set a human-readable text explaining why a warning should be ignored. It is a string type. ```csharp public string Reason { get; set; } ``` -------------------------------- ### Sample NuGet Package Specification (.nuspec) Source: https://doc.postsharp.net/deploymentconfiguration/deployment/deployment-end-user This .nuspec file demonstrates how to specify PostSharp.Redist as a dependency for a NuGet package. This ensures that only the run-time libraries are included, not the build-time components. ```xml MyLibrary 1.0.0 John Smith John Smith false This is my library created with a help of PostSharp. ``` -------------------------------- ### Get or Set ObjectConstruction Property Source: https://doc.postsharp.net/api/postsharp-aspects-configuration-customattributeintroductionaspectconfiguration-objectconstruction Use this property to get or set the construction of the custom attribute that must be applied to the target of this aspect. ```csharp public ObjectConstruction ObjectConstruction { get; set; } ``` -------------------------------- ### Get or Set Profile Name Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-loggingprofile-name Gets or sets the name of the current profile. This name must match the constructor argument of the LogAttribute aspect. ```csharp public string Name { get; set; } ``` -------------------------------- ### Initialize ApplicationInsightsLoggingBackend Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-applicationinsights-applicationinsightsloggingbackend--ctor Constructors for creating an instance of the ApplicationInsightsLoggingBackend, with or without an explicit instrumentation key. ```csharp public ApplicationInsightsLoggingBackend() ``` ```csharp public ApplicationInsightsLoggingBackend(string instrumentationKey) ``` -------------------------------- ### Get Method Instance with Target Property Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-audit-auditrecord-target Use the Target property to get the instance on which a method was executed. It returns null for static methods. ```csharp public object Target { get; set; } ``` -------------------------------- ### Configure PostSharp Logging Build-Time Options Source: https://doc.postsharp.net/deploymentconfiguration/configuration/configuration-system Configure build-time options for PostSharp's logging feature. This example sets up a 'detailed' logging profile that includes source line information, execution time, and awaited task details. ```xml ``` -------------------------------- ### Get or Set MaxDelay Property Source: https://doc.postsharp.net/api/postsharp-patterns-caching-resilience-retrypolicy-maxdelay Use this property to get or set the maximum delay. It returns a TimeSpan value. An ArgumentOutOfRangeException may be thrown. ```csharp public TimeSpan MaxDelay { get; set; } ``` -------------------------------- ### Constructor TextLoggingBackend Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-textloggingbackend--ctor Initializes a new instance of the TextLoggingBackend class. ```APIDOC ## Constructor TextLoggingBackend ### Description Initializes a new instance of the TextLoggingBackend class. ### Method Constructor ### Declaration protected TextLoggingBackend() ``` -------------------------------- ### Initialize RedisCachingBackendConfiguration Source: https://doc.postsharp.net/api/postsharp-patterns-caching-backends-redis-rediscachingbackendconfiguration--ctor Use this constructor to create a new instance of RedisCachingBackendConfiguration. No specific setup is required beyond having the necessary PostSharp libraries available. ```csharp public RedisCachingBackendConfiguration() ``` -------------------------------- ### Get TransactionRetryPolicy Property Source: https://doc.postsharp.net/api/postsharp-patterns-caching-backends-redis-rediscachingbackendconfiguration-transactionretrypolicy Gets the IRetryPolicy that handles the retry loop of Redis transactions. The default value is the default instance of the TransactionRetryPolicy class. ```csharp public IRetryPolicy TransactionRetryPolicy { get; set; } ``` -------------------------------- ### Example output for async profiling Source: https://doc.postsharp.net/custompatterns/aspects/tutorials/method-decorator The expected console output after executing the profiled async method. ```text Method ProfilingTest executed for 1007ms. ``` -------------------------------- ### Get and Set AttributeTargetParameterAttributes Source: https://doc.postsharp.net/api/postsharp-extensibility-multicastattribute-attributetargetparameterattributes Gets or sets the passing style (by value, out or ref) of parameters to which this attribute applies. Ignored if the AttributeTargetElements do not include parameters. ```csharp public MulticastAttributes AttributeTargetParameterAttributes { get; set; } ``` -------------------------------- ### Get or Set MetadataEmitter Property Source: https://doc.postsharp.net/api/postsharp-serialization-portableformatter-metadataemitter Use this property to get or set the facility for serializing metadata objects as MSIL. This makes metadata transparent to obfuscation. ```csharp public IMetadataEmitter MetadataEmitter { get; set; } ``` -------------------------------- ### PostSharp Initialize Method Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-adapters-httpclient-httpclientlogging-initialize Instruments the PostSharp.Patterns.Diagnostics.Adapters.HttpClient class. ```APIDOC ## Initialize ### Description Instruments the PostSharp.Patterns.Diagnostics.Adapters.HttpClient class. ### Method `Initialize` ### Signature `public static IDisposable Initialize(ICorrelationProtocol correlationProtocol = null, Predicate requestUriPredicate = null)` ### Parameters #### Optional Parameters - **correlationProtocol** (ICorrelationProtocol) - An optional implementation of ICorrelationProtocol to support distributed logging and add relevant headers to outgoing requests. - **requestUriPredicate** (Predicate) - A predicate that determines whether a given outgoing request should be captured. If null, all requests are captured. ### Returns - **IDisposable** - An opaque token to dispose when instrumentation is no longer needed. ### Remarks It's the user's responsibility to call this method only once. ``` -------------------------------- ### Get or Set Enabled Record Kinds Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-loggingprofile-enabledrecordkinds Gets or sets the set of record kinds that are enabled for the given profile. Change it with care. Not all combinations are tested. ```csharp public LogRecordKind EnabledRecordKinds { get; set; } ``` -------------------------------- ### Constructor OnMethodEntryAdvice() Source: https://doc.postsharp.net/api/postsharp-aspects-advices-onmethodentryadvice--ctor Initializes a new instance of the OnMethodEntryAdvice class. ```APIDOC ## Constructor OnMethodEntryAdvice() ### Description Initializes a new instance of the OnMethodEntryAdvice class. ### Method Constructor ### Request Example public OnMethodEntryAdvice() ``` -------------------------------- ### Initialize Default Logging Backend Source: https://doc.postsharp.net/logging/add-logging Set the default logging backend at the beginning of your application's startup method. ```csharp LoggingServices.DefaultBackend = new PostSharp.Patterns.Diagnostics.Backends.Console.ConsoleLoggingBackend(); ``` -------------------------------- ### Handle Exceptions Aspect Source: https://doc.postsharp.net/custompatterns/aspects/tutorials/exception-handling This aspect intercepts exceptions, logs details to a trace file with a generated GUID, and re-throws a custom BusinessException containing the GUID. ```csharp [PSerializable] public sealed class HandleExceptionsAttribute : OnExceptionAspect { public override void OnException(MethodExecutionArgs args) { Guid guid = Guid.NewGuid(); // In a real-world app, we would file the exception in the QA database. Trace.WriteLine( "#Exception {guid}:"); Trace.WriteLine(args.Exception.ToString()); args.FlowBehavior = FlowBehavior.ThrowException; args.Exception = new BusinessException( $"The service failed unexpectedly. Please report the incident to the QA team with the id #{guid}." ); } } [HandleExceptions] public class BusinessServices { // Dozens of methods here. } public class BusinessException : Exception { public BusinessException(string message) : base(message) { } } ``` -------------------------------- ### Configuring Central Log Levels Source: https://doc.postsharp.net/logging/log-custom-messages Demonstrates how to define a prototype LogSource with custom default levels and reuse it across different classes. ```csharp using PostSharp.Patterns.Diagnostics; using static PostSharp.Patterns.Diagnostics.FormattedMessageBuilder; static class LogSources { // Configure a prototype LogSource that you will reuse in several classes. public static readonly LogSource Default = LogSource.Get().WithLevels( LogLevel.Trace, LogLevel.Warning ); } class MyClass { // Instantiates a LogSource from the prototype for the current type. static readonly LogSource logSource = LogSources.Default.ForCurrentType(); void MyMethod() { // Write a message with default verbosity. logSource.Default.Write( Formatted( "Hello, World." ) ); } } ``` -------------------------------- ### Get or Set DefaultValue Property Source: https://doc.postsharp.net/api/postsharp-patterns-xaml-dependencypropertyattribute-defaultvalue This property gets or sets the initial value of a dependency property and its metadata. Avoid using a property initializer if this property is set. ```csharp public object DefaultValue { get; set; } ``` -------------------------------- ### Initialize AdvisableDictionary with Capacity and Custom Comparer Source: https://doc.postsharp.net/api/postsharp-patterns-collections-advisabledictionary-2--ctor Creates an empty AdvisableDictionary with a specified initial capacity and a specified equality comparer for keys. ```csharp public AdvisableDictionary(int capacity, IEqualityComparer comparer) ``` -------------------------------- ### Get Property Id Declaration Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-contexts-loggingcontext-id This C# code shows the declaration of the 'Id' property, which is used to get or set the identifier of the current context. It is a read-only property. ```csharp public long Id { get; } ``` -------------------------------- ### Constructor LoggingBackend Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-loggingbackend--ctor Initializes a new instance of the LoggingBackend class. ```APIDOC ## Constructor LoggingBackend ### Description Initializes a new LoggingBackend. ### Declaration `protected LoggingBackend()` ``` -------------------------------- ### Get ConstructorDepth Zero Instance Source: https://doc.postsharp.net/api/postsharp-aspects-constructordepth-zero Access the static property 'Zero' to get a ConstructorDepth instance representing zero. This is useful for initializing or comparing ConstructorDepth values. ```csharp public static ConstructorDepth Zero { get; } ``` -------------------------------- ### Configure Console Logging Backend Source: https://doc.postsharp.net/logging/logging-console Initializes the console logging backend for the application. ```csharp using PostSharp.Patterns.Diagnostics; using PostSharp.Patterns.Diagnostics.Backends.Console; ``` ```csharp LoggingServices.DefaultBackend = new ConsoleLoggingBackend(); ``` -------------------------------- ### Get or Set SerializerType Source: https://doc.postsharp.net/api/postsharp-aspects-configuration-aspectconfigurationattribute-serializertype Gets or sets the Type of the serializer that will be used to configure the current aspect. The type assigned must derive from AspectSerializer and have a default constructor. ```csharp public Type SerializerType { get; set; } ``` -------------------------------- ### Default PostSharpHost.config Example Source: https://doc.postsharp.net/deploymentconfiguration/configuration/assembly-binding-resolution This is an example of the PostSharpHost.config file generated by PostSharp for an empty ASP.NET MVC 5 application, showing default assembly binding redirections. ```xml ``` -------------------------------- ### BeginRecord Method Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-applicationinsights-applicationinsightslogrecordbuilder Initializes the LogRecordBuilder to emit a standard log record for a given context and method. Requires LoggingContext, LogRecordInfo, and LogMemberInfo. ```csharp BeginRecord(LoggingContext, ref LogRecordInfo, ref LogMemberInfo) ``` -------------------------------- ### Get Dependency Property by Type and Name Source: https://doc.postsharp.net/api/postsharp-patterns-xaml-dependencypropertyservices-getdependencyproperty Use this overload to get a DependencyProperty when you have the type and the property name as strings. Ensure the type and property name are correctly specified. ```csharp public static DependencyProperty GetDependencyProperty(Type type, string propertyName) ``` -------------------------------- ### Constructor AuditBackend() Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-audit-auditbackend--ctor Initializes a new instance of the AuditBackend class. ```APIDOC ## Constructor AuditBackend() ### Description Initializes a new AuditBackend. ### Declaration ```csharp public AuditBackend() ``` ``` -------------------------------- ### Initialize EventSourceLoggingBackend with default source Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-eventsource-eventsourceloggingbackend--ctor Use this parameterless constructor to initialize the backend using the default event source. ```csharp public EventSourceLoggingBackend() ``` -------------------------------- ### Get Recorder Property Declaration Source: https://doc.postsharp.net/api/postsharp-patterns-recording-irecordable-recorder This C# code shows the declaration for the Recorder property. Getting this property automatically attaches the object to the default Recorder if it is not yet attached. ```csharp Recorder Recorder { get; set; } ``` -------------------------------- ### Get Operation Description as Text Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-audit-auditrecord-text Use the Text property to get a string describing the operation, typically including method type, name, and parameters. This property is read-write. ```csharp public string Text { get; set; } ``` -------------------------------- ### IntroduceInterfaceAdviceInstance Constructor Source: https://doc.postsharp.net/api/postsharp-aspects-advices-introduceinterfaceadviceinstance--ctor Initializes a new instance of the IntroduceInterfaceAdviceInstance class. Use this to specify the interface to introduce and how to handle existing implementations. ```csharp public IntroduceInterfaceAdviceInstance(Type interfaceType, InterfaceOverrideAction overrideAction = InterfaceOverrideAction.Default, InterfaceOverrideAction ancestorOverrideAction = InterfaceOverrideAction.Default) ``` -------------------------------- ### Initialize LoggingOptions Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-loggingoptions--ctor Use this constructor to create a new instance of LoggingOptions with default settings. ```csharp public LoggingOptions() ``` -------------------------------- ### Get or Set CreateSerializer Property Source: https://doc.postsharp.net/api/postsharp-patterns-caching-backends-redis-rediscachingbackendconfiguration-createserializer This property gets or sets a function that creates the serializer used for object serialization. The default value is null, which indicates that JsonCachingSerializer will be used. ```csharp public Func CreateSerializer { get; set; } ``` -------------------------------- ### Property Order Source: https://doc.postsharp.net/api/postsharp-aspects-moduleinitializerattribute-order Gets the order in which the ModuleInitializerAttribute will be executed if the current project contains several initializers. Initializers with smaller values of the Order property get invoked first. ```APIDOC ## Property Order ### Description Gets the order in which the ModuleInitializerAttribute will be executed if the current project contains several initializers. Initializers with smaller values of the Order property get invoked first. ### Declaration ```csharp public int Order { get; } ``` ### Property Value | Type | Description | |---|---| | int | | ``` -------------------------------- ### RuntimeInitialize Method Source: https://doc.postsharp.net/api/postsharp-aspects-ieventlevelaspect-runtimeinitialize Initializes the current aspect. ```APIDOC ## Method RuntimeInitialize ### Description Initializes the current aspect. ### Method void ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (void) This method does not return a value. #### Response Example None ### See Also Initializing Aspects ``` -------------------------------- ### Constructor VerbosityConfigurationModel() Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-transactions-model-verbosityconfigurationmodel--ctor Initializes a new instance of the VerbosityConfigurationModel class. ```APIDOC ## Constructor VerbosityConfigurationModel() ### Description Initializes a new instance of the VerbosityConfigurationModel class. ### Declaration ```csharp public VerbosityConfigurationModel() ``` ``` -------------------------------- ### Declare the Sample property Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-transactions-model-policyconfigurationmodel-sample This property returns a string representing the predicate logic for transaction logging. ```csharp public string Sample { get; } ``` -------------------------------- ### Get Dark ConsoleTheme Property Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-console-consolethemes-dark Accesses the static 'Dark' property of ConsoleTheme to get the dark theme. This theme is designed for black backgrounds and highlights parameters and return values. ```csharp public static ConsoleTheme Dark { get; } ``` -------------------------------- ### Method Initialize Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-adapters-aspnetcore-aspnetcorelogging-initialize Instruments the ASP.NET Core stack to define new logging activity and transactions for incoming HTTP requests. ```APIDOC ## Initialize ### Description Instruments the ASP.NET Core stack to define new logging activity (and possibly transactions) for incoming HTTP requests. ### Method Static Method ### Parameters - **correlationProtocol** (ICorrelationProtocol) - Optional - An optional implementation of ICorrelationProtocol to support distributed logging and interpret incoming request headers. - **filter** (Predicate) - Optional - An optional predicate that determines which requests must be captured. If that parameter is omitted, the paths `/lib`, `/css` and `/js` will be ignored. - **metadata** (LogEventMetadata) - Optional - An optional LogEventMetadata, which maps an HttpContext on a set of properties and an expression model. ### Returns - **IDisposable** - An opaque IDisposable that you can dispose to stop collecting logs from ASP.NET Core. ``` -------------------------------- ### Get or Set JitterFactor Property Source: https://doc.postsharp.net/api/postsharp-patterns-caching-resilience-retrypolicy-jitterfactor Use this property to get or set the jitter factor, a randomness value between 0 and 1. An ArgumentOutOfRangeException may be thrown if the value is outside this range. ```csharp public double JitterFactor { get; set; } ``` -------------------------------- ### Initialize CollectionDynamicAdvice Source: https://doc.postsharp.net/api/postsharp-patterns-collections-advices-collectiondynamicadvice-1--ctor Use this constructor to initialize a new instance of the CollectionDynamicAdvice class. It requires the parent object implementing IQueryInterface. ```csharp protected CollectionDynamicAdvice(IQueryInterface parent) ``` -------------------------------- ### Get or Set RemediationDelay Source: https://doc.postsharp.net/api/postsharp-patterns-caching-implementation-cachecleanupoptions-remediationdelay Gets or sets the delay between detecting an inconsistency and attempting remediation. The default value is 5 seconds. Useful for managing replication delays in distributed caching. ```csharp public TimeSpan RemediationDelay { get; set; } ``` -------------------------------- ### Get Logging Role Name Declaration Source: https://doc.postsharp.net/api/postsharp-patterns-caching-formatters-cachingformattingrole-loggingrole This C# code snippet shows the declaration of the public override string LoggingRole property. It is used to get the logging role name. ```csharp public override string LoggingRole { get; } ``` -------------------------------- ### Constructor ConsoleLoggingBackendOptions() Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-console-consoleloggingbackendoptions--ctor Initializes a new instance of the ConsoleLoggingBackendOptions class. ```APIDOC ## Constructor ConsoleLoggingBackendOptions() ### Description Initializes a new instance of the ConsoleLoggingBackendOptions class. ### Declaration ```csharp public ConsoleLoggingBackendOptions() ``` ``` -------------------------------- ### Get or Set Exception Property Source: https://doc.postsharp.net/api/postsharp-aspects-methodexecutionargs-exception This property is available within OnException advices. It allows you to get the thrown exception, replace it, or throw a new one by setting FlowBehavior to ThrowException. ```csharp public Exception Exception { get; set; } ``` -------------------------------- ### Constructor DictionaryDynamicAdvice Source: https://doc.postsharp.net/api/postsharp-patterns-collections-advices-dictionarydynamicadvice-2--ctor Initializes a new instance of the DictionaryDynamicAdvice class. ```APIDOC ## Constructor DictionaryDynamicAdvice ### Description Initializes a new DictionaryDynamicAdvice. ### Method Constructor ### Parameters #### Path Parameters - **parent** (IQueryInterface) - Required - Parent object. ### Request Example protected DictionaryDynamicAdvice(IQueryInterface parent) ``` -------------------------------- ### Initialize VerbosityConfigurationModel Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-transactions-model-verbosityconfigurationmodel--ctor Use the default constructor to create an instance of VerbosityConfigurationModel. ```csharp public VerbosityConfigurationModel() ``` -------------------------------- ### C# 14 Extension Block Example Source: https://doc.postsharp.net/custompatterns/aspects/applying/extension-blocks-multicast Demonstrates the syntax for defining C# 14 extension blocks with methods and properties. ```csharp public static class TestClassExtensions { extension(TInstance instance) { public TInstance ExtensionMethod() => instance; public TInstance ExtensionProperty => instance; } } ``` -------------------------------- ### Get or Set BackgroundTasksMaxConcurrency Source: https://doc.postsharp.net/api/postsharp-patterns-caching-backends-redis-rediscachingbackendconfiguration-backgroundtasksmaxconcurrency This property gets or sets the maximal number of concurrent background tasks. Keep this number low to avoid overloading the system or cache. The default value is 25. ```csharp public int BackgroundTasksMaxConcurrency { get; set; } ``` -------------------------------- ### Initialize ConsoleLoggingBackendOptions Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-console-consoleloggingbackendoptions--ctor Initializes a new instance of the ConsoleLoggingBackendOptions class. No specific setup is required beyond instantiating the object. ```csharp public ConsoleLoggingBackendOptions() ``` -------------------------------- ### Configure Trace and PostSharp Logging independently Source: https://doc.postsharp.net/logging/logging-trace Demonstrates a setup where Trace listeners and PostSharp logging are configured separately, noting that manual Trace logs will not respect PostSharp indentation. ```csharp // Add additional listeners: Trace.Listeners.Add( new ConsoleTraceListener() ); // Configure PostSharp Logging to use Trace: LoggingServices.DefaultBackend = new TraceLoggingBackend(); // Emit manual log records. Note that this logger will skip PostSharp Logging, so indentation // will not be respected. Trace.TraceError( "The {0} sky is shining {adverb}!", "blue", "bright" ); ``` -------------------------------- ### Get or Set SerializerType Source: https://doc.postsharp.net/api/postsharp-aspects-configuration-aspectconfiguration-serializertype Gets or sets the type of the serializer for aspect configuration. The assigned type must derive from AspectSerializer and have a default constructor. Use MsilAspectSerializer to specify MSIL construction. ```csharp public TypeIdentity SerializerType { get; set; } ``` -------------------------------- ### Initialize TextLoggingBackend Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-textloggingbackend--ctor Use this protected constructor when creating a derived class that needs to implement custom text logging behavior. No additional setup is required. ```csharp protected TextLoggingBackend() ``` -------------------------------- ### Get Property Value Declaration Source: https://doc.postsharp.net/api/postsharp-aspects-locationinitializationargs-value This C# code shows the declaration of the 'Value' property. It is used to get or set the initial value of a location, typically a field or property's backing field. ```csharp public override object Value { get; set; } ``` -------------------------------- ### TraceLoggingBackend Constructors Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-trace-traceloggingbackend Information on how to initialize a TraceLoggingBackend instance. ```APIDOC ### Constructors - **TraceLoggingBackend()**: Initializes a new TraceLoggingBackend that logs into Trace (the static trace source). - **TraceLoggingBackend(IEnumerable, string)**: Initializes a new TraceLoggingBackend that logs directly into the given trace listeners. ``` -------------------------------- ### IntroduceMethodAdviceInstance Constructor Source: https://doc.postsharp.net/api/postsharp-aspects-advices-introducemethodadviceinstance--ctor Initializes a new instance of the IntroduceMethodAdviceInstance class with specified method, visibility, virtual status, and override action. ```APIDOC ## IntroduceMethodAdviceInstance Constructor ### Description Initializes a new instance of the IntroduceMethodAdviceInstance class. ### Method Constructor ### Endpoint N/A (Class Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None (Constructor) #### Response Example None ``` -------------------------------- ### Get and Set SemanticallyAdvisedMethodKinds Source: https://doc.postsharp.net/api/postsharp-aspects-advices-onmethodboundaryadvice-semanticallyadvisedmethodkinds This property is used to get or set the SemanticallyAdvisedMethodKinds, which controls how methods are advised semantically. It affects iterator and async methods compiled into state machines. The default behavior is semantic advising. ```csharp public SemanticallyAdvisedMethodKinds SemanticallyAdvisedMethodKinds { get; set; } ``` -------------------------------- ### Constructor ProvideAspectRoleAttribute Source: https://doc.postsharp.net/api/postsharp-aspects-dependencies-provideaspectroleattribute--ctor Initializes a new instance of the ProvideAspectRoleAttribute class. ```APIDOC ## Constructor ProvideAspectRoleAttribute ### Description Initializes a new ProvideAspectRoleAttribute. ### Method Constructor ### Parameters #### Path Parameters - **role** (string) - Required - The role name to be assigned to the aspect. ``` -------------------------------- ### Get or Set BackgroundTasksOverloadedThreshold Source: https://doc.postsharp.net/api/postsharp-patterns-caching-backends-redis-rediscachingbackendconfiguration-backgroundtasksoverloadedthreshold Gets or sets the number of tasks over which the RedisCachingBackend notifies its state as overloaded. The default value is 125. The RedisCacheDependencyGarbageCollector component stops processing real-time eviction and expiration notifications when the component is overloaded. ```csharp public int BackgroundTasksOverloadedThreshold { get; set; } ``` -------------------------------- ### Constructor ConsoleLoggingBackend Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-console-consoleloggingbackend--ctor Initializes a new instance of the ConsoleLoggingBackend class. ```APIDOC ## Constructor ConsoleLoggingBackend ### Description Initializes a new instance of the ConsoleLoggingBackend class. ### Method Constructor ### Request Example public ConsoleLoggingBackend() ``` -------------------------------- ### RuntimeProperty Source: https://doc.postsharp.net/api/postsharp-patterns-xaml-attached-1-runtimeproperty Gets DependencyProperty registered in runtime. ```APIDOC ## Property RuntimeProperty ### Description Gets DependencyProperty registered in runtime. ### Declaration ```csharp public DependencyProperty RuntimeProperty { get; } ``` ### Property Value | Type | Description | |------------------|-------------| | DependencyProperty | | ``` -------------------------------- ### Property NewIndex Source: https://doc.postsharp.net/api/postsharp-patterns-recording-operations-icollectionoperation-newindex Gets the index after the operation. ```APIDOC ## Property NewIndex ### Description Gets the index after the operation. ### Declaration ```csharp int NewIndex { get; } ``` ### Property Value Type | Description ---|--- int | ``` -------------------------------- ### Method Initialize Source: https://doc.postsharp.net/api/postsharp-patterns-dynamicadvising-dynamicadvice-initialize Initializes the current advice within the PostSharp framework. This method is part of the IDynamicAdvice interface. ```APIDOC ## Method Initialize ### Description Initializes the current advice. ### Method `Initialize(IQueryInterface parent, AdviceEnumerator nextAdvice)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ### Declaration ```csharp public virtual void Initialize(IQueryInterface parent, AdviceEnumerator nextAdvice) ``` ### Parameters - **parent** (IQueryInterface) - Required - The parent, dynamically-advisable object. - **nextAdvice** (AdviceEnumerator) - Required - The next advice in the chain. ### Implements IDynamicAdvice.Initialize(IQueryInterface, AdviceEnumerator) ``` -------------------------------- ### Property OldItem Source: https://doc.postsharp.net/api/postsharp-patterns-recording-operations-hashsetoperation-1-olditem Gets the item after the operation. ```APIDOC ## Property OldItem ### Description Gets the item after the operation. ### Declaration ```csharp public virtual T OldItem { get; } ``` ### Property Value | Type | Description | |---|---| | T | | ``` -------------------------------- ### Configure NLog Targets and PostSharp Logging Backend Source: https://doc.postsharp.net/logging/nlog Sets up NLog to write logs to a file and the console, then configures PostSharp Logging to use NLog as its backend. Ensure NLog is enabled. ```csharp // Configure NLog. var nlogConfig = new LoggingConfiguration(); var fileTarget = new FileTarget("file") { FileName = "nlog.log", KeepFileOpen = true, ConcurrentWrites = false, }; nlogConfig.AddTarget(fileTarget); nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); var consoleTarget = new ConsoleTarget("console"); nlogConfig.AddTarget(consoleTarget); nlogConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); LogManager.EnableLogging(); // Configure PostSharp Logging to use NLog. LoggingServices.DefaultBackend = new NLogLoggingBackend(new LogFactory(nlogConfig)); ``` -------------------------------- ### Constructor IntroduceInterfaceAdviceInstance Source: https://doc.postsharp.net/api/postsharp-aspects-advices-introduceinterfaceadviceinstance--ctor Initializes a new instance of the IntroduceInterfaceAdviceInstance class with specified interface type and override actions. ```APIDOC ## Constructor IntroduceInterfaceAdviceInstance ### Description Initializes a new instance of the IntroduceInterfaceAdviceInstance class. ### Declaration ```csharp public IntroduceInterfaceAdviceInstance(Type interfaceType, InterfaceOverrideAction overrideAction = InterfaceOverrideAction.Default, InterfaceOverrideAction ancestorOverrideAction = InterfaceOverrideAction.Default) ``` ### Parameters - **interfaceType** (Type) - Required - Interface to introduce to the target class. Must be implemented by the aspect class itself. - **overrideAction** (InterfaceOverrideAction) - Optional - Specifies the action (Fail or Ignore) to be overtaken when the interface specified in the constructor of this custom attribute is already implemented by the type to which the current aspect is applied. - **ancestorOverrideAction** (InterfaceOverrideAction) - Optional - Specifies the action (Fail or Ignore) to be overtaken when an ancestor of the interface specified in the constructor of this custom attribute is already implemented by the type to which the current aspect is applied. ``` -------------------------------- ### Property OldIndex Source: https://doc.postsharp.net/api/postsharp-patterns-recording-operations-collectionoperation-1-oldindex Gets the index before the operation. ```APIDOC ## Property OldIndex ### Description Gets the index before the operation. ### Declaration ```csharp public virtual int OldIndex { get; } ``` ### Property Value Type | Description ---|--- int | ``` -------------------------------- ### Initialize Method Source: https://doc.postsharp.net/api/postsharp-extensibility-buildtimelogging-buildtimelogger-initialize Initializes the BuildTimeLogger facility with a specified set of enabled categories. ```APIDOC ## Initialize(IEnumerable) ### Description Initializes the BuildTimeLogger facility. This method sets the enabled categories for logging, which cannot be changed after initialization. ### Method Static Method ### Parameters #### Parameters - **enabledCategories** (IEnumerable) - Optional - The set of enabled categories. ### Request Example BuildTimeLogger.Initialize(new List { "Category1", "Category2" }); ``` -------------------------------- ### Backend Property Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-loggingnamespacesource-backend Gets the parent LoggingBackend. ```APIDOC ## Property Backend ### Description Gets the parent LoggingBackend. ### Declaration ```csharp public LoggingBackend Backend { get; } ``` ### Property Value Type | Description ---|--- LoggingBackend | ``` -------------------------------- ### AuditBackend.Backend Property Source: https://doc.postsharp.net/api/postsharp-patterns-diagnostics-backends-audit-auditrecordbuilder-backend Gets the current AuditBackend. ```APIDOC ## GET /api/audit/backend ### Description Gets the current AuditBackend. ### Method GET ### Endpoint /api/audit/backend ### Parameters #### Query Parameters None ### Request Body None ### Response #### Success Response (200) - **Backend** (AuditBackend) - The current AuditBackend instance. #### Response Example ```json { "Backend": { "//": "AuditBackend object details" } } ``` ``` -------------------------------- ### Initialize Method Declaration Source: https://doc.postsharp.net/api/postsharp-patterns-dynamicadvising-dynamicadvice-initialize Defines the signature for initializing dynamic advice within the PostSharp framework. ```csharp public virtual void Initialize(IQueryInterface parent, AdviceEnumerator nextAdvice) ``` -------------------------------- ### RedisCacheDependencyGarbageCollector Options Source: https://doc.postsharp.net/api/postsharp-patterns-caching-backends-redis-rediscachedependencygarbagecollector-options Gets the options for the RedisCacheDependencyGarbageCollector. ```APIDOC ## GET /api/options/redisCacheDependencyGarbageCollector ### Description Gets the options for the RedisCacheDependencyGarbageCollector. ### Method GET ### Endpoint /api/options/redisCacheDependencyGarbageCollector ### Parameters #### Query Parameters - **options** (RedisCacheDependencyGarbageCollectorOptions) - Required - The options for the garbage collector. ### Response #### Success Response (200) - **options** (RedisCacheDependencyGarbageCollectorOptions) - The options for the garbage collector. #### Response Example ```json { "options": { "//": "RedisCacheDependencyGarbageCollectorOptions details here" } } ``` ``` -------------------------------- ### CustomerService Class Example Source: https://doc.postsharp.net/custompatterns/aspects/method-interception A basic CustomerService class with a Save method. ```csharp public class CustomerService { public void Save(Customer customer) { // Database or web-service call. } } ```