DocumentDB .Net客户端使用连接字符串

时间:2017-01-16 19:04:43

标签: c# azure-cosmosdb

我检查了DocumentDB上的MSDN for .Net(here)并找到了3个有效的构造函数。但是他们都没有使用连接字符串,这听起来很奇怪。

是否真的没有办法用连接字符串而不是端点+ authKey组合来实例化客户端,或者我错过了什么?

例如,大多数其他Microsoft服务都使用此概念,即https://docs.microsoft.com/en-us/azure/storage/storage-configure-connection-string#parsing-a-connection-string。 在我们的例子中,如果所有Azure相关的东西都以相同的方式初始化,那将是超级的。只是更清洁,而不是停止显示。

P.S。 请停止告诉我有关Uri和authKey参数的现有构造函数,问题(略有)不同。我可以按照自己提供的链接,无需帮助。感谢。

4 个答案:

答案 0 :(得分:8)

我创建了一个用于解析连接字符串的类,类似于CloudStorageAccount.Parse的工作方式。我试图尽可能地遵循他们的模式,以防他们决定开源它,这可能有希望在没有太大变化的情况下做出贡献。

public static class DocumentDbAccount
{
    public static DocumentClient Parse(string connectionString)
    {
        DocumentClient ret;

        if (String.IsNullOrWhiteSpace(connectionString))
        {
            throw new ArgumentException("Connection string cannot be empty.");
        }

        if(ParseImpl(connectionString, out ret, err => { throw new FormatException(err); }))
        {
            return ret;
        }

        throw new ArgumentException($"Connection string was not able to be parsed into a document client.");
    }

    public static bool TryParse(string connectionString, out DocumentClient documentClient)
    {
        if (String.IsNullOrWhiteSpace(connectionString))
        {
            documentClient = null;
            return false;
        }

        try
        {
            return ParseImpl(connectionString, out documentClient, err => { });
        }
        catch (Exception)
        {
            documentClient = null;
            return false;
        }
    }

    private const string AccountEndpointKey = "AccountEndpoint";
    private const string AccountKeyKey = "AccountKey";
    private static readonly HashSet<string> RequireSettings = new HashSet<string>(new [] { AccountEndpointKey, AccountKeyKey }, StringComparer.OrdinalIgnoreCase);

    internal static bool ParseImpl(string connectionString, out DocumentClient documentClient, Action<string> error)
    {
        IDictionary<string, string> settings = ParseStringIntoSettings(connectionString, error);

        if (settings == null)
        {
            documentClient = null;
            return false;
        }

        if (!RequireSettings.IsSubsetOf(settings.Keys))
        {
            documentClient = null;
            return false;
        }

        documentClient = new DocumentClient(new Uri(settings[AccountEndpointKey]), settings[AccountKeyKey]);
        return true;
    }

    /// <summary>
    /// Tokenizes input and stores name value pairs.
    /// </summary>
    /// <param name="connectionString">The string to parse.</param>
    /// <param name="error">Error reporting delegate.</param>
    /// <returns>Tokenized collection.</returns>
    private static IDictionary<string, string> ParseStringIntoSettings(string connectionString, Action<string> error)
    {
        IDictionary<string, string> settings = new Dictionary<string, string>();
        string[] splitted = connectionString.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (string nameValue in splitted)
        {
            string[] splittedNameValue = nameValue.Split(new char[] { '=' }, 2);

            if (splittedNameValue.Length != 2)
            {
                error("Settings must be of the form \"name=value\".");
                return null;
            }

            if (settings.ContainsKey(splittedNameValue[0]))
            {
                error(string.Format(CultureInfo.InvariantCulture, "Duplicate setting '{0}' found.", splittedNameValue[0]));
                return null;
            }

            settings.Add(splittedNameValue[0], splittedNameValue[1]);
        }

        return settings;
    }
}

答案 1 :(得分:6)

DocumentDB SDK没有使用连接字符串的构造函数重载。它们支持使用端点+主密钥和端点+权限/资源令牌进行初始化。

如果您想查看单个连接字符串参数,请在此处提出/ upvote:https://feedback.azure.com/forums/263030-documentdb

答案 2 :(得分:6)

实际上,您可以通过环形交叉路口来做到这一点。

internal class CosmosDBConnectionString
{
    public CosmosDBConnectionString(string connectionString)
    {
        // Use this generic builder to parse the connection string
        DbConnectionStringBuilder builder = new DbConnectionStringBuilder
        {
            ConnectionString = connectionString
        };

        if (builder.TryGetValue("AccountKey", out object key))
        {
            AuthKey = key.ToString();
        }

        if (builder.TryGetValue("AccountEndpoint", out object uri))
        {
            ServiceEndpoint = new Uri(uri.ToString());
        }
    }

    public Uri ServiceEndpoint { get; set; }

    public string AuthKey { get; set; }
}

然后

var cosmosDBConnectionString = new CosmosDBConnectionString(connectionString)
var client = new DocumentClient(
            cosmosDBConnectionString.ServiceEndpoint,
            cosmosDBConnectionString.AuthKey)

这取自Azure WebJobs扩展SDK,这是Azure Functions V2能够仅使用连接字符串的方式。省去了尝试自己解析字符串的麻烦。

答案 3 :(得分:2)

对我有用:

#include <stdio.h>
#include <string.h>

void login(){
    char username[100];
    char pass[100]; 


    int i = 0;
    while( i < 3){
        printf("Enter the username : ");
        scanf("%s", &username);
        printf("Password : ");
        scanf("%s", &pass);

        printf("%s %s \n", username, pass);

        if ((strcmp(username, "a")==0) && (strcmp(pass, "a")==0)){
            printf("You are sucessfull login into your account");
            BilaDahLogin();
            break;

        }
        else{
            printf("The username or password incorrect\nTry again\n");
            i += 1;
        }

    }

}