Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var cs = new MsSqlConnectionStringBuilder
- { User = "dmitry", Password = "Password!" }
- .Build();
- Console.WriteLine(cs); // Password=Password!;User=dmitry;
- cs = cs.With("Provider", "MSSQL");
- Console.WriteLine(cs); // Provider=MSSQL;Password=Password!;User=dmitry;
- Console.WriteLine(cs["Provider"]); // MSSQL
- cs = cs.Excerpt("Provider"); // Password=Password!;User=dmitry;
- Console.WriteLine(cs);
- public class MsSqlConnectionStringBuilder
- {
- public string User { get; set; } = "sa";
- public string Password { get; set; }
- public ConnectionString Build() =>
- ConnectionString.Empty
- .With("User", User ?? throw new InvalidOperationException())
- .With("Password", Password ?? throw new InvalidOperationException());
- }
- public sealed class ConnectionString
- {
- public static explicit operator ConnectionString(string text) => Parse(text);
- public static implicit operator string(ConnectionString connectionString) => connectionString.ToString();
- public static readonly ConnectionString Empty = new ConnectionString(ConnectionParameter.None);
- public static ConnectionString Parse(string text, string regex = "(?<name>[^=]+)=(?<value>[^;]);?") =>
- new ConnectionString(
- new Regex(regex ?? throw new ArgumentNullException(nameof(regex)))
- .Matches(text ?? throw new ArgumentNullException(nameof(text)))
- .Select(m => new ConnectionParameter(m.Groups["name"].Value, m.Groups["value"].Value)));
- ConnectionString(IEnumerable<ConnectionParameter> parameters)
- {
- Parameters = parameters.ToArray();
- }
- IEnumerable<ConnectionParameter> Parameters { get; }
- public string this[string name] => Parameters
- .FirstOrDefault(p => p.Name.ToUpper() == name.ToUpper())?.Value;
- public ConnectionString With(string name, object value) =>
- new ConnectionString(Parameters
- .Prepend(new ConnectionParameter(name, $"{value}")));
- public ConnectionString Excerpt(string name) =>
- new ConnectionString(Enumerable.Concat(
- Parameters.TakeWhile(p => p.Name.ToUpper() != name.ToUpper()),
- Parameters.SkipWhile(p => p.Name.ToUpper() != name.ToUpper()).Skip(1)));
- public override string ToString() => ToString("{0}={1};");
- public string ToString(string format) =>
- string.Join("", from p in Parameters
- select string.Format(format, p.Name, p.Value));
- }
- sealed class ConnectionParameter
- {
- public static readonly ConnectionParameter[] None = new ConnectionParameter[0];
- internal ConnectionParameter(string name, string value)
- {
- Name = name ?? throw new ArgumentNullException(nameof(name));
- Value = value ?? throw new ArgumentNullException(nameof(value));
- }
- public string Name { get; }
- public string Value { get; }
- }
Add Comment
Please, Sign In to add comment