Is there any way to interpret (parser) from a string Connection to an object?

Asked

Viewed 106 times

6

There is a certain library that I am using where I need to pass separately as parameter, separately, the connection values with the database: Username, Password, Host and Database.

I took this project and someone else, and noticed that the programmer, in addition to the connectionString used for the database’s default configuration, defined these same data separately through the <appSettings> using the <add key="Key" value="Value"> to implement specifically for this aforementioned library.

I didn’t think it was a good idea, since I would theoretically be repeating the same configuration I already have, only the difference is that it is written in connectionString.

I was wondering if there’s any way to turn one connectionString in a key/value structure.

For example, I would like that string below becomes an object or dictionary.

"Data Source=.\SQLEXPRESS;Initial Catalog=Target_Database;User Id=User; Password=MyPassword"

How can I do that?

3 answers

6


How can you guarantee the format of string can do something like this:

var cs = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;

var dicionario = cs.Split(';').ToDictionary(x => x.Split('=')[0], 
                                            x => x.Split('=')[1], 
                                            StringComparer.OrdinalIgnoreCase);

See working on . NET Fiddle.

This will return a dictionary with this structure

[Data Source, .\SQLEXPRESS]  
[Initial Catalog, Target_Database]  
[User Id, User]  
[Password, MyPassword]

3

One suggestion is to use Regex with and add the results in a dictionary, regex would look like this:

([^\\s].*?)=([^;]+?)(;|$)

 ^     ^     ^        ^
 |     |     |        |
 |     |     |        |
 |     |     |        +---- Verifica se é o final da string
 |     |     |              ou se encontra um ponto virgula
 |     |     |        
 |     |     +------------- Busca o "valor" até encontrar um ;
 |     |             
 |     +------------------- Busca qualquer coisa que representa a chave
 |                  
 +------------------------- A chave não pode extrair o espaço que vier no prefixo

The code should look something like this

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        Dictionary<string, string> configuracoes = new Dictionary<string, string>();

        string re = "([^\\s].*?)=([^;]+?)(;|$)";

        string input = "Data Source=.\\SQLEXPRESS;Initial Catalog=Target_Database;User Id=User; Password=MyPassword";

        foreach (Match m in Regex.Matches(input, re)) {
            //Salva o item
            configuracoes[m.Groups[1].Value] = m.Groups[2].Value;
        }

        //Pegando os itens do dicionário
        Console.WriteLine("Valor: {0}", configuracoes["Data Source"]); // Retorna .\SQLEXPRESS
        Console.WriteLine("Valor: {0}", configuracoes["Initial Catalog"]); // Retorna Target_Database
        Console.WriteLine("Valor: {0}", configuracoes["User Id"]); // Retorna User
        Console.WriteLine("Valor: {0}", configuracoes["Password"]); // Retorna MyPassword
    }
}

Notes:

  • The .Groups[1] take what’s inside the parentheses ([^\\s].*?)
  • The .Groups[2] take what’s inside the parentheses ([^;]+?)

The .Groups[0] would take the whole "match", and the .Groups[3] would take the (;|$), but we won’t use any of them

Example in IDEONE

3

I’d also like to give my two cents here.

After taking a look at the Stackoverflow, I learned that there is a specific class to do this work: System.Data.Common.DbConnectionStringBuilder.

I made an example below just to demonstrate how it would be used.

using System;
using System.Data.Common;

public class Program
{
    public static void Main()
    {
        var builder = new DbConnectionStringBuilder();

        builder.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=Target_Database;User Id=User; Password=MyPassword";

        Console.WriteLine(builder["data source"]);
    }
}

You can access the values of builder through the name of the option used in connectionString. There is no difference between upper and lower case, so it could be used as well builder["Data Source"] to access the value of this property.

TIP: If it is necessary to check, before using, if a property exists, just use the method ContainsKey(). He will return false if the passkey does not exist.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.