Here’s an example of a class in C# that generates a registration random code and includes an expiration date based on a given name:
using System;
public class RegistrationCodeGenerator
{
private const string ValidCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private const int CodeLength = 8;
private const int ExpirationDays = 30;
public string GenerateRegistrationCode(string name)
{
// Generate a random code consisting of uppercase letters and digits
Random random = new Random();
char[] codeChars = new char[CodeLength];
for (int i = 0; i < CodeLength; i++)
{
int index = random.Next(ValidCharacters.Length);
codeChars[i] = ValidCharacters[index];
}
// Generate expiration date based on current date + ExpirationDays
DateTime expirationDate = DateTime.Now.AddDays(ExpirationDays);
// Combine the code and expiration date into a single string
string code = new string(codeChars);
string registrationInfo = $"{name},{expirationDate:yyyy-MM-dd},{code}";
return registrationInfo;
}
public bool ValidateRegistrationCode(string registrationInfo, out string name, out DateTime expirationDate)
{
name = string.Empty;
expirationDate = DateTime.MinValue;
// Split the registrationInfo string into name, expiration date, and code
string[] parts = registrationInfo.Split(',');
if (parts.Length != 3)
{
return false; // Invalid format
}
name = parts[0];
string expirationDateString = parts[1];
string code = parts[2];
// Parse the expiration date
if (!DateTime.TryParseExact(expirationDateString, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out expirationDate))
{
return false; // Invalid expiration date format
}
// Additional validation can be performed here, such as checking the code against a stored value or database.
return true;
}
}
Here’s an example usage of the class:
RegistrationCodeGenerator codeGenerator = new RegistrationCodeGenerator();
string registrationInfo = codeGenerator.GenerateRegistrationCode("John Doe");
Console.WriteLine("Registration Info: " + registrationInfo);
string name;
DateTime expirationDate;
bool isValid = codeGenerator.ValidateRegistrationCode(registrationInfo, out name, out expirationDate);
if (isValid)
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Expiration Date: " + expirationDate.ToString("yyyy-MM-dd"));
}
else
{
Console.WriteLine("Invalid registration code.");
}
In this example, the GenerateRegistrationCode
method generates a random code using the characters defined in ValidCharacters
and combines it with the current date plus the ExpirationDays
value to create the registration information string. The ValidateRegistrationCode
method takes the registration information string and validates it, extracting the name, expiration date, and code if the format is correct.
Note that this implementation is a basic example and does not include any additional validation, such as checking the code against a stored value or database. You can add that functionality based on your specific requirements.