### Install L5Sharp NuGet Package
Source: https://deepwiki.com/tnunnink/L5Sharp/1.1-getting-started-and-installation
Use the Package Manager Console to install the core L5Sharp library. It targets .NET Standard 2.0 and .NET 8.0.
```powershell
Install-Package L5Sharp
```
--------------------------------
### Rung Serialization Example (L5X)
Source: https://deepwiki.com/tnunnink/L5Sharp/6.1-rung-line-block-and-sheet-%28code-elements%29
Demonstrates the typical XML structure of a Rung element in the L5X format, including its number, type, comment, and neutral text representation of ladder logic.
```xml
```
--------------------------------
### Reference to XPath Translation Example
Source: https://deepwiki.com/tnunnink/L5Sharp/5-scope-reference-and-addressing
Demonstrates how a L5Sharp Reference object can be converted into a valid XPath expression for direct lookup in the L5X XML document.
```csharp
var reference = new Reference("tag://MainProgram/MyTag");
var xpath = reference.ToXPath();
// xpath will be "//Structure[@Name='MainProgram']/Tag[@Name='MyTag']"
```
--------------------------------
### Querying and Retrieval Methods
Source: https://deepwiki.com/tnunnink/L5Sharp/2.3-l5x-document-and-logixcontent
L5Sharp offers multiple ways to find elements within the document, including direct lookups and complex LINQ queries using Get and TryGet methods.
```APIDOC
## Querying and Retrieval
L5Sharp provides multiple ways to find elements within the document, ranging from direct lookups to complex LINQ queries.
### Get and TryGet
These methods perform lookups using either a `Reference` object or a component name.
#### `Get(string name)`
Retrieves a component by name from its respective container. Throws `KeyNotFoundException` if not found.
#### `TryGet(string path, out LogixElement element)`
Attempts to find an element by its URI-style path (e.g., `datatype://AlarmType`). Returns `bool`.
```
--------------------------------
### Retrieve Module Definition
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
Get the ModuleDefinition (template) for a specific piece of hardware by its catalog number. Optionally specify a revision.
```csharp
var definition = catalog.GetDefinition("1756-L1");
// or
var definition = catalog.GetDefinition("1756-L1", Revision.Rev25);
```
--------------------------------
### Get Tag Directly from Index (C#)
Source: https://deepwiki.com/tnunnink/L5Sharp/1.1-getting-started-and-installation
Retrieve a controller-scoped tag directly from the index for O(1) access. Use path-based lookup for program-scoped tags.
```csharp
// Get a controller-scoped tag directly from the index (O(1))
Tag controllerTag = content.Get("MyTagName");
// Get a program-scoped tag using a path-based lookup
Tag programTag = content.Get("/MyProgram/Tag/MyTagName");
```
--------------------------------
### Create Module Instance from Catalog
Source: https://deepwiki.com/tnunnink/L5Sharp/8-module-catalog
Use the Create() method on the catalog or a ModuleDefinition to instantiate a new Module with initialized ports and tags.
```csharp
var module = catalog.Create("1756-L73", "16.011");
// or
var definition = catalog.GetDefinition("1756-L73", "16.011");
var module = definition.Create();
```
--------------------------------
### Module Creation using Factory Pattern
Source: https://deepwiki.com/tnunnink/L5Sharp/8-module-catalog
The Create() method on the ModuleDefinition or ModuleCatalog is the preferred way to instantiate hardware, ensuring correct configuration.
```APIDOC
## Module Creation using Factory Pattern
### Description
Instantiates hardware components using a factory pattern to ensure correct configuration, including Communications method, EKey state, and child Config tags for valid L5X import.
### Method
- **`Create(catalogNumber: string, revision: string = null)`** (on `ModuleDefinition` or `ModuleCatalog`)
- **Description**: Factory method to create a new `Module` instance with all necessary initializations.
- **Parameters**:
- **catalogNumber** (string) - Required - The catalog number of the module.
- **revision** (string) - Optional - The revision of the module.
- **Returns**: A new `Module` instance.
```
--------------------------------
### Create New L5X Project
Source: https://deepwiki.com/tnunnink/L5Sharp
Use the `L5X.New` method to create a new project, seeded with a specific controller, processor, and revision.
```csharp
L5X.New(name, processor, revision)
```
--------------------------------
### Instantiate Module with Specific Revision
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
Create a Module instance for a specific hardware revision by providing the catalog number and the desired revision.
```csharp
var module = catalog.Create("MyModule", "1756-L1", Revision.Rev25);
```
--------------------------------
### Create a new Program
Source: https://deepwiki.com/tnunnink/L5Sharp/7.1-tag-and-routine-builders
Instantiate a new program with a given name and type, such as `ProgramType.Normal`.
```csharp
new Program(programName, ProgramType.Normal)
```
--------------------------------
### Load L5X File
Source: https://deepwiki.com/tnunnink/L5Sharp
Use the `L5X.Load` method to load Logix content from a file on disk.
```csharp
L5X.Load(path)
```
--------------------------------
### Build Final Module Catalog Instance
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
Complete the configuration of the ModuleCatalogBuilder and obtain a fully populated ModuleCatalog instance containing all resolved definitions.
```csharp
var catalog = ModuleCatalogBuilder.Create()
.WithDefaultModules()
.WithModulesFromL5X("path/to/project.L5X")
.Build();
```
--------------------------------
### Safely Attempt Module Creation
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
Use TryCreate to safely attempt module instantiation. It returns a boolean indicating success and provides the created instance via an out parameter.
```csharp
if (catalog.TryCreate("MyModule", "1756-L1", out var module)) {
// Module created successfully
}
```
--------------------------------
### Attempt to Create Module Instance
Source: https://deepwiki.com/tnunnink/L5Sharp/8-module-catalog
Use TryCreate() to attempt creating a Module instance, returning a boolean success indicator.
```csharp
if (catalog.TryCreate("1756-L73", "16.011", out var module)) {
// Module created successfully
}
```
--------------------------------
### Build Module Catalog from L5X File
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
Configure the ModuleCatalogBuilder to scan an existing L5X file and extract module definitions to be used as templates for new modules.
```csharp
var catalog = ModuleCatalogBuilder.Create()
.WithModulesFromL5X("path/to/your/project.L5X")
.Build();
```
--------------------------------
### Load and Query L5X File
Source: https://deepwiki.com/tnunnink/L5Sharp/1.1-getting-started-and-installation
Load an L5X file and use LINQ to query its components, such as finding a specific tag by name or filtering tags by data type.
```csharp
// 1. Load the file
var content = L5X.Load("C:\\Projects\\MyProject.L5X");
// 2. Find a specific tag by name
var myTag = content.Tags.Find("MyTag");
// 3. Query all TIMER tags in the project
var timerTags = content.Query()
.Where(t => t.DataType == "TIMER")
.ToList();
```
--------------------------------
### Instantiate Module with Name and Catalog Number
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
Use this method to create a Module instance with a specific name and catalog number. It automatically resolves the latest revision available in the catalog.
```csharp
var module = catalog.Create("MyModule", "1756-L1", Action config: null);
// or
var module = catalog.Create("MyModule", "1756-L1");
```
--------------------------------
### L5X Factory Methods
Source: https://deepwiki.com/tnunnink/L5Sharp/2.3-l5x-document-and-logixcontent
The L5X class provides static factory methods to create instances from various sources, as it cannot be instantiated directly with a file path.
```APIDOC
## L5X Factory Methods
The `L5X` class cannot be instantiated directly with a file path; instead, it provides several static factory methods to create an instance from various sources.
### `Load(string fileName)`
Synchronously loads an L5X file from the disk into an `L5X` object.
### `LoadAsync(string fileName)`
Asynchronously loads an L5X file using a `StreamReader`.
### `Parse(string text)`
Creates an `L5X` instance from a raw XML string.
### `New(string name, string processor)`
Creates a new, minimal L5X project with a specified controller name and processor type.
### `Empty()`
Creates an empty L5X project with default "Controller" metadata.
```
--------------------------------
### Populate Module Catalog with ModuleCatalogBuilder
Source: https://deepwiki.com/tnunnink/L5Sharp/8-module-catalog
Use ModuleCatalogBuilder to populate the catalog from default modules, L5X files, or the Rockwell database.
```csharp
var catalog = new ModuleCatalogBuilder()
.WithDefaultModules()
.WithL5X("path/to/your/export.L5X")
.WithRockwellDatabase()
.Build();
```
--------------------------------
### Build Module Catalog with Default Modules
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
Initialize the ModuleCatalogBuilder and load a pre-compiled set of common Rockwell module definitions from an embedded XML resource.
```csharp
var catalog = ModuleCatalogBuilder.Create()
.WithDefaultModules()
.Build();
```
--------------------------------
### IModuleCatalog Interface
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
The IModuleCatalog interface provides methods for querying module definitions and instantiating new Module objects. The Create method acts as a factory for hardware components.
```APIDOC
## IModuleCatalog Interface
### Description
The `IModuleCatalog` interface defines the contract for querying module definitions and instantiating new `Module` objects. The primary entry point for users is the `Create` method, which acts as a factory for hardware components.
### Methods
* **`Create(string name, string catalogNumber, Action? config = null)`**: Instantiates a `Module` with the specified name and catalog number. It automatically resolves the latest (highest) revision found in the catalog.
* **`Create(string name, string catalogNumber, Revision revision, ...)`**: Instantiates a module for a specific hardware version.
* **`TryCreate(...)`**: Safely attempts to create a module, returning a boolean indicating success and an out parameter for the instance.
* **`GetDefinition(string catalogNumber, Revision? revision = null)`**: Retrieves the `ModuleDefinition` (template) for a specific piece of hardware.
```
--------------------------------
### Build a Tag with Description and Aliases
Source: https://deepwiki.com/tnunnink/L5Sharp/7.1-tag-and-routine-builders
Utilize the `TagBuilder` to construct a Tag component. Methods like `WithDescription`, `AliasFor`, `Produces`, and `Consumes` allow for detailed configuration before building the final Tag object.
```csharp
TagBuilder.Build()
```
--------------------------------
### Initialize a new Routine
Source: https://deepwiki.com/tnunnink/L5Sharp/7.1-tag-and-routine-builders
Use the `new Routine` constructor to create a new routine. Specify the routine's name and its type, such as `RoutineType.RLL` for Relay Ladder Logic.
```csharp
new Routine(name, RoutineType.RLL)
```
--------------------------------
### Retrieve All Module Definitions
Source: https://deepwiki.com/tnunnink/L5Sharp/8-module-catalog
The Definitions() method returns all available ModuleDefinition objects in the catalog.
```csharp
var definitions = catalog.Definitions();
```
--------------------------------
### Configure a Routine Builder
Source: https://deepwiki.com/tnunnink/L5Sharp/7.1-tag-and-routine-builders
The `RllBuilder` facilitates the construction of `Routine` components. Use `WithRung` to add rungs and `InProgram` to associate the routine with a program before calling `Build`.
```csharp
RllBuilder.Build()
```
--------------------------------
### Manually Add Module Definition
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
Manually add a specific Module instance as a template to the catalog by generating a definition from it.
```csharp
var module = new Module("MyCustomModule", "CUSTOM-01");
var catalog = ModuleCatalogBuilder.Create()
.AddDefinitionFor(module)
.Build();
```
--------------------------------
### LogixMemberInfo.GenerateInitializer Method
Source: https://deepwiki.com/tnunnink/L5Sharp/9.2-l5sharp.generators.data-%28udt-code-generation%29
Produces the C# constructor initialization code for a Logix member. It ensures that Logix arrays are instantiated with the correct dimensions using ArrayData.
```csharp
public string GenerateInitializer()
{
var sb = new StringBuilder();
var memberName = Name.ToPascalCase();
var offset = Offset;
var size = Size;
var dimensions = Dimensions;
if (dimensions != null)
{
sb.AppendLine($"this.{memberName} = new ArrayData<{TypeName}>({offset}, {size}, new[] {{ {string.Join(", ", dimensions)} }});");
}
else
{
sb.AppendLine($"this.{memberName} = new L5Sharp.Core.MemberData<{TypeName}>({offset}, {size});");
}
return sb.ToString();
}
```
--------------------------------
### Build Module Catalog from Rockwell Database
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
Add module definitions to the catalog by querying the Rockwell Automation Catalog Services database (RAD) for comprehensive hardware support.
```csharp
var catalog = ModuleCatalogBuilder.Create()
.WithModulesFromRAD()
.Build();
```
--------------------------------
### Resolve Logic Dependencies in Rung
Source: https://deepwiki.com/tnunnink/L5Sharp/6-logic-and-code-elements
Demonstrates how to recursively find all Tag and AddOnInstruction dependencies within a Rung by calling the Dependencies() method. This method attempts to resolve these references against the project structure.
```csharp
public override IEnumerable Dependencies()
{
var dependencies = new List();
// ... logic to resolve tags and AOIs from instructions ...
}
```
--------------------------------
### Generate C# Classes from L5X Files for AOIs
Source: https://deepwiki.com/tnunnink/L5Sharp/9-source-generators
Similar to UDTs, L5X files containing Add-On Instructions (AOIs) can be included as `AdditionalFiles`. The generator will produce C# classes that represent these AOIs, enabling type-safe interaction with them.
```csharp
// In your .csproj file:
//
//
//
// Generated C# code will look like:
public class GeneratedAOI : AddOnInstructionData
{
// Properties and methods corresponding to AOI parameters and logic will be generated here
}
```
--------------------------------
### ModuleCatalogBuilder Fluent API
Source: https://deepwiki.com/tnunnink/L5Sharp/8.1-modulecatalog-api-and-data-sources
The ModuleCatalogBuilder implements IModuleCatalogBuilder to aggregate hardware definitions from multiple sources into a single searchable catalog.
```APIDOC
## ModuleCatalogBuilder Fluent API
### Description
The `ModuleCatalogBuilder` implements `IModuleCatalogBuilder` to aggregate hardware definitions from multiple sources into a single searchable catalog.
### Methods
* **`WithDefaultModules()`**: Loads a pre-compiled set of common Rockwell module definitions from an embedded XML resource.
* **`WithModulesFromL5X(string path)`**: Scans an existing L5X file and extracts module definitions to be used as templates for new modules.
* **`WithModulesFromRAD(string? path)`**: Queries the Rockwell Automation Catalog Services database (RAD) for comprehensive hardware support.
* **`AddDefinitionFor(Module module)`**: Manually adds a specific `Module` instance as a template by generating a definition from it.
* **`Build()`**: Returns a `ModuleCatalog` instance containing all resolved definitions.
```
--------------------------------
### IModuleCatalog Operations
Source: https://deepwiki.com/tnunnink/L5Sharp/8-module-catalog
The IModuleCatalog interface provides methods to retrieve hardware templates and create module instances. It is implemented by ModuleCatalog, which stores definitions in-memory for fast lookup.
```APIDOC
## IModuleCatalog Operations
### Description
Provides methods for interacting with the module catalog to retrieve definitions and create module instances.
### Methods
- **`Definitions()`**
- **Description**: Returns all available `ModuleDefinition` objects in the catalog.
- **Returns**: A collection of `ModuleDefinition` objects.
- **`GetDefinition(catalogNumber: string, revision: string = null)`**
- **Description**: Retrieves a specific definition by catalog number and optional revision.
- **Parameters**:
- **catalogNumber** (string) - Required - The catalog number of the module.
- **revision** (string) - Optional - The revision of the module.
- **Returns**: The specific `ModuleDefinition` object or null if not found.
- **`Create(catalogNumber: string, revision: string = null)`**
- **Description**: A factory method that returns a new `Module` instance with all ports and tags initialized.
- **Parameters**:
- **catalogNumber** (string) - Required - The catalog number of the module to create.
- **revision** (string) - Optional - The revision of the module.
- **Returns**: A new `Module` instance.
- **`TryCreate(catalogNumber: string, revision: string = null)`**
- **Description**: Attempts to create a `Module` and returns a boolean success indicator.
- **Parameters**:
- **catalogNumber** (string) - Required - The catalog number of the module to create.
- **revision** (string) - Optional - The revision of the module.
- **Returns**: A tuple containing a boolean indicating success and the created `Module` instance (or null if creation failed).
```
--------------------------------
### Update and Save L5X File (C#)
Source: https://deepwiki.com/tnunnink/L5Sharp/1.1-getting-started-and-installation
Modify tag values directly or use TagBuilder for complex tag construction. Save the modified L5X content to a specified file path.
```csharp
// 1. Update a tag value directly
var tag = content.Tags.Find("ExistingTag");
tag.Value = 50;
// 2. Use TagBuilder for complex construction
var newTag = Tag.New("NewTag").WithValue(100).WithDescription("Fluent Tag").Build();
content.Tags.Add(newTag);
// 3. Save the modified L5X
content.Save("C:\\Projects\\UpdatedProject.L5X");
```
--------------------------------
### Configure Generator Project
Source: https://deepwiki.com/tnunnink/L5Sharp/9.1-l5sharp.generators-%28core-registration%29
Configure the generator project to target netstandard2.0 and use Microsoft.CodeAnalysis.CSharp. Mark the project as a Roslyn component.
```xml
true
```
--------------------------------
### Component Containers
Source: https://deepwiki.com/tnunnink/L5Sharp/2.3-l5x-document-and-logixcontent
The L5X class provides direct access to primary Logix component collections via LogixContainer properties, which are proxies to collections defined within the Controller root.
```APIDOC
## Component Containers
The `L5X` class provides direct access to the primary Logix component collections via `LogixContainer` properties. These containers are proxies to the collections defined within the `Controller` root.
### `DataTypes`
Component Type: `DataType`
Scope: Controller-scoped User Defined Types.
### `AddOnInstructions`
Component Type: `AddOnInstruction`
Scope: Controller-scoped AOI definitions.
### `Tags`
Component Type: `Tag`
Scope: Controller-scoped tags only.
### `Programs`
Component Type: `Program`
Scope: All programs in the project.
### `Modules`
Component Type: `Module`
Scope: All I/O modules in the project.
### `Tasks`
Component Type: `Task`
Scope: All tasks (Main, Periodic, Event).
### `Trends`
Component Type: `Trend`
Scope: Project trends.
### `WatchLists`
Component Type: `WatchList`
Scope: Project watch lists.
```
--------------------------------
### Generate C# Classes from L5X Files for UDTs
Source: https://deepwiki.com/tnunnink/L5Sharp/9-source-generators
Include L5X files as `AdditionalFiles` in your project. The `L5Sharp.Generators.Data` package will process these files and generate strongly-typed C# classes inheriting from `StructureData`, simplifying the use of User-Defined Types.
```csharp
// In your .csproj file:
//
//
//
// Generated C# code will look like:
public class GeneratedUDT : StructureData
{
// Properties corresponding to L5X members will be generated here
}
```
--------------------------------
### Add L5Sharp Generators as Analyzer
Source: https://deepwiki.com/tnunnink/L5Sharp/9.1-l5sharp.generators-%28core-registration%29
Reference the L5Sharp.Generators package as an analyzer in your project file to enable custom Logix type generation.
```xml
```
--------------------------------
### ModuleCatalogBuilder
Source: https://deepwiki.com/tnunnink/L5Sharp/8-module-catalog
The ModuleCatalogBuilder provides a fluent API to populate the module catalog from different data providers, including default modules, L5X files, and the Rockwell Database.
```APIDOC
## ModuleCatalogBuilder
### Description
Provides a fluent API to populate the module catalog from various data sources.
### Data Providers
- **Default Modules**: Loads a curated set of common modules from an embedded resource (`L5Sharp.Catalog.Internal.ModuleDefinitions.xml`).
- **L5X Files**: Extracts module definitions from an existing Logix export file via `L5X.Load()`, allowing you to "clone" hardware configurations from existing projects.
- **Rockwell Database**: Uses the `RockwellDatabaseReader` to parse the local `CatalogSvcsDatabaseV2.xml` typically found in `C:\ProgramData\Rockwell Automation\Catalog Services\`.
```
--------------------------------
### Module Definition Structure
Source: https://deepwiki.com/tnunnink/L5Sharp/8-module-catalog
A ModuleDefinition represents the blueprint for a piece of hardware, encapsulating static metadata required to build a Module instance.
```APIDOC
## Module Definition Structure
### Description
Encapsulates the static metadata for a hardware component, serving as a blueprint for creating `Module` instances.
### Components
- **Identity**: Vendor ID, Product Type, Product Code, and Catalog Number.
- **Hardware Capabilities**: Available `Ports` (e.g., Ethernet, ICP, PointIO) and their default addresses.
- **Template Data**: The structure of the `ConfigTag`, `InputTag`, and `OutputTag`, including default values.
```
--------------------------------
### Register Generated Types with ModuleInitializer
Source: https://deepwiki.com/tnunnink/L5Sharp/9.2-l5sharp.generators.data-%28udt-code-generation%29
Ensures that all generated types are registered with the LogixType factory as soon as the assembly is loaded. This is necessary because generated types are created during compilation, which might be too late for the standard L5Sharp.Generators registration pass.
```csharp
internal static class LogixDataRegistration
{
[ModuleInitializer]
internal static void Register()
{
LogixType.Register("MyCustomType");
// ...
}
}
```
--------------------------------
### LogixContent Metadata
Source: https://deepwiki.com/tnunnink/L5Sharp/2.3-l5x-document-and-logixcontent
The Content property of the L5X class returns a LogixContent object, which acts as a metadata wrapper for the root RSLogix5000Content element of the L5X file.
```APIDOC
## LogixContent Metadata
The `Content` property of the `L5X` class returns a `LogixContent` object. This acts as a metadata wrapper for the root `RSLogix5000Content` element of the L5X file.
### Target Information
Accesses `TargetName` (the controller name) and `TargetType` (typically "Controller").
### Revisioning
Provides `SoftwareRevision` and `SchemaRevision` (e.g., "1.0").
### Audit Data
Contains `ExportDate` and contextual flags like `ContainsContext`.
```
--------------------------------
### Add a Rung to a Routine
Source: https://deepwiki.com/tnunnink/L5Sharp/7.1-tag-and-routine-builders
Add a new rung to a routine using the `Rungs.Add` method. Each rung can be initialized with text and an optional comment.
```csharp
_routine.Rungs.Add(new Rung(text) { Comment = comment })
```
--------------------------------
### Parse L5X XML String
Source: https://deepwiki.com/tnunnink/L5Sharp
Use the `L5X.Parse` method to parse Logix content from a raw XML string.
```csharp
L5X.Parse(text)
```
--------------------------------
### Retrieve Specific Module Definition
Source: https://deepwiki.com/tnunnink/L5Sharp/8-module-catalog
GetDefinition() retrieves a specific ModuleDefinition by catalog number and optional revision.
```csharp
var definition = catalog.GetDefinition("1756-L73", "16.011");
```
--------------------------------
### Ensure Module Initializer Compatibility
Source: https://deepwiki.com/tnunnink/L5Sharp/9-source-generators
The `ModuleInitializerGenerator` acts as a polyfill to ensure that `[ModuleInitializer]` attributes function correctly across various .NET target frameworks. This allows for automatic registration of types when an assembly is loaded.
```csharp
using System.Runtime.CompilerServices;
public static class MyRegistrations
{
[ModuleInitializer]
public static void Initialize() => LogixType.Register();
}
```
--------------------------------
### Register Custom Logix Elements with [LogixElement]
Source: https://deepwiki.com/tnunnink/L5Sharp/9-source-generators
Use the `[LogixElement]` attribute to automatically register custom C# classes representing Logix elements with the `LogixSerializer`. This generator simplifies the mapping of XML tags to your C# types.
```csharp
using L5Sharp.Core;
[LogixElement("MyCustomElement")]
public class MyCustomElement : LogixElement
{
// ... custom implementation ...
}
```