80 lines
2.7 KiB
C#
Raw Permalink Normal View History

2024-04-15 13:34:57 -05:00
#nullable enable
#region
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text.RegularExpressions;
using MySql.Data.MySqlClient;
#endregion
namespace website {
public static class Utilities {
private static readonly string MySqlPass =
File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "mysql.pass");
private static readonly string MySqlHost =
File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "mysql.host");
private static readonly string MySqlUser =
File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "mysql.user");
public static MySqlConnection getConnection() {
return new MySqlConnection("server=" + MySqlHost + ";pwd=" + MySqlPass + ";uid=" + MySqlUser +
";database=san_antonio_senior_golf;Port=5618;Convert Zero Datetime=True;");
}
/// <summary>
/// Verify if string date can be converted to DateTime
/// </summary>
/// <param name="date"></param>
/// <returns>True if date matches "^[0-9]{4}/[0-9]{2}/[0-9]{2}$"</returns>
public static bool verifyDate(string? date) {
if (date == null)
return false;
Regex regex = new("^[0-9]{4}/[0-9]{2}/[0-9]{2}$", RegexOptions.IgnoreCase);
return regex.IsMatch(date);
}
/// <summary>
/// Check if date param is applicable with verifyDate
/// </summary>
/// <param name="date">Not null string</param>
/// <returns>DateTime equivalent of date param</returns>
// TODO Creating 3 regex's is inefficient
public static DateTime stringDateToDateTime([NotNull] string date) {
int year = int.Parse(new Regex("^[0-9]{4}$").Match(date).Value);
int month = int.Parse(new Regex("/[0-9]{2}/$").Match(date).Value);
int day = int.Parse(new Regex("/[0-9]{2}$").Match(date).NextMatch().Value);
return new DateTime(year, month, day);
}
/// <summary>
/// Verify if string time can be converted to TimeSpan using stringTimeToTimeSpan
/// </summary>
/// <param name="time"></param>
/// <returns>True if time matches "^[0-9]{2}:[0-9]{2}:[0-9]{2}$"</returns>
public static bool verifyTime(string? time) {
if (time == null)
return true;
Regex regex = new("^[0-9]{2}:[0-9]{2}:[0-9]{2}$", RegexOptions.IgnoreCase);
return regex.IsMatch(time);
}
/// <summary>
/// Check if time param is applicable with verifyTime
/// </summary>
/// <param name="time">Not null string</param>
/// <returns>TimeSpan equivalent of time string</returns>
public static TimeSpan stringTimeToTimeSpan([NotNull] string time) {
Match match = new Regex("^[0-9]{2}$").Match(time);
int hours = int.Parse(match.Value);
int minutes = int.Parse(match.NextMatch().Value);
int seconds = int.Parse(match.NextMatch().Value);
return new TimeSpan(hours, minutes, seconds);
}
}
}