### Usage Example for ValueRangeAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-value-analysis.md Illustrates specifying allowed value ranges for integral types using ValueRangeAttribute. The example shows a warning for an expression that is always false due to the specified range. ```csharp void Foo([ValueRange(0, 100)] int value) { if (value == -1) // Warning: Expression is always 'false' { ... } } ``` -------------------------------- ### Source Template Method Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-source-templates.md Example of a source template method for iterating over an IEnumerable. It uses special comments starting with '$' for code injection and template parameters like '$END$' for caret placement. ```csharp [SourceTemplate] public static void forEach(this IEnumerable xs) { foreach (var x in xs) { //$ $END$ } } ``` -------------------------------- ### AspMvcActionAttribute Usage Examples Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc.md Illustrates how to use the AspMvcActionAttribute in custom HtmlHelpers and Controller actions. ```csharp public class HtmlHelpers { public static string RenderAction(this HtmlHelper helper, [AspMvcAction] string actionName) { return RenderAction(helper, actionName, null); } public static string RenderAction(this HtmlHelper helper, [AspMvcAction("action")] object routeValues) { // routeValues.action contains the action name } } public class HomeController : Controller { public ActionResult Index() => View(); [AspMvcAction] public ActionResult GetProductList() => View(); } ``` -------------------------------- ### AspMvcAreaAttribute Usage Examples Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc.md Demonstrates how to use the AspMvcAreaAttribute to specify MVC areas in method parameters, both directly and via anonymous objects. ```csharp public class RouteHelper { public static string GenerateUrl([AspMvcArea] string area, string controller, string action) { // area specifies the MVC area } public static string GenerateUrl([AspMvcArea("area")] object routeValues) { // routeValues.area contains area name } } ``` -------------------------------- ### Usage Example for ValueProviderAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-value-analysis.md Demonstrates how to use ValueProviderAttribute to enable IDE completion suggestions based on constant values defined in a specified type. ```csharp namespace TestNamespace { public class Constants { public static int INT_CONST = 1; public const string STRING_CONST = "1"; } public class Class1 { [ValueProvider("TestNamespace.Constants")] public int myField; public void Foo([ValueProvider("TestNamespace.Constants")] string str) { } public void Test() { Foo(/*try completion here*/); myField = /*try completion here*/ } } } ``` -------------------------------- ### Usage Examples for MustDisposeResourceAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-resource-disposal.md Demonstrates how to apply MustDisposeResourceAttribute to types and factory methods, and shows the expected IDE warnings for unhandled resource disposal. ```csharp [MustDisposeResource] public class FileReader : IDisposable { public void Dispose() { ... } } public class Factory { [MustDisposeResource] public FileReader CreateReader() { ... } } void Usage() { using (var reader = new FileReader()) // OK { // use reader } var reader2 = new FileReader(); // Warning: not disposed } ``` -------------------------------- ### Usage of NoReorderAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-nostructure.md Example demonstrating how to apply the NoReorderAttribute to a class to preserve the declaration order of its members. ```csharp [NoReorder] public class OrderedClass { public void Method1() { } public void Method2() { } public void Method3() { } // Member order will not be changed by IDE reordering } ``` -------------------------------- ### Assertion Method Usage Examples Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-method-behavior.md Demonstrates how to use the AssertionConditionAttribute with assertion methods. The first example asserts a boolean condition is true, and the second asserts an object is not null. ```csharp [AssertionMethod] public static void Assert([AssertionCondition(AssertionConditionType.IS_TRUE)] bool condition) { if (!condition) throw new AssertionException(); } [AssertionMethod] public static void AssertNotNull([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] object obj) { if (obj == null) throw new AssertionException(); } ``` -------------------------------- ### Usage Example for CodeTemplateAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-language-injection.md Demonstrates how to apply the CodeTemplateAttribute to a class to find a specific code pattern and suggest a replacement using nameof. ```csharp [CodeTemplate( searchTemplate: "$obj.ToString()", message: "Use nameof instead", replaceTemplate: "nameof($obj)", replaceMessage: "Replace with nameof")] public class UseNameofExample { } ``` -------------------------------- ### PathReferenceAttribute Usage Examples Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-paths-uri.md Demonstrates how to use PathReferenceAttribute to mark parameters and properties for IDE navigation and validation. Supports project root and web root resolution. ```csharp public class FileManager { public void LoadFile([PathReference] string filePath) { // filePath is a path reference with IDE support } public void LoadFromFolder([PathReference("~/Data")] string relativePath) { // relativePath is resolved relative to ~/Data folder } [PathReference] public string ConfigPath { get; set; } } ``` -------------------------------- ### Usage Example for ProvidesContextAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-collections.md Illustrates applying the ProvidesContextAttribute to a field, signaling that other methods of obtaining the same type of value should defer to this marked member. This helps in centralizing context-dependent service access. ```csharp class Foo { [ProvidesContext] IBarService _barService = ...; void ProcessNode(INode node) { DoSomething(node, node.GetGlobalServices().Bar); // ^ Warning: use value of '_barService' field } } ``` -------------------------------- ### RazorDirectiveAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-razor-xaml.md Shows how to use the RazorDirectiveAttribute in AssemblyInfo.cs to include directives such as @using System.Linq and @using MyProject.Models. ```csharp // In AssemblyInfo.cs [assembly: RazorDirective("@using System.Linq")] [assembly: RazorDirective("@using MyProject.Models")] ``` -------------------------------- ### Usage Example for NonNegativeValueAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-value-analysis.md Shows the application of NonNegativeValueAttribute to integral values that are guaranteed to be non-negative. The example highlights a warning for an expression that is always false. ```csharp void Foo([NonNegativeValue] int value) { if (value == -1) // Warning: Expression is always 'false' { ... } } ``` -------------------------------- ### AspMvcViewAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc.md Shows how to use the AspMvcViewAttribute with an extension method to render an MVC view, ensuring the provided view name is valid. ```csharp public class ControllerHelper { public static ViewResult RenderView(this Controller controller, [AspMvcView] string viewName) { return controller.View(viewName); } } public class HomeController : Controller { public ActionResult Index() { return this.RenderView("Index"); // viewName must be valid view } } ``` -------------------------------- ### Usage of AspMinimalApiImplicitEndpointDeclarationAttribute for GET and POST Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-minimal-api.md Shows how to use AspMinimalApiImplicitEndpointDeclarationAttribute to define GET and POST endpoints with route templates, query parameters, and request body types. ```csharp public class UserService { [AspMinimalApiImplicitEndpointDeclaration( HttpVerb = "GET", RouteTemplate = "/api/users/{id}", QueryParameters = "includeInactive")] public IResult GetUser(int id, bool includeInactive = false) => Results.Ok(new { Id = id }); [AspMinimalApiImplicitEndpointDeclaration( HttpVerb = "POST", RouteTemplate = "/api/users", BodyType = typeof(CreateUserRequest))] public IResult CreateUser([FromBody] CreateUserRequest request) => Results.Created("/api/users/1", new { }); } public class CreateUserRequest { public string Name { get; set; } public string Email { get; set; } } ``` -------------------------------- ### Apply AspMvcViewComponentViewLocationFormatAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc-locations.md Example of applying the AspMvcViewComponentViewLocationFormatAttribute at the assembly level to specify a custom view component view location format. ```csharp [assembly: AspMvcViewComponentViewLocationFormat("~/Views/Components/{0}/Default.cshtml")] ``` -------------------------------- ### Example Usage of DefaultEqualityUsageAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-usage-analysis.md Demonstrates how to apply the DefaultEqualityUsageAttribute to generic type parameters, method parameters, and return values to signal the use of default equality. This can help in identifying potential issues where custom equality might be expected but not provided. ```csharp struct StructWithDefaultEquality { /* no Equals & GetHashCode override */ } class MySet<[DefaultEqualityUsage] T> { ... } static class Extensions { public static MySet ToMySet<[DefaultEqualityUsage] T>(this IEnumerable items) { ... } } class MyList { public int IndexOf([DefaultEqualityUsage] T item) { ... } } class UsesDefaultEquality { void Test() { var list = new MyList(); list.IndexOf(new StructWithDefaultEquality()); // Warning var set1 = new MySet(); // Warning var set2 = new StructWithDefaultEquality[1].ToMySet(); // Warning } } ``` -------------------------------- ### Usage Example for InvokerParameterNameAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-value-analysis.md Demonstrates the use of InvokerParameterNameAttribute on string parameters that must reference parameter names of the calling method. The example shows a warning for an unresolved symbol. ```csharp void Foo(string param) { if (param == null) throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol } ``` -------------------------------- ### RazorPageBaseTypeAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-razor-xaml.md Example of how to apply the RazorPageBaseTypeAttribute in AssemblyInfo.cs to set global or specific Razor page base types. ```csharp // In AssemblyInfo.cs [assembly: RazorPageBaseType("MyProject.Views.RazorPageBase")] [assembly: RazorPageBaseType("MyProject.Views.AdminPage", "Admin/*")] ``` -------------------------------- ### NotNullAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-nullability.md Shows the usage of NotNullAttribute on a method return value, highlighting the warning generated when attempting to return null. ```csharp [NotNull] object Foo() { return null; // Warning: Possible 'null' assignment } ``` -------------------------------- ### Usage of AspRouteConventionAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Demonstrates how to use the AspRouteConventionAttribute to mark methods that configure routing conventions. The first example uses the attribute without a predefined pattern, while the second specifies a pattern for area-based routing. ```csharp [AspRouteConvention] public void ConfigureRoutes(IEndpointRouteBuilder endpoints) { endpoints.MapControllerRoute( name: "default", pattern: "{controller}/{action}/{id?}"); } [AspRouteConvention("{area}/{controller}/{action}")] public void ConfigureAreaRoutes(IEndpointRouteBuilder endpoints) { // Predefined pattern for area-based routing } ``` -------------------------------- ### MacroAttribute Applied to Template Method Parameter Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-source-templates.md Example of applying MacroAttribute directly to a template method parameter. The 'guid()' macro is used for the 'newguid' parameter, marked as non-editable. ```csharp [SourceTemplate] public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) { /*$ var $x$Id = "$newguid$" + x.ToString(); x.DoSomething($x$Id); */ } ``` -------------------------------- ### Enforcing Allocation-Free Delegates Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-resource-disposal.md Demonstrates how to apply RequireStaticDelegateAttribute to a method parameter and shows examples of valid and invalid delegate usage. ```csharp public class EventLoop { public void Schedule([RequireStaticDelegate] Action callback) { // Expects allocation-free delegate } } void Example() { int localVar = 0; eventLoop.Schedule(() => Console.WriteLine("OK")); // OK - no captures eventLoop.Schedule(() => Console.WriteLine(localVar)); // Warning - captures local void LocalFunction() { } eventLoop.Schedule(LocalFunction); // Warning - always allocates } ``` -------------------------------- ### CanBeNullAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-nullability.md Demonstrates how to use CanBeNullAttribute on a method return value and the potential null reference exception when dereferencing a possibly null object. ```csharp [CanBeNull] object Test() { ... } void UseTest() { var p = Test(); var s = p.ToString(); // Warning: Possible 'System.NullReferenceException' ``` -------------------------------- ### Usage of CqrsCommandHandlerAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-cqrs-testing.md Example of applying the CqrsCommandHandlerAttribute to a class that handles CQRS commands. Demonstrates potential warnings for using queries within command handlers. ```csharp [CqrsCommandHandler] public class UserCommandHandler { public void Handle(SetUserNameCommand command) { var query = new GetUserNameQuery() { Id = command.Id }; // Warning about Query use inside Command var handler = new UserQuery(); // Warning about using Query inside Command if (command.Name == handler.Handle(query)) // Warning about using Query inside Command return; // ... } } ``` -------------------------------- ### LinqTunnelAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-method-behavior.md Illustrates how LinqTunnelAttribute is applied to a LINQ extension method that defers enumeration. ```csharp [LinqTunnel] public static IEnumerable Where(this IEnumerable source, Func predicate) { // postponed enumeration } ``` -------------------------------- ### Usage of CqrsQueryHandlerAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-cqrs-testing.md Example of applying the CqrsQueryHandlerAttribute to a class that handles CQRS queries. Shows a read-only operation for retrieving user data. ```csharp [CqrsQueryHandler] public class UserQueryHandler { public User Handle(GetUserByIdQuery query) { // Read-only operation, no state modification return database.Users.FirstOrDefault(u => u.Id == query.Id); } } ``` -------------------------------- ### MustUseReturnValueAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-method-behavior.md Demonstrates how to apply the MustUseReturnValueAttribute to methods. Use the justification parameter for methods that require a specific check, and IsFluentBuilderMethod for fluent builder patterns. ```csharp [MustUseReturnValue("Check the result")] bool TryOperation() { ... } [MustUseReturnValue(IsFluentBuilderMethod = true)] public Builder WithName(string name) { this.Name = name; return this; } ``` -------------------------------- ### RazorInjectionAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-razor-xaml.md Demonstrates how to apply the RazorInjectionAttribute in AssemblyInfo.cs to inject services like UrlHelper and a custom UserService into Razor views. ```csharp // In AssemblyInfo.cs [assembly: RazorInjection("System.Web.Mvc.UrlHelper", "Url")] [assembly: RazorInjection("MyProject.Services.IUserService", "UserService")] ``` -------------------------------- ### UriStringAttribute Usage Examples Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-paths-uri.md Illustrates using UriStringAttribute to enable URI-specific IDE features like syntax highlighting and validation. Supports generic URIs and specific HTTP verbs. ```csharp public class HttpClient { public void Get([UriString("GET")] string url) { // url is treated as a URI with GET verb } public async Task FetchAsync([UriString("POST")] string endpoint) { // endpoint is a POST URI } [UriString] public string BaseUrl { get; set; } } ``` -------------------------------- ### AspMvcDisplayTemplateAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc.md Illustrates how to use the AspMvcDisplayTemplateAttribute in an MVC HtmlHelper extension method to specify a display template name. ```csharp public class HtmlHelper { public static MvcHtmlString DisplayTemplate([AspMvcDisplayTemplate] string templateName, object model) { // templateName specifies the display template } } ``` -------------------------------- ### AspMvcPartialViewAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc.md Demonstrates how to use the AspMvcPartialViewAttribute on a parameter in a custom extension method for HtmlHelper to render a partial view. This helps in statically analyzing partial view names. ```csharp public class ViewHelper { public static string RenderPartialView(this HtmlHelper helper, [AspMvcPartialView] string partialViewName) { return helper.Partial(partialViewName).ToString(); } } public class MyView { @{ Html.RenderPartialView("_Header"); } // _Header must be valid partial view } ``` -------------------------------- ### HtmlElementAttributesAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-razor-xaml.md Demonstrates how to use HtmlElementAttributesAttribute to specify that a dictionary contains attributes for a specific HTML element like 'div'. ```csharp public class HtmlBuilder { public void AddAttributes([HtmlElementAttributes("div")] IDictionary attributes) { // attributes dictionary will have div-specific attributes } } ``` -------------------------------- ### NoEnumerationAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-method-behavior.md Demonstrates using NoEnumerationAttribute on a parameter to suppress 'Possible multiple enumeration of IEnumerable' warnings. ```csharp static void ThrowIfNull([NoEnumeration] T v, string n) where T : class { // custom check for null but no enumeration } void Foo(IEnumerable values) { ThrowIfNull(values, nameof(values)); var x = values.ToList(); // No warnings about multiple enumeration } ``` -------------------------------- ### ItemCanBeNullAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-nullability.md Demonstrates using ItemCanBeNullAttribute on a List parameter, highlighting the potential for null reference exceptions when accessing items. ```csharp public void Foo([ItemCanBeNull]List books) { foreach (var book in books) { // Warning: Possible 'System.NullReferenceException' Console.WriteLine(book.ToUpper()); } } ``` -------------------------------- ### AssertionMethodAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-method-behavior.md Shows how to apply the AssertionMethodAttribute to methods that terminate control flow based on a condition, similar to assertion statements. ```csharp [AssertionMethod] public static void Assert(bool condition, string message) { if (!condition) throw new AssertionException(message); } ``` -------------------------------- ### AspMvcEditorTemplateAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc.md Demonstrates the usage of the AspMvcEditorTemplateAttribute within an MVC HtmlHelper extension method for specifying an editor template name. ```csharp public class HtmlHelper { public static MvcHtmlString EditorTemplate([AspMvcEditorTemplate] string templateName, object model) { // templateName specifies the editor template } } ``` -------------------------------- ### Usage Example for CollectionAccessAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-collections.md Demonstrates how to use the CollectionAccessAttribute to specify read-only access to a collection's elements. This helps static analysis tools warn about unintended modifications. ```csharp public class MyStringCollection : List { [CollectionAccess(CollectionAccessType.Read)] public string GetFirstString() { return this.ElementAt(0); } } class Test { public void Foo() { // Warning: Contents of the collection is never updated var col = new MyStringCollection(); string x = col.GetFirstString(); } } ``` -------------------------------- ### AspMvcMasterAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc.md Shows how to use the AspMvcMasterAttribute on a parameter within a custom controller extension method. This facilitates static analysis for master view names when rendering views. ```csharp public class ViewHelper { public static ViewResult RenderViewWithMaster(this Controller controller, string viewName, [AspMvcMaster] string masterName) { return controller.View(viewName, masterName); } } ``` -------------------------------- ### ItemNotNullAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-nullability.md Illustrates using ItemNotNullAttribute on a List parameter, showing that the compiler warns if an item is checked for null. ```csharp public void Foo([ItemNotNull]List books) { foreach (var book in books) { if (book != null) // Warning: Expression is always true { Console.WriteLine(book.ToUpper()); } } } ``` -------------------------------- ### Use AspRouteVerbsAttribute with a Method Parameter Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Shows how to use AspRouteVerbsAttribute on a string parameter 'allowedVerbs' in a method to specify allowed HTTP methods like "GET,POST". ```csharp [AspRouteConvention] public void ConfigureRoutes(IEndpointRouteBuilder endpoints, [AspRouteVerbs] string allowedVerbs) { // allowedVerbs specifies HTTP methods like "GET,POST" } ``` -------------------------------- ### AspMvcMasterLocationFormatAttribute Usage Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc-locations.md Example of how to apply the AspMvcMasterLocationFormatAttribute to specify master page locations. Supports controller name and master page name parameters. ```csharp [assembly: AspMvcMasterLocationFormat("~/Views/{1}/Masters/{0}.master")] [assembly: AspMvcMasterLocationFormat("~/Views/Shared/Masters/{0}.master")] ``` -------------------------------- ### Conditional Compilation Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/00-START-HERE.txt Attributes are defined with [Conditional("JETBRAINS_ANNOTATIONS")] and compile only when the preprocessor symbol is set, providing zero runtime overhead if not defined. ```C# /* Example of conditional compilation */ [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class MyAnnotationAttribute : Attribute { } ``` -------------------------------- ### Declaring Multiple Endpoints with AspMinimalApiImplicitEndpointDeclarationAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-minimal-api.md Illustrates how to declare multiple Minimal API endpoints (GET, POST, PUT, DELETE) on a single class using multiple instances of the AspMinimalApiImplicitEndpointDeclarationAttribute. ```csharp [AspMinimalApiImplicitEndpointDeclaration(HttpVerb = "GET", RouteTemplate = "/api/products")] [AspMinimalApiImplicitEndpointDeclaration(HttpVerb = "POST", RouteTemplate = "/api/products", BodyType = typeof(Product))] [AspMinimalApiImplicitEndpointDeclaration(HttpVerb = "PUT", RouteTemplate = "/api/products/{id}", BodyType = typeof(Product))] [AspMinimalApiImplicitEndpointDeclaration(HttpVerb = "DELETE", RouteTemplate = "/api/products/{id}")] public class ProductEndpoints { public IResult GetProducts() => Results.Ok(new[] { }); public IResult CreateProduct([FromBody] Product product) => Results.Created("/api/products/1", product); public IResult UpdateProduct(int id, [FromBody] Product product) => Results.Ok(); public IResult DeleteProduct(int id) => Results.NoContent(); } ``` -------------------------------- ### MacroAttribute Applied to Source Template Method Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-source-templates.md Example of applying MacroAttribute to a source template method to define a macro for a parameter. The 'suggestVariableName()' macro is used for the 'item' parameter. ```csharp [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")] public static void forEach(this IEnumerable collection) { foreach (var item in collection) { //$ $END$ } } ``` -------------------------------- ### Configuring Custom Route Constraints in Startup Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Illustrates registering custom route constraints and using them in route templates within the Startup class. ```csharp public class Startup { public void Configure(IApplicationBuilder app) { // Route templates can now use {id:guid} or {count:positive} app.MapRoute("{controller}/{id:guid}"); } } ``` -------------------------------- ### AspMvcAreaMasterLocationFormatAttribute Usage Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc-locations.md Example of how to apply the AspMvcAreaMasterLocationFormatAttribute to specify area master page locations. Supports area name, controller name, and master page name parameters. ```csharp [assembly: AspMvcAreaMasterLocationFormat("~/Areas/{2}/Views/{1}/Masters/{0}.master")] ``` -------------------------------- ### Apply AspMvcAreaViewComponentViewLocationFormatAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc-locations.md Example of applying the AspMvcAreaViewComponentViewLocationFormatAttribute at the assembly level to specify a custom view component view location format for a particular area. The format string uses {0} for the view component name and {1} for the area name. ```csharp [assembly: AspMvcAreaViewComponentViewLocationFormat("~/Areas/{1}/Views/Components/{0}/Default.cshtml")] ``` -------------------------------- ### Custom Route Constraint Implementation Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Shows how to implement custom route constraints using RouteParameterConstraintAttribute. ```csharp [RouteParameterConstraint("guid")] public class GuidConstraint : IRouteConstraint { public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { return values[routeKey] is Guid; } } [RouteParameterConstraint("positive", ProposedType = typeof(int))] public class PositiveIntConstraint : IRouteConstraint { // Ensures positive integers only } ``` -------------------------------- ### Add JetBrains.Annotations NuGet Package Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/README.md Use the dotnet CLI to add the JetBrains.Annotations package to your project. ```bash dotnet add package JetBrains.Annotations ``` -------------------------------- ### Apply CqrsQueryAttribute and CqrsCommandAttribute in UserRepository Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-cqrs-testing.md Illustrates the usage of CqrsQueryAttribute for a read operation and CqrsCommandAttribute for a state modification operation within a UserRepository. ```csharp public class UserRepository { [CqrsQuery] public User GetUserById(int id) { // Query: read-only operation return database.Users.FirstOrDefault(u => u.Id == id); } [CqrsCommand] public void CreateUserCommand(string name, string email) { // Command: state modification var user = new User { Name = name, Email = email }; database.Users.Add(user); database.SaveChanges(); } } ``` -------------------------------- ### Using JetBrains.Annotations Attributes in C# Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/README.md Demonstrates the application of various JetBrains.Annotations attributes like NotNull, MustDisposeResource, and Pure to C# code for improved static analysis and IDE warnings. ```csharp using JetBrains.Annotations; public class MyService { [NotNull] public string GetName() { ... } public void Process([NotNull] string input) { // IDE warns if null is passed } [MustDisposeResource] public FileStream OpenFile(string path) { return new FileStream(path, FileMode.Open); } [Pure] public int Calculate(int x, int y) => x + y; } ``` -------------------------------- ### Usage of RouteTemplateAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Demonstrates marking string parameters with RouteTemplateAttribute for ASP.NET route templates. ```csharp public class RouteBuilder { public void MapRoute([RouteTemplate] string template) { // template contains route pattern like "{controller}/{action}/{id}" } public void ConfigureRoutes([RouteTemplate] string defaultRoute) { // configures default route template } } ``` -------------------------------- ### Enum-based Language Injection with Prefix/Suffix Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-language-injection.md Demonstrates using LanguageInjectionAttribute with an enum value (InjectedLanguage.CSS) and specifying prefix and suffix strings to define the context for the injected code fragment. ```csharp void Foo([LanguageInjection(InjectedLanguage.CSS, Prefix = "body{", Suffix = "}")] string cssProps) { // cssProps should only contain a list of CSS properties ApplyStyles(cssProps); } ``` -------------------------------- ### Apply AspRouteValuesConstraintsAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Demonstrates applying the AspRouteValuesConstraintsAttribute to a parameter in a route convention configuration method. ```csharp [AspRouteConvention] public void ConfigureRoutes(IEndpointRouteBuilder endpoints, [AspRouteValuesConstraints] object constraints) { // constraints specifies route parameter constraints } ``` -------------------------------- ### HtmlAttributeValueAttribute Usage Example Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-razor-xaml.md Shows how to use HtmlAttributeValueAttribute to indicate that a string parameter represents the value for a specific HTML attribute, such as 'class'. ```csharp public class HtmlHelper { public string GetAttribute([HtmlAttributeValue("class")] string classValue) { return $"class=\"{classValue}\""; } } ``` -------------------------------- ### Usage of CqrsExcludeFromAnalysisAttribute in a Class Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-cqrs-testing.md Demonstrates applying CqrsExcludeFromAnalysisAttribute to a method that is used by both commands and queries, ensuring it's ignored in CQRS analyses. ```csharp public class User { private string Name; [CqrsCommand] public void SetUserNameCommand(string newName) { if (newName == GetUserName()) // Warning about 'GetUserName' being called from Command but belongs to the Query return; Name = newName; CheckName(); } [CqrsQuery] public string GetUserName() { CheckName(); return Name; } [CqrsExcludeFromAnalysis] public bool CheckName() // Although this method is used both in Command and Query, will be ignored in all CQRS analyzes { ... } } ``` -------------------------------- ### Apply AspRouteOrderAttribute to Parameter Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Demonstrates applying the AspRouteOrderAttribute to a parameter in a route convention configuration method to specify route priority. ```csharp [AspRouteConvention] public void ConfigureRoutes(IEndpointRouteBuilder endpoints, [AspRouteOrder] int routeOrder) { // routeOrder determines route priority } ``` -------------------------------- ### Method Termination Annotation Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-code-analysis.md Annotates a method that is guaranteed to terminate. Use this when a method always exits, for example, by throwing an exception or calling Environment.FailFast. ```csharp [ContractAnnotation("=> halt")] public void TerminationMethod() ``` -------------------------------- ### ASP.NET Routing Conventions Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/00-START-HERE.txt Apply AspRouteConvention to define routing patterns in ASP.NET. Use AspMinimalApiDeclaration for minimal API route definitions, specifying HTTP verb and route template. ```C# public void Map([AspRouteConvention] string pattern) { } ``` ```C# [AspMinimalApiDeclaration(HttpVerb = "GET", RouteTemplate = "/api/users/{id}")] IResult GetUser(int id) { } ``` -------------------------------- ### Enable JETBRAINS_ANNOTATIONS Preprocessor Symbol in .csproj Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/README.md Configure your .csproj file to include the JETBRAINS_ANNOTATIONS preprocessor symbol for conditional compilation. ```xml $(DefineConstants);JETBRAINS_ANNOTATIONS ``` -------------------------------- ### Apply CqrsCommandAttribute to User Class Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-cqrs-testing.md Demonstrates applying the CqrsCommandAttribute to a method that modifies the state of a User object. It includes a check that might trigger a warning if a query method is called within a command. ```csharp public class User { private string Name; [CqrsCommand] public void SetUserNameCommand(string newName) { if (newName == GetUserName()) // Warning about 'GetUserName' is called from Command but belongs to the Query return; Name = newName; } [CqrsQuery] public string GetUserName() // Suggestion to rename it to the 'GetUserNameQuery' { return Name; } } ``` -------------------------------- ### PureAttribute Usage Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-method-behavior.md Illustrates the usage of the PureAttribute on a method. A warning is generated if the return value of a pure method is not used. ```csharp [Pure] int Multiply(int x, int y) => x * y; void M() { Multiply(123, 42); // Warning: Return value of pure method is not used } ``` -------------------------------- ### InstantHandleAttribute Usage with Func and RequireAwait Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-method-behavior.md Shows InstantHandleAttribute with RequireAwait set to true for a Func parameter, meaning the callback must be awaited within the method. ```csharp async Task ProcessAsync([InstantHandle(RequireAwait = true)] Func callback) { // callback must be awaited in this method } ``` -------------------------------- ### Use AspRouteVerbsAttribute in a Class Property Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Demonstrates marking a string property 'HttpMethod' within a 'RouteAttribute' class using AspRouteVerbsAttribute to indicate it holds HTTP verbs. ```csharp public class RouteAttribute { [AspRouteVerbs] public string HttpMethod { get; set; } } ``` -------------------------------- ### Configure ASP.NET MVC View Locations Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc-locations.md Use these attributes in an assembly-level file (like AssemblyInfo.cs) to define custom search paths for views, partial views, master views, and view components. This allows for centralized control over view organization. ```csharp // In AssemblyInfo.cs or a similar assembly-level file [assembly: AspMvcViewLocationFormat("~/Views/{1}/{0}.cshtml")] [assembly: AspMvcViewLocationFormat("~/Views/Shared/{0}.cshtml")] [assembly: AspMvcPartialViewLocationFormat("~/Views/{1}/Partials/{0}.cshtml")] [assembly: AspMvcPartialViewLocationFormat("~/Views/Shared/Partials/{0}.cshtml")] [assembly: AspMvcMasterLocationFormat("~/Views/{1}/Masters/{0}.master")] [assembly: AspMvcMasterLocationFormat("~/Views/Shared/Masters/{0}.master")] [assembly: AspMvcAreaViewLocationFormat("~/Areas/{2}/Views/{1}/{0}.cshtml")] [assembly: AspMvcAreaViewLocationFormat("~/Areas/{2}/Views/Shared/{0}.cshtml")] [assembly: AspMvcAreaPartialViewLocationFormat("~/Areas/{2}/Views/{1}/Partials/{0}.cshtml")] [assembly: AspMvcAreaPartialViewLocationFormat("~/Areas/{2}/Views/Shared/Partials/{0}.cshtml")] [assembly: AspMvcAreaMasterLocationFormat("~/Areas/{2}/Views/{1}/Masters/{0}.master")] [assembly: AspMvcAreaMasterLocationFormat("~/Areas/{2}/Views/Shared/Masters/{0}.master")] [assembly: AspMvcViewComponentViewLocationFormat("~/Views/Components/{0}/Default.cshtml")] [assembly: AspMvcAreaViewComponentViewLocationFormat("~/Areas/{1}/Views/Components/{0}/Default.cshtml")] ``` -------------------------------- ### Method Parameter Nullability Annotation Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-code-analysis.md Annotates a method where the output depends on the nullability of an input parameter. This example shows that if the 'surname' parameter is null, the method returns null. ```csharp [ContractAnnotation("null <= param:null")] public string GetName(string surname) ``` -------------------------------- ### Use RegexPatternAttribute for Validation Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-language-injection.md Demonstrates how to use the RegexPatternAttribute to mark a string parameter that expects a regex pattern. This allows the IDE to provide specific analysis for the regex string. ```csharp public class Validator { public bool Matches([RegexPattern] string pattern, string input) { var regex = new Regex(pattern); return regex.IsMatch(input); } } void Usage() { var v = new Validator(); v.Matches(@"\d+", "123"); // OK - regex pattern } ``` -------------------------------- ### Apply AspRouteOrderAttribute to Property Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Shows how to apply the AspRouteOrderAttribute to an integer property within a route configuration class. ```csharp public class RouteConfig { [AspRouteOrder] public int Priority { get; set; } } ``` -------------------------------- ### InstantHandleAttribute Usage with IEnumerable Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-method-behavior.md Demonstrates using InstantHandleAttribute on an IEnumerable parameter, indicating it must be enumerated during the method call. ```csharp void ProcessItems([InstantHandle] IEnumerable items) { // items must be enumerated during this call } ``` -------------------------------- ### Apply PublicAPIAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-usage-analysis.md Demonstrates how to apply the PublicAPIAttribute to a class and a method. The attribute can be used without arguments or with a string comment. ```csharp [PublicAPI] public class PublicService { } [PublicAPI("Since 1.2")] public void PublicMethod() { } ``` -------------------------------- ### HTML Language Injection Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-language-injection.md Illustrates using LanguageInjectionAttribute to specify that a string parameter contains HTML markup, enabling IDE support for HTML syntax. ```csharp void RenderHtml([LanguageInjection(InjectedLanguage.HTML)] string htmlContent) { // htmlContent contains HTML markup with syntax highlighting } ``` -------------------------------- ### AspMvcControllerAttribute Usage in HtmlHelpers Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc.md Demonstrates how to use the AspMvcControllerAttribute in extension methods for HtmlHelper to specify controller names. ```csharp public class HtmlHelpers { public static string RenderAction(this HtmlHelper helper, [AspMvcController] string controllerName, string actionName) { // controllerName specifies the controller } public static string RenderAction(this HtmlHelper helper, [AspMvcController("controller")] object routeValues) { // routeValues.controller contains controller name } } ``` -------------------------------- ### Usage of AspMinimalApiHandlerAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-minimal-api.md Demonstrates how to apply the AspMinimalApiHandlerAttribute to parameters of type Func or delegate for Minimal API endpoint handlers. ```csharp public void ConfigureEndpoints(WebApplication app, [AspMinimalApiHandler] Func handler) { app.MapGet("/", handler); } ``` ```csharp public class EndpointConfiguration { public void SetupHandler([AspMinimalApiHandler] RequestDelegate handler) { // handler is a Minimal API endpoint handler } } ``` -------------------------------- ### String-based Language Injection Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-language-injection.md Shows how to use LanguageInjectionAttribute with a custom language name string ("json") for code injection. ```csharp void Bar([LanguageInjection("json")] string json) { ParseJson(json); } ``` -------------------------------- ### AspTypePropertyAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/types.md Attribute to enable reference creation for ASP.NET type properties. ```APIDOC ## AspTypePropertyAttribute ### Description Enables reference creation for ASP.NET type properties. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Apply ASP.NET MVC View Location Formats Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc-locations.md Applies custom view location formats to an assembly. Use {0} for the view name and {1} for the controller name. ```csharp [assembly: AspMvcViewLocationFormat("~/Views/{1}/{0}.cshtml")] [assembly: AspMvcViewLocationFormat("~/Views/Shared/{0}.cshtml")] ``` -------------------------------- ### Usage of CannotApplyEqualityOperatorAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-code-analysis.md Illustrates the usage of CannotApplyEqualityOperatorAttribute on a class. It shows that while comparison with null is permitted, direct equality checks between instances of the marked type will trigger a warning. ```csharp [CannotApplyEqualityOperator] class NoEquality { } class UsesNoEquality { void Test() { var instance1 = new NoEquality(); var instance2 = new NoEquality(); if (instance1 != null) // OK { bool condition = instance1 == instance2; // Warning } } } ``` -------------------------------- ### Apply ASP.NET MVC Partial View Location Formats Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-mvc-locations.md Applies custom partial view location formats to an assembly. Use {0} for the view name and {1} for the controller name. ```csharp [assembly: AspMvcPartialViewLocationFormat("~/Views/{1}/Partials/{0}.cshtml")] [assembly: AspMvcPartialViewLocationFormat("~/Views/Shared/Partials/{0}.cshtml")] ``` -------------------------------- ### Resource Management Attributes Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/00-START-HERE.txt Use MustDisposeResource for resources that must be disposed and HandlesResourceDisposal for parameters that manage resource disposal. ```C# [MustDisposeResource] FileStream OpenFile(string path) { } ``` ```C# void Process([HandlesResourceDisposal] IDisposable resource) { } ``` -------------------------------- ### Usage of LocalizationRequiredAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-code-analysis.md Demonstrates how to apply the LocalizationRequiredAttribute to a class, marking its string members as localizable. This helps in identifying strings that need translation. ```csharp [LocalizationRequired(true)] class Foo { string str = "my string"; // Warning: Localizable string } ``` -------------------------------- ### AspRouteConventionAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/types.md Defines a conventional route pattern for ASP.NET Core. ```APIDOC ## AspRouteConventionAttribute ### Description Defines a conventional route pattern for ASP.NET Core applications. ### Members - **PredefinedPattern** (string) - get - Predefined route pattern ``` -------------------------------- ### Usage of HandlesResourceDisposalAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-resource-disposal.md Demonstrates how to use HandlesResourceDisposalAttribute on methods and properties that manage disposable resources. Applied to methods, it indicates the method handles disposal for the resource instance. Applied to fields/properties, it signifies the type owns and manages the resource's disposal. ```csharp [MustDisposeResource] public class FileReader : IDisposable { public void Dispose() { ... } } public class FileProcessor { [HandlesResourceDisposal] public void ProcessFile(FileReader reader) { // Takes ownership and disposes using (reader) { ... } } private FileReader _reader; [HandlesResourceDisposal] public FileReader Reader { get { return _reader; } set { _reader?.Dispose(); _reader = value; } } public void Dispose() { _reader?.Dispose(); } } void Usage() { var reader = new FileReader(); processor.ProcessFile(reader); // OK - ownership transferred } ``` -------------------------------- ### InstantHandleAttribute Definition Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-method-behavior.md Defines the InstantHandleAttribute, used to indicate that a parameter is completely handled when the invoked method is on the stack. The RequireAwait property specifies if the invocation must be under an await expression. ```csharp using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class InstantHandleAttribute : Attribute { public bool RequireAwait { get; set; } } ``` -------------------------------- ### AspMvcLocationFormatAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/types.md Defines a format pattern for ASP.NET MVC location. ```APIDOC ## AspMvcLocationFormatAttribute Classes ### Description Defines a format pattern for ASP.NET MVC location. ### Members - **Format** (string) - get - Location format pattern ``` -------------------------------- ### Disposal Tracking Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/README.md Use [MustDisposeResource] for objects that must be disposed of after use. Use [HandlesResourceDisposal] to indicate that a parameter is a resource whose disposal is handled by the method. ```csharp [MustDisposeResource] FileStream OpenFile(string path) { ... } void ProcessWithDisposal([HandlesResourceDisposal] IDisposable resource) { ... } ``` -------------------------------- ### Usage of RazorImportNamespaceAttribute in AssemblyInfo.cs Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-razor-xaml.md Demonstrates how to use the RazorImportNamespaceAttribute in an AssemblyInfo.cs file to import specific namespaces into Razor views. ```csharp // In AssemblyInfo.cs [assembly: RazorImportNamespace("System.Linq")] [assembly: RazorImportNamespace("MyProject.Helpers")] [assembly: RazorImportNamespace("MyProject.Models")] ``` -------------------------------- ### Usage of NotifyPropertyChangedInvocatorAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-code-analysis.md Demonstrates how to use the NotifyPropertyChangedInvocatorAttribute in a class implementing INotifyPropertyChanged. This helps the code analysis identify property change notifications. ```csharp public class ObservableBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void NotifyChanged(string propertyName) { ... } string _name; public string Name { get { return _name; } set { _name = value; NotifyChanged("LastName"); /* Warning */ } } } ``` -------------------------------- ### Method Input-Output Transformation Annotation Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-code-analysis.md Annotates a method that transforms its input based on nullability. If the input 'data' is null, the output is null; if it's not null, the output is also not null. ```csharp [ContractAnnotation("null => null; notnull => notnull")] public object Transform(object data) ``` -------------------------------- ### Usage of DebuggerGlobalWatchAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-nostructure.md Illustrates applying DebuggerGlobalWatchAttribute to static properties to display custom information in the debugger's Watches window. ```csharp public static class DispatcherDebugWatch { [DebuggerGlobalWatch(Name = "UI Thread")] public static bool IsUIThread => System.Windows.Application.Current.Dispatcher.CheckAccess(); [DebuggerGlobalWatch(Name = "Total Memory")] public static long TotalMemory => GC.GetTotalMemory(false); } ``` -------------------------------- ### JavaScript Language Injection Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-language-injection.md Demonstrates using LanguageInjectionAttribute to specify that a string parameter contains JavaScript code, providing IDE support for JavaScript syntax. ```csharp void ExecuteScript([LanguageInjection(InjectedLanguage.JAVASCRIPT)] string script) { // script contains JavaScript code with IDE support } ``` -------------------------------- ### CQRS Pattern Attributes Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/00-START-HERE.txt Use CqrsCommand for methods that represent commands in the CQRS pattern and CqrsQuery for methods that represent queries. ```C# [CqrsCommand] void CreateUser(string name) { } ``` ```C# [CqrsQuery] User GetUser(int id) { } ``` -------------------------------- ### Define AspRouteOrderAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Defines the AspRouteOrderAttribute, used to mark parameters or properties containing routing order information. ```csharp [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspRouteOrderAttribute : Attribute { } ``` -------------------------------- ### Pure Methods Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/00-START-HERE.txt Mark methods as pure if they have no side effects and their return value depends only on their input parameters. Use MustUseReturnValue for methods that should not be ignored. ```C# [Pure] int Calculate(int x, int y) => x + y; ``` ```C# [MustUseReturnValue] List Filter(...) { } ``` -------------------------------- ### Declare ASP.NET Minimal API Endpoint Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-minimal-api.md Use AspMinimalApiDeclarationAttribute to mark methods that declare individual ASP.NET Minimal API endpoints. Specify the HTTP method using the HttpVerb property. ```csharp [AttributeUsage(AttributeTargets.Method)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMinimalApiDeclarationAttribute : Attribute { public string HttpVerb { get; set; } } ``` ```csharp public class ApiEndpoints { [AspMinimalApiDeclaration(HttpVerb = "GET")] public void MapGetUsers(WebApplication app) { app.MapGet("/api/users", GetAllUsers); } private IResult GetAllUsers() => Results.Ok(new[] { }); [AspMinimalApiDeclaration(HttpVerb = "POST")] public void MapCreateUser(WebApplication app) { app.MapPost("/api/users", CreateUser); } private IResult CreateUser() => Results.Created("/api/users/1", new { }); } ``` -------------------------------- ### Format String Validation Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/README.md Use [StringFormatMethod] to indicate that a parameter is a format string for other parameters. Use [StructuredMessageTemplate] for structured logging templates. ```csharp [StringFormatMethod("format")] void Log(string format, params object[] args) { ... } [StructuredMessageTemplate] void LogInfo(string template, params object[] args) { ... } ``` -------------------------------- ### AspMinimalApiDeclarationAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/types.md Declares an endpoint for ASP.NET Core Minimal APIs with an HTTP verb constraint. ```APIDOC ## AspMinimalApiDeclarationAttribute ### Description Declares an endpoint for ASP.NET Core Minimal APIs, specifying the HTTP method. ### Members - **HttpVerb** (string) - get/set - HTTP method for endpoint ``` -------------------------------- ### Define a Custom Attribute for Attribute Routing Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Defines a custom attribute 'GetRouteAttribute' inheriting from Attribute, marked with AspAttributeRoutingAttribute, and specifying an optional HTTP verb and a template for defining routes. ```csharp [AspAttributeRouting(HttpVerb = "GET")] [AttributeUsage(AttributeTargets.Method)] public class GetRouteAttribute : Attribute { public string Template { get; set; } } ``` -------------------------------- ### Apply Custom Attribute Routing to a Controller Method Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/api-reference-asp-routing.md Applies the custom 'GetRouteAttribute' to a controller method 'GetProduct', specifying the route template and parameter. ```csharp public class ProductController { [GetRoute(Template = "api/products/{id}")] public IActionResult GetProduct(int id) { ... } } ``` -------------------------------- ### AspMvcActionAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/types.md Specifies an action for ASP.NET MVC routing. ```APIDOC ## AspMvcActionAttribute ### Description Specifies the action for ASP.NET MVC routing. ### Members - **AnonymousProperty** (string) - get - Property containing action ``` -------------------------------- ### AspMvcControllerAttribute Source: https://github.com/jetbrains/jetbrains.annotations/blob/main/_autodocs/types.md Specifies a controller for ASP.NET MVC routing. ```APIDOC ## AspMvcControllerAttribute ### Description Specifies the controller for ASP.NET MVC routing. ### Members - **AnonymousProperty** (string) - get - Property containing controller ```