ASCCommonCode 1.0.2
dotnet add package ASCCommonCode --version 1.0.2
NuGet\Install-Package ASCCommonCode -Version 1.0.2
<PackageReference Include="ASCCommonCode" Version="1.0.2" />
<PackageVersion Include="ASCCommonCode" Version="1.0.2" />
<PackageReference Include="ASCCommonCode" />
paket add ASCCommonCode --version 1.0.2
#r "nuget: ASCCommonCode, 1.0.2"
#:package ASCCommonCode@1.0.2
#addin nuget:?package=ASCCommonCode&version=1.0.2
#tool nuget:?package=ASCCommonCode&version=1.0.2
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
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 methodAttachPaymentMethodToCustomerAsync()- Attaches payment method to customerProcessPaymentAsync(long amount, string currency, string description)- Processes immediate paymentCreateAuthorizationAsync(long amount, string currency, string description)- Creates payment holdCaptureAuthorizationAsync(string paymentIntentId, long? amountToCapture)- Captures authorized paymentProcessRefundAsync(string paymentIntentId, long? refundAmount, string reason)- Process refunds
Subscription Management
CreateSubscriptionAsync(string priceId, int? trialPeriodDays)- Creates recurring subscriptionUpdateSubscriptionAsync(string subscriptionId, string newPriceId, string prorationBehavior)- Updates subscriptionCancelSubscriptionAsync(string subscriptionId, bool cancelAtPeriodEnd)- Cancels subscription
Customer Management
CreateOrGetCustomerAsync(string email, string name, string phone)- Creates or retrieves customerGetCustomerPaymentMethodsAsync(string customerId, string type)- Gets customer payment methods
StripePaymentMethod Class
Manages credit card information for Stripe payments.
Properties
CustomerID- Company's subscription IDPaymentMethodID- Unique identifierCardNumber- Last 4 digits onlyCardHolderFullName- Cardholder nameCardType- Card brand (Visa, Mastercard, etc.)ExpirationDate- MM/YY formatIsPreferred- Preferred billing card flag
Methods
SaveToDB(IConfiguration config, bool isUpdate)- Persists to databaseGetCompanyPaymentMethods(IConfiguration config)- Retrieves all company payment methodsValidatePaymentMethodAsync(IConfiguration config)- Validates payment methodDeletePaymentMethodAsync(IConfiguration config)- Deletes payment methodGetPreferredPaymentMethod(string customerId)- Gets preferred payment method
StripeIntentResult Class
Represents payment operation results.
Properties
Success- Operation success statusTransactionId- Stripe PaymentIntent IDAmount- Charged amount (smallest currency unit)Currency- Payment currencyStatus- Payment statusErrorMessage- Error details if failedRequiresAction- Additional authentication neededClientSecret- 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 AImodelName- AI model to useendPointUrl- API endpoint URLapiKey- Authentication keyprompt- User promptpurpose- 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 identifierCustomerID- Customer identifierCallDateTime- Call timestampPurpose- Call purpose/descriptionModelName- Model usedInputTokens/OutputTokens- Token consumptionTotalCost- Calculated costDurationMs- Call durationMetadata- Additional metadata
Methods
RetrieveAzurePricingAsync(IConfiguration config)- Gets current Azure OpenAI pricingSaveAsync(IConfiguration config)- Saves usage dataGetUsageStatisticsAsync(DateTime start, DateTime end, IConfiguration config)- Gets usage statistics
Required Azure Configuration:
Azure:SubscriptionIdAzure:ResourceGroupNameAzure:OpenAIAccountNameAzure:TenantIdAzure:ClientIdAzure: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 positionCurrent- Object at current indexPeek- Current item and index as tupleHasNext/HasPrevious- Navigation availabilityIsValidIndex- Index bounds validation
Navigation Methods
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 settingFind(Predicate<T> match)- Find and set as currentWhere(Func<T, bool> predicate)- Filter to new StateListIntersect(IEnumerable<T> other)- Set intersectionExcept(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 metadataGetObjectProperties<T>()- Cached property infoGetObjectAttributes<TObject, TAttribute>()- Cached property attributesGetEnumAttributes<TEnum, TAttribute>()- Cached enum attributesGetEnumValues<T>()- Cached enum values
Extension Methods
String Extensions
Phone Number Handling
TryValidatePhone(string number)- Validates and gets phone infoFormatPhoneNumber(string phoneNumber)- Formats to international formatMakeReadablePhoneForRegion(string phoneNumber)- Regional formattingToAudiblePhone(string phoneNumber)- Converts to speakable formatConvertPhoneNumberToText(string phoneNumber)- Converts to word representationLooksLikeUSAPhone(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 fillersSplitIntoSentences(string text)- Intelligent sentence splittingWordCount(string phrase)- Word countingRemovePunctuation(string text)- Punctuation removalRemoveSpaces(string text)- Space removalKeepOnlyLetters(string text)- Letter filteringTruncateText(string content, int maxLength)- Smart truncation
String Analysis
IsURL(string text, bool strict = true)- URL detectionExtractLinks(string input)- Link extractionHasAddressFormat(string sentence)- Address pattern detectionIsHtml(string input)- HTML detectionLooksLikeGuid(string text)- GUID pattern detectionHasVerb(string sentence)- Verb detection
Natural Language
Pluralize(string word)- Word pluralizationSingularize(string word)- Word singularizationToTitleCase(string word)- Title casingIsCalendarMonth(string word)- Month detectionToCalendarDate(string text)- Date parsing from natural language
Data Processing
RecursiveSplit(string value)- Multi-delimiter splittingSelectDelimitedData(IEnumerable<string> source, bool scramble)- Delimited data processingReplaceVariables(string str, Dictionary<string, string> variables)- Variable substitutionRemoveEscapeSequences(string text)- Escape sequence removal
DateTime Extensions
Time Comparison
IsDateWithin(DateTime current, int toleranceDays)- Date proximity checkIsDayWithin(DateTime current, int toleranceDays)- Day proximity checkIsDateTimeInRange(DateTime? target, DateTime? start, DateTime? end)- Range checkingIsDateTimeInThePast(DateTime date)- Past date checkIsTimeBetween(DateTimeOffset t, DateTime compare, int startInterval, int endInterval)- Time interval checking
Formatting
ToFilteredDateString(DateTime date)- Table Storage compatible formatToISO860(DateTime date)- ISO 8601 with timezoneToAudibleDateTime(DateTime dt)- Human-readable datetimeToAudibleDateOnly(DateTime dt)- Human-readable dateToAudibleTimeOnly(DateTime dt)- Human-readable time
Timezone Operations
TryConvertToExactTimezone(DateTime value, string sourceTimezone, string targetTimezone)- Timezone conversionGetCurrentTimeInTimezone(string timeZoneId)- Current time in timezoneConvertToLocalTime(DateTime value, string timeZoneId, bool isDaylightSaving)- UTC to local conversion
Collection Extensions
ToStateList<T>(IEnumerable<T> source)- Convert to StateListGetRandom<T>(IEnumerable<T> source)- Random element selectionGetRandom<T>(IEnumerable<T> list, int count)- Multiple random elementsScramble<T>(IEnumerable<T> source)- Random orderingUnCased<T>(Dictionary<string, T> dict)- Case-insensitive dictionary
Email Validation
IsValidEmailAddress(string email)- Email validationDomainName(string email)- Extract domainIsCommonDomainName(string domainName)- Common domain detectionIsDisposableDomainName(string domainName)- Temporary email detectionIsRoleBasedEmail(string email)- Role-based email detectionIsValidDomainName(string domainName)- DNS validation with MX, TXT, DMARC
Numeric Extensions
RoundUp(double currentValue, int nearestWhole)- Round up to nearest wholeRoundUp(double currentValue, double nearestWhole)- Round up to nearest decimalCalculateMarkupAndTax(double cost, double markUpPercentage, bool roundToNickel, bool addMarkup)- Pricing calculationsFormatAmount(double amount, bool roundUp)- Amount formatting
Utilities
Shared Class
Static utility methods and properties.
Properties
TableStorageName- Azure Table Storage account nameTableStorageKey- Azure Table Storage account keyAppConfig- Configuration instanceUserAgent- Standard HTTP User-AgentWebClient- Singleton HttpClient
Methods
Unique Identifiers
CreateUniqueName()- Generates globally unique nameBase36Encode(ulong value)- Base36 encoding
Color Utilities
HexToRgb(string hex)- Hex to RGB conversionGetLuminance(int r, int g, int b)- Color luminance calculationGetContrastColor(string hex)- Contrast color determinationGetSecondaryColor(string primaryColor)- Secondary color selection
Web Operations
ScrapeWebsite(string url, string selector)- Web scrapingDownloadFileAsBytes(string fileUrl)- File download
DNS and Timezone
GetDNSLookupOptions()- DNS configurationGetWindowsIANATimezone(string windowsTimeZoneId)- Timezone conversionGetTimezoneInfo(string IANATimezone)- Timezone information
SerializationHelper Class
JSON serialization with fuzzy deserialization support.
Methods
ToJson(object data)- Object to JSONTryDeserializeJsonString<T>(string json)- Fuzzy deserializationCleanJsonResponse(string response)- JSON cleaning
Features fuzzy property matching for AI-generated JSON with inconsistent naming.
PhoneValidationResult Class
Phone number validation results.
Properties
Status- Validation statusFormattedPhone- International formatCode- Country code (US, NG, CA)Prefix- Phone code (+1, +234)Location- Registration cityTimezone- Phone timezoneCanReceiveSMS- SMS capability
Cryptography
CryptoHelper Class
Encryption and decryption using TripleDES and AES algorithms.
Methods
TripleDES Operations
EncryptString(string plainText)- TripleDES encryptionTryDecryptString(string cipherText)- TripleDES decryption
AES Operations (URL-Safe)
TryUrlEncrypt(string plainText)- AES URL-safe encryptionTryUrlDecrypt(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 charactersPhone- 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
Payment Processing
- Always validate payment methods before processing
- Use authorization/capture for delayed charging
- Store only last 4 digits of card numbers
AI Integration
- Implement usage tracking for cost management
- Use appropriate models for different tasks
- Cache pricing information when possible
Data Management
- Use StateList for navigation-heavy operations
- Leverage TypeCache to reduce reflection overhead
- Implement AsyncProcessingState for large datasets
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
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
- HttpClient - Use the shared
Shared.WebClientsingleton - Type Reflection - Use TypeCache for repeated reflection operations
- Large Collections - Use AsyncProcessingState for memory-efficient iteration
- Fuzzy Matching - Adjust thresholds based on performance needs
- 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 | Versions 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. |
-
net9.0
- ASCDataAccessLibrary (>= 2.0.0)
- DnsClient (>= 1.8.0)
- HtmlAgilityPack (>= 1.12.2)
- libphonenumber-csharp (>= 9.0.10)
- Microsoft.AspNetCore.Http (>= 2.3.0)
- Microsoft.AspNetCore.Http.Features (>= 5.0.17)
- Microsoft.Extensions.Configuration.Abstractions (>= 9.0.7)
- Microsoft.Extensions.Configuration.Json (>= 9.0.7)
- NodaTime (>= 3.2.2)
- Pluralize.NET (>= 1.0.2)
- Stripe.net (>= 48.4.0)
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