ASCCommonCode 1.0.2

The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package ASCCommonCode --version 1.0.2
                    
NuGet\Install-Package ASCCommonCode -Version 1.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ASCCommonCode" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ASCCommonCode" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="ASCCommonCode" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ASCCommonCode --version 1.0.2
                    
#r "nuget: ASCCommonCode, 1.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ASCCommonCode@1.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ASCCommonCode&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=ASCCommonCode&version=1.0.2
                    
Install as a Cake Tool

ASCCommonCode Library Documentation

Overview

ASCCommonCode is a comprehensive .NET library providing essential utilities, extensions, and helper classes for common development tasks. The library includes payment processing, AI integration, data management, cryptography, and numerous extension methods for string manipulation, date handling, and more.

Table of Contents

  1. Payment Processing
  2. AI Integration
  3. Data Management
  4. Extension Methods
  5. Utilities
  6. Cryptography

Payment Processing

StripePayments Class

Handles all Stripe payment operations including authorizations, payments, and subscriptions.

Key Features
  • Payment method validation and management
  • Payment authorization and capture
  • Subscription management
  • Customer management
  • Refund processing
Constructor
var stripePayments = new StripePayments(IConfiguration config, StripePaymentMethod paymentMethod);

Note: Requires Stripe:SecretKey in configuration file.

Core Methods
Payment Operations
  • ValidatePaymentMethodAsync() - Validates a payment method
  • AttachPaymentMethodToCustomerAsync() - Attaches payment method to customer
  • ProcessPaymentAsync(long amount, string currency, string description) - Processes immediate payment
  • CreateAuthorizationAsync(long amount, string currency, string description) - Creates payment hold
  • CaptureAuthorizationAsync(string paymentIntentId, long? amountToCapture) - Captures authorized payment
  • ProcessRefundAsync(string paymentIntentId, long? refundAmount, string reason) - Process refunds
Subscription Management
  • CreateSubscriptionAsync(string priceId, int? trialPeriodDays) - Creates recurring subscription
  • UpdateSubscriptionAsync(string subscriptionId, string newPriceId, string prorationBehavior) - Updates subscription
  • CancelSubscriptionAsync(string subscriptionId, bool cancelAtPeriodEnd) - Cancels subscription
Customer Management
  • CreateOrGetCustomerAsync(string email, string name, string phone) - Creates or retrieves customer
  • GetCustomerPaymentMethodsAsync(string customerId, string type) - Gets customer payment methods

StripePaymentMethod Class

Manages credit card information for Stripe payments.

Properties
  • CustomerID - Company's subscription ID
  • PaymentMethodID - Unique identifier
  • CardNumber - Last 4 digits only
  • CardHolderFullName - Cardholder name
  • CardType - Card brand (Visa, Mastercard, etc.)
  • ExpirationDate - MM/YY format
  • IsPreferred - Preferred billing card flag
Methods
  • SaveToDB(IConfiguration config, bool isUpdate) - Persists to database
  • GetCompanyPaymentMethods(IConfiguration config) - Retrieves all company payment methods
  • ValidatePaymentMethodAsync(IConfiguration config) - Validates payment method
  • DeletePaymentMethodAsync(IConfiguration config) - Deletes payment method
  • GetPreferredPaymentMethod(string customerId) - Gets preferred payment method

StripeIntentResult Class

Represents payment operation results.

Properties
  • Success - Operation success status
  • TransactionId - Stripe PaymentIntent ID
  • Amount - Charged amount (smallest currency unit)
  • Currency - Payment currency
  • Status - Payment status
  • ErrorMessage - Error details if failed
  • RequiresAction - Additional authentication needed
  • ClientSecret - Client-side authentication secret

AI Integration

AIEngine Class

Manages all AI communication operations.

Core Method
public static async Task<AiResult> ChatAiAsync(
    string baseSystemInstruction,
    string modelName,
    string endPointUrl,
    string apiKey,
    string prompt,
    string purpose = "General AI Chat",
    IConfiguration config = null)
Parameters
  • baseSystemInstruction - System instruction for AI
  • modelName - AI model to use
  • endPointUrl - API endpoint URL
  • apiKey - Authentication key
  • prompt - User prompt
  • purpose - Purpose description (default: "General AI Chat")
  • config - Configuration for pricing info (optional)

Usage Tracking

Usage Class

Comprehensive usage tracking for AI calls with Azure cost integration.

Properties
  • UsageID - Unique identifier
  • CustomerID - Customer identifier
  • CallDateTime - Call timestamp
  • Purpose - Call purpose/description
  • ModelName - Model used
  • InputTokens / OutputTokens - Token consumption
  • TotalCost - Calculated cost
  • DurationMs - Call duration
  • Metadata - Additional metadata
Methods
  • RetrieveAzurePricingAsync(IConfiguration config) - Gets current Azure OpenAI pricing
  • SaveAsync(IConfiguration config) - Saves usage data
  • GetUsageStatisticsAsync(DateTime start, DateTime end, IConfiguration config) - Gets usage statistics

Required Azure Configuration:

  • Azure:SubscriptionId
  • Azure:ResourceGroupName
  • Azure:OpenAIAccountName
  • Azure:TenantId
  • Azure:ClientId
  • Azure:ClientSecret

Data Management

StateList<T> Class

A List implementation that maintains its current position through serialization/deserialization.

Key Features
  • Maintains current index position
  • Navigation methods (MoveNext, MovePrevious, First, Last)
  • Case-insensitive string searches
  • LINQ-like operations maintaining state
Properties
  • CurrentIndex - Current position
  • Current - Object at current index
  • Peek - Current item and index as tuple
  • HasNext / HasPrevious - Navigation availability
  • IsValidIndex - Index bounds validation
var list = new StateList<string>(items);
list.MoveNext();      // Move forward
list.MovePrevious();  // Move backward
list.First();         // Go to first
list.Last();          // Go to last
list.Reset();         // Reset position
Enhanced Operations
  • Add(T item, bool setCurrent = true) - Add with optional current setting
  • Find(Predicate<T> match) - Find and set as current
  • Where(Func<T, bool> predicate) - Filter to new StateList
  • Intersect(IEnumerable<T> other) - Set intersection
  • Except(IEnumerable<T> other) - Set difference

AsyncProcessingState<T> Class

Enables lazy asynchronous iteration over collections.

Key Method
public async IAsyncEnumerable<(T item, int index)> GetItemAsync(CancellationToken cancellationToken)

Yields items one at a time for efficient memory usage.

TypeCache Class

Enhanced type cache for objects and enums to reduce reflection overhead.

Methods
  • GetTypeMetadata<T>() - Cached type metadata
  • GetObjectProperties<T>() - Cached property info
  • GetObjectAttributes<TObject, TAttribute>() - Cached property attributes
  • GetEnumAttributes<TEnum, TAttribute>() - Cached enum attributes
  • GetEnumValues<T>() - Cached enum values

Extension Methods

String Extensions

Phone Number Handling
  • TryValidatePhone(string number) - Validates and gets phone info
  • FormatPhoneNumber(string phoneNumber) - Formats to international format
  • MakeReadablePhoneForRegion(string phoneNumber) - Regional formatting
  • ToAudiblePhone(string phoneNumber) - Converts to speakable format
  • ConvertPhoneNumberToText(string phoneNumber) - Converts to word representation
  • LooksLikeUSAPhone(string phone, out string number) - USA phone validation
Fuzzy Matching
// Find best matches using multiple algorithms
var matches = collection.GetFuzzyMatches(searchString, selector, threshold: 0.5);
var bestMatch = collection.GetFuzzyMatch(searchString, selector, threshold: 0.7);

// Dictionary fuzzy matching
var dictMatch = dictionary.GetFuzzyMatch(searchTerms, keyTransform, 0.6);

Fuzzy matching uses multiple algorithms:

  • Token matching
  • Levenshtein distance
  • Jaro-Winkler
  • Metaphone (phonetic)
Text Processing
  • Humanize(string text, double frequency = 0.1) - Adds natural speech fillers
  • SplitIntoSentences(string text) - Intelligent sentence splitting
  • WordCount(string phrase) - Word counting
  • RemovePunctuation(string text) - Punctuation removal
  • RemoveSpaces(string text) - Space removal
  • KeepOnlyLetters(string text) - Letter filtering
  • TruncateText(string content, int maxLength) - Smart truncation
String Analysis
  • IsURL(string text, bool strict = true) - URL detection
  • ExtractLinks(string input) - Link extraction
  • HasAddressFormat(string sentence) - Address pattern detection
  • IsHtml(string input) - HTML detection
  • LooksLikeGuid(string text) - GUID pattern detection
  • HasVerb(string sentence) - Verb detection
Natural Language
  • Pluralize(string word) - Word pluralization
  • Singularize(string word) - Word singularization
  • ToTitleCase(string word) - Title casing
  • IsCalendarMonth(string word) - Month detection
  • ToCalendarDate(string text) - Date parsing from natural language
Data Processing
  • RecursiveSplit(string value) - Multi-delimiter splitting
  • SelectDelimitedData(IEnumerable<string> source, bool scramble) - Delimited data processing
  • ReplaceVariables(string str, Dictionary<string, string> variables) - Variable substitution
  • RemoveEscapeSequences(string text) - Escape sequence removal

DateTime Extensions

Time Comparison
  • IsDateWithin(DateTime current, int toleranceDays) - Date proximity check
  • IsDayWithin(DateTime current, int toleranceDays) - Day proximity check
  • IsDateTimeInRange(DateTime? target, DateTime? start, DateTime? end) - Range checking
  • IsDateTimeInThePast(DateTime date) - Past date check
  • IsTimeBetween(DateTimeOffset t, DateTime compare, int startInterval, int endInterval) - Time interval checking
Formatting
  • ToFilteredDateString(DateTime date) - Table Storage compatible format
  • ToISO860(DateTime date) - ISO 8601 with timezone
  • ToAudibleDateTime(DateTime dt) - Human-readable datetime
  • ToAudibleDateOnly(DateTime dt) - Human-readable date
  • ToAudibleTimeOnly(DateTime dt) - Human-readable time
Timezone Operations
  • TryConvertToExactTimezone(DateTime value, string sourceTimezone, string targetTimezone) - Timezone conversion
  • GetCurrentTimeInTimezone(string timeZoneId) - Current time in timezone
  • ConvertToLocalTime(DateTime value, string timeZoneId, bool isDaylightSaving) - UTC to local conversion

Collection Extensions

  • ToStateList<T>(IEnumerable<T> source) - Convert to StateList
  • GetRandom<T>(IEnumerable<T> source) - Random element selection
  • GetRandom<T>(IEnumerable<T> list, int count) - Multiple random elements
  • Scramble<T>(IEnumerable<T> source) - Random ordering
  • UnCased<T>(Dictionary<string, T> dict) - Case-insensitive dictionary

Email Validation

  • IsValidEmailAddress(string email) - Email validation
  • DomainName(string email) - Extract domain
  • IsCommonDomainName(string domainName) - Common domain detection
  • IsDisposableDomainName(string domainName) - Temporary email detection
  • IsRoleBasedEmail(string email) - Role-based email detection
  • IsValidDomainName(string domainName) - DNS validation with MX, TXT, DMARC

Numeric Extensions

  • RoundUp(double currentValue, int nearestWhole) - Round up to nearest whole
  • RoundUp(double currentValue, double nearestWhole) - Round up to nearest decimal
  • CalculateMarkupAndTax(double cost, double markUpPercentage, bool roundToNickel, bool addMarkup) - Pricing calculations
  • FormatAmount(double amount, bool roundUp) - Amount formatting

Utilities

Shared Class

Static utility methods and properties.

Properties
  • TableStorageName - Azure Table Storage account name
  • TableStorageKey - Azure Table Storage account key
  • AppConfig - Configuration instance
  • UserAgent - Standard HTTP User-Agent
  • WebClient - Singleton HttpClient
Methods
Unique Identifiers
  • CreateUniqueName() - Generates globally unique name
  • Base36Encode(ulong value) - Base36 encoding
Color Utilities
  • HexToRgb(string hex) - Hex to RGB conversion
  • GetLuminance(int r, int g, int b) - Color luminance calculation
  • GetContrastColor(string hex) - Contrast color determination
  • GetSecondaryColor(string primaryColor) - Secondary color selection
Web Operations
  • ScrapeWebsite(string url, string selector) - Web scraping
  • DownloadFileAsBytes(string fileUrl) - File download
DNS and Timezone
  • GetDNSLookupOptions() - DNS configuration
  • GetWindowsIANATimezone(string windowsTimeZoneId) - Timezone conversion
  • GetTimezoneInfo(string IANATimezone) - Timezone information

SerializationHelper Class

JSON serialization with fuzzy deserialization support.

Methods
  • ToJson(object data) - Object to JSON
  • TryDeserializeJsonString<T>(string json) - Fuzzy deserialization
  • CleanJsonResponse(string response) - JSON cleaning

Features fuzzy property matching for AI-generated JSON with inconsistent naming.

PhoneValidationResult Class

Phone number validation results.

Properties
  • Status - Validation status
  • FormattedPhone - International format
  • Code - Country code (US, NG, CA)
  • Prefix - Phone code (+1, +234)
  • Location - Registration city
  • Timezone - Phone timezone
  • CanReceiveSMS - SMS capability

Cryptography

CryptoHelper Class

Encryption and decryption using TripleDES and AES algorithms.

Methods
TripleDES Operations
  • EncryptString(string plainText) - TripleDES encryption
  • TryDecryptString(string cipherText) - TripleDES decryption
AES Operations (URL-Safe)
  • TryUrlEncrypt(string plainText) - AES URL-safe encryption
  • TryUrlDecrypt(string cipherText) - AES URL-safe decryption

Enumerations

Status

Common status values used throughout the application.

TimeFrame

Time intervals in minutes for date calculations:

  • Half - 0.5 (30 seconds)
  • Various minute-based intervals

CalendarMonth

Months of the year enumeration.

USAConstants

  • SSN - 9 characters
  • Phone - 10 characters

Configuration Requirements

Required Configuration Keys

Azure Storage
{
  "Azure": {
    "TableStorageName": "your-storage-account",
    "TableStorageKey": "your-storage-key"
  }
}
Stripe Payments
{
  "Stripe": {
    "SecretKey": "your-stripe-secret-key"
  }
}
Azure OpenAI (for Usage tracking)
{
  "Azure": {
    "SubscriptionId": "your-subscription-id",
    "ResourceGroupName": "your-resource-group",
    "OpenAIAccountName": "your-openai-account",
    "TenantId": "your-tenant-id",
    "ClientId": "your-client-id",
    "ClientSecret": "your-client-secret"
  }
}

Best Practices

  1. Payment Processing

    • Always validate payment methods before processing
    • Use authorization/capture for delayed charging
    • Store only last 4 digits of card numbers
  2. AI Integration

    • Implement usage tracking for cost management
    • Use appropriate models for different tasks
    • Cache pricing information when possible
  3. Data Management

    • Use StateList for navigation-heavy operations
    • Leverage TypeCache to reduce reflection overhead
    • Implement AsyncProcessingState for large datasets
  4. String Operations

    • Use fuzzy matching for user input validation
    • Apply appropriate thresholds (0.5 default, 0.7+ for high confidence)
    • Validate phone numbers and emails before processing
  5. Security

    • Use URL-safe encryption for query parameters
    • Never store full credit card numbers
    • Validate all external inputs

Error Handling

Most async methods return result objects with success/failure information:

var result = await stripePayments.ProcessPaymentAsync(amount, currency, description);
if (result.Success)
{
    // Handle success
    var transactionId = result.TransactionId;
}
else
{
    // Handle failure
    var error = result.ErrorMessage;
}

Performance Considerations

  1. HttpClient - Use the shared Shared.WebClient singleton
  2. Type Reflection - Use TypeCache for repeated reflection operations
  3. Large Collections - Use AsyncProcessingState for memory-efficient iteration
  4. Fuzzy Matching - Adjust thresholds based on performance needs
  5. Serialization - Cached serializer options for improved performance

Version History

This documentation covers the ASCCommonCode library as of the latest XML documentation version.


Support

For issues, feature requests, or questions, please refer to the library's repository or contact the development team.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated

Beginning