Created
December 18, 2022 02:31
-
-
Save xbotter/0306444570ad5b9ef8e675b8371b441f to your computer and use it in GitHub Desktop.
Parse Azure App Service MYSQLCONNSTR to EF connectionstring
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AzureAppServiceMysqlConnectionParser | |
{ | |
const string Database = nameof(Database); | |
const string Server = "Data Source"; | |
const string UId = "User Id"; | |
const string Pwd = "Password"; | |
// example: Database={database};Data Source={host}:{port};User Id={username};Password={password} | |
public static string Parse(string mysqlconnstr) { | |
var builder = new MySqlConnectionStringBuilder(); | |
var _dic = mysqlconnstr.Split(';',StringSplitOptions.RemoveEmptyEntries).Select(c => | |
{ | |
var kv = c.Split('='); | |
return new | |
{ | |
Key = kv[0], | |
value = kv[1] | |
}; | |
}).ToDictionary(kv => kv.Key, kv => kv.value); | |
if(_dic.TryGetValue(Database,out var db)) { | |
builder.Database = db; | |
} | |
if (_dic.TryGetValue(Server, out var server)) | |
{ | |
var serverAndPort = server.Split(new[] { ',', ':' }).ToArray(); | |
builder.Server = serverAndPort[0]; | |
if (serverAndPort.Length > 1 && uint.TryParse(serverAndPort[1], out var _p)) | |
{ | |
builder.Port = _p; | |
} | |
} | |
if(_dic.TryGetValue(UId,out var _uid)) | |
{ | |
builder.UserID = _uid; | |
} | |
if(_dic.TryGetValue(Pwd,out var _pwd)) { | |
builder.Password= _pwd; | |
} | |
return builder.ConnectionString; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment