BB84.Extensions is a comprehensive collection of extension methods for the .NET framework and Windows Forms applications. The project consists of two main libraries that provide utility methods to simplify common programming tasks and enhance developer productivity.
- Cross-Platform Compatibility: Supports multiple .NET target frameworks
- Comprehensive Coverage: Extension methods for arrays, strings, dates, colors, HTTP clients, and more
- Windows Forms Support: Specialized extensions for WinForms data binding and control manipulation
- Well-Tested: Extensive unit test coverage
- NuGet Packages: Available as published NuGet packages
- Strong Naming: Assemblies are signed for security
- Current Version: 3.2.x (versioned using date-based scheme)
- Author: Robert Peter Meyer
- Copyright: Β© 2023 Robert Peter Meyer
- License: MIT License
BB84.Extensions/
βββ src/
β βββ BB84.Extensions/ # Core extension methods library
β βββ BB84.WinForms.Extensions/ # Windows Forms specific extensions
βββ tests/
β βββ BB84.Extensions.Tests/ # Unit tests for core library
β βββ BB84.WinForms.Extensions.Tests/ # Unit tests for WinForms library
βββ docs/ # Documentation files
βββ TestResults/ # Test execution results
The project supports multiple .NET target frameworks to ensure broad compatibility:
- .NET Standard 2.0
- .NET Standard 2.1
- .NET Framework 4.6.2
- .NET Framework 4.8.1
- .NET 8.0
- .NET 9.0
- .NET Framework 4.6.2
- .NET Framework 4.8.1
- .NET 8.0 (Windows)
- .NET 9.0 (Windows)
The project uses modern .NET SDK-style project files with:
- C# Language Version: Latest
- Nullable Reference Types: Enabled
- Implicit Usings: Enabled
- Assembly Signing: Enabled with public key
- Documentation Generation: XML documentation files generated
- Package Validation: Enabled for NuGet packages
The core extension methods library providing utilities for common .NET types.
Array Extensions
TakeRandom()- Returns a randomly selected element from an array
Boolean Extensions
IsTrue()- Checks if a boolean value is trueIsFalse()- Checks if a boolean value is falseIsNull()- Checks if a nullable boolean is null
Byte Extensions
Compress()- Compresses byte arrays using GZipDecompress()- Decompresses GZip compressed byte arraysToBase64()- Converts byte array to Base64 stringFromBase64()- Converts Base64 string to byte arrayGetMD5()- Calculates MD5 hash of byte arrayGetHexString()- Converts byte array to hexadecimal stringGetString()- Converts byte array to string using specified encoding
Color Extensions
ToRGBHexString()- Converts Color to RGB hex representationToARGBHexString()- Converts Color to ARGB hex representationFromRGBHexString()- Creates Color from RGB hex stringFromARGBHexString()- Creates Color from ARGB hex stringToRgbByteArray()- Converts Color to RGB byte arrayToArgbByteArray()- Converts Color to ARGB byte array
Comparable Extensions
IsGreaterThan()- Checks if value is greater than comparison valueIsLessThan()- Checks if value is less than comparison valueIsGreaterOrEqualThan()- Checks if value is greater than or equal to comparison valueIsLessOrEqualThan()- Checks if value is less than or equal to comparison value
DateTime Extensions
StartOfWeek()- Gets the first day of the weekEndOfWeek()- Gets the last day of the weekStartOfMonth()- Gets the first day of the monthEndOfMonth()- Gets the last day of the monthStartOfYear()- Gets the first day of the yearEndOfYear()- Gets the last day of the yearStartOfFiscalYear()- Gets the start of fiscal yearEndOfFiscalYear()- Gets the end of fiscal yearWeekOfYear()- Gets the week number of the year
Enumerable Extensions
ForEach()- Executes an action for each element in the enumerableTakeRandom()- Returns a randomly selected element from enumerable
HttpClient Extensions
WithBaseAddress()- Sets the base address for HTTP client- Additional HTTP configuration methods
HttpRequestMessage Extensions
- Bearer token authentication helpers
- Media type configuration methods
Integer Extensions
ArrayUp()- Creates an array of integers from current value up to maximumArrayDown()- Creates an array of integers from current value down to minimum
Object Extensions
IsNull()- Checks if object is nullToBooleanInvariant()- Converts object to boolean using invariant cultureToDateTimeInvariant()- Converts object to DateTime using invariant culture
Stream Extensions
ToByteArray()- Converts stream to byte array
String Extensions
- Various string manipulation and validation methods
- Regular expression helpers
Task Extensions
ToSafeSync()- Safely executes async tasks synchronously with error handling
Specialized extension methods for Windows Forms controls, focusing on simplified data binding.
Button Extensions
- Command binding support
- Property binding for Enabled, Text, Visible
CheckBox Extensions
- Checked property binding
ComboBox Extensions
- DataSource binding
- SelectedItem binding
DataGridView Extensions
- DataSource binding
DateTimePicker Extensions
- Value property binding
Label Extensions
- Text property binding
ListBox Extensions
- DataSource binding
- SelectedItem binding
NumericUpDown Extensions
- Value property binding
PictureBox Extensions
- Image property binding
PropertyGrid Extensions
- SelectedObject binding
ProgressBar Extensions
- Value property binding
RadioButton Extensions
- Checked property binding
TextBox Extensions
- Text property binding
TrackBar Extensions
- Value property binding
Install-Package BB84.ExtensionsInstall-Package BB84.WinForms.Extensionsdotnet add package BB84.Extensionsdotnet add package BB84.WinForms.Extensions<PackageReference Include="BB84.Extensions" Version="2.14.*" />
<PackageReference Include="BB84.WinForms.Extensions" Version="2.14.*" />using BB84.Extensions;
DateTime today = new(2023, 9, 5);
DateTime startOfWeek = today.StartOfWeek();
DateTime endOfMonth = today.EndOfMonth();
int weekNumber = today.WeekOfYear();using BB84.Extensions;
// Random selection
int[] numbers = [1, 2, 3, 4, 5];
int randomNumber = numbers.TakeRandom();
// ForEach with condition
IEnumerable<string> strings = ["apple", "banana", "cherry"];
int count = 0;
strings.ForEach(x => x.Contains("a"), x => count++);using BB84.Extensions;
using System.Drawing;
Color color = Color.Red;
string hexRgb = color.ToRGBHexString(); // "#FF0000"
string hexArgb = color.ToARGBHexString(); // "#FFFF0000"
byte[] rgbBytes = color.ToRgbByteArray(); // [255, 0, 0]using BB84.Extensions;
var client = new HttpClient()
.WithBaseAddress("https://api.example.com")
.WithTimeout(TimeSpan.FromSeconds(30));
var request = new HttpRequestMessage(HttpMethod.Get, "/users")
.WithBearerToken("your-token-here")
.WithJsonMediaType();using BB84.Extensions;
byte[] data = Encoding.UTF8.GetBytes("Hello World");
byte[] compressed = data.Compress();
byte[] decompressed = compressed.Decompress();
string base64 = data.ToBase64();
string hex = data.GetHexString();
string md5Hash = data.GetMD5();using BB84.WinForms.Extensions;
public partial class MyForm : Form
{
private MyViewModel viewModel = new();
public MyForm()
{
InitializeComponent();
SetupDataBindings();
}
private void SetupDataBindings()
{
// Chain multiple bindings
textBox1
.BindText(viewModel, nameof(MyViewModel.Name))
.BindEnabled(viewModel, nameof(MyViewModel.IsEditable))
.BindVisible(viewModel, nameof(MyViewModel.IsVisible));
// Bind checkbox
checkBox1.BindChecked(viewModel, nameof(MyViewModel.IsSelected));
// Bind combo box
comboBox1
.SetDataSource(categories)
.BindSelectedItem(viewModel, nameof(MyViewModel.SelectedCategory));
// Bind numeric up/down
numericUpDown1
.BindValue(viewModel, nameof(MyViewModel.Count))
.BindMinimum(viewModel, nameof(MyViewModel.MinCount))
.BindMaximum(viewModel, nameof(MyViewModel.MaxCount));
}
}using BB84.WinForms.Extensions;
using System.Windows.Input;
public class MyViewModel : INotifyPropertyChanged
{
public ICommand SaveCommand { get; private set; }
public MyViewModel()
{
SaveCommand = new RelayCommand(Save, CanSave);
}
private void Save() => /* Save logic */;
private bool CanSave() => /* Validation logic */;
}
// In the form
saveButton.BindCommand(viewModel.SaveCommand);The project follows strict coding standards enforced through .editorconfig:
- Naming Conventions: PascalCase for public members, camelCase for private fields
- Language Features: Modern C# features encouraged (nullable reference types, pattern matching)
- Documentation: XML documentation required for all public APIs
- Error Handling: Comprehensive exception handling with appropriate exception types
- Partial Classes: Extension methods are organized using partial classes
- Single Responsibility: Each file contains a specific set of related extension methods
- Namespace Organization: Clear namespace hierarchy (
BB84.Extensions,BB84.WinForms.Extensions)
- PolySharp: For backward compatibility polyfills
- System.Text.Json: For JSON serialization (when targeting older frameworks)
- System.Net.Http: For HTTP extensions (when targeting older frameworks)
- System.Windows.Forms: Windows Forms framework
- System.Windows.Input: For command pattern support
The project maintains comprehensive test coverage with dedicated test projects:
- BB84.Extensions.Tests: Unit tests for core extension methods
- BB84.WinForms.Extensions.Tests: Unit tests for WinForms extensions
- MSTest: Primary testing framework
- Data-Driven Tests: Extensive use of
[DataTestMethod]for parameterized tests - Exception Testing: Proper validation of exception scenarios
[TestClass]
public sealed partial class BooleanExtensionsTests
{
[DataTestMethod]
[DataRow(true, false)]
[DataRow(false, true)]
public void IsFalseTest(bool value, bool expected)
=> Assert.AreEqual(expected, value.IsFalse());
[TestMethod]
[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void ArrayUpExceptionTest()
{
int value = 15;
int maxValue = 0;
_ = value.ArrayUp(maxValue);
}
}Tests can be executed using:
# Run all tests
dotnet test
# Run tests with coverage
dotnet test --collect:"XPlat Code Coverage"
# Run specific test project
dotnet test tests/BB84.Extensions.Tests/BB84.Extensions.Tests.csprojThe project uses MSBuild with the following key configurations:
<PropertyGroup Label="Technical">
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>..\..\PublicKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>The project uses a date-based versioning scheme:
- Major: 2 (current major version)
- Minor: 14 (feature version)
- Patch: MMDD (month and day)
- Revision: Minutes since midnight
The project includes GitHub Actions workflows for:
- CI (Continuous Integration): Build and test validation
- CD (Continuous Delivery): Package publishing to NuGet
- CodeQL: Security analysis
- Dependabot: Dependency updates
Packages are automatically published to NuGet.org through the CD pipeline when:
- Changes are pushed to the main branch
- All tests pass
- Package validation succeeds
- Fork the repository on GitHub
- Clone your fork locally
- Create a feature branch from main
- Make your changes following the coding standards
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
- Follow the existing code style and patterns
- Add XML documentation for all public APIs
- Include unit tests for new functionality
- Update documentation if needed
- Ensure compatibility across all target frameworks
This project follows the Contributor Covenant Code of Conduct. Please read and follow these guidelines when contributing.
- Ensure your code builds without warnings
- All tests must pass
- Include appropriate test coverage
- Update documentation as needed
- Describe your changes in the PR description
Complete API documentation is automatically generated and hosted at: https://bobobass84.github.io/BB84.Extensions/
Documentation is generated using DocFX from XML comments in the source code.
To build documentation locally:
# Install DocFX
dotnet tool install -g docfx
# Build documentation
docfx docs/docfx.json --serveThis project is licensed under the MIT License. See the LICENSE file for the full license text.
- GitHub Repository: https://github.com/BoBoBaSs84/BB84.Extensions
- NuGet Packages:
- Issues and Bug Reports: GitHub Issues
- API Documentation: Online Documentation