Создание псевдонима SQL Server с использованием WMI на x64 - PullRequest
1 голос
/ 16 августа 2010

У меня есть небольшое приложение, которое автоматически создает необходимые записи псевдонимов SQL Server для некоторых серверов.Большая часть кода выглядит следующим образом:

        private static void SetAlias(string aliasName, string server, string protocol, int? port)
        {
            var scope = new ManagementScope(@"\\.\root\Microsoft\SqlServer\ComputerManagement10");
            try
            {
                scope.Connect();

            }
            catch
            {
                scope = new ManagementScope(@"\\.\root\Microsoft\SqlServer\ComputerManagement");
            }
            var clientAlias = new ManagementClass(scope, new ManagementPath("SqlServerAlias"), null);
            clientAlias.Get();

            foreach (ManagementObject existingAlias in clientAlias.GetInstances())
            {
                existingAlias.Get();
                if (String.Equals((String)existingAlias.GetPropertyValue("AliasName"), aliasName))
                {
                    UpdateAlias(existingAlias, aliasName, server, protocol, port);
                    return;
                }
            }

            // create new
            ManagementObject newAlias = clientAlias.CreateInstance();
            UpdateAlias(newAlias, aliasName, server, protocol, port);
            newAlias.Put();
        }

        private static void UpdateAlias(ManagementObject alias, string aliasName, string server, string protocol, int? port)
        {
            alias.SetPropertyValue("AliasName", aliasName);
            alias.SetPropertyValue("ServerName", server);
            alias.SetPropertyValue("ProtocolName", protocol);
            alias.SetPropertyValue("ConnectionString", port != null ? port.ToString() : string.Empty);
        }

Это правильно создает нужные записи в 32-битных ОС, однако в 64-битных ОС мне нужны псевдонимы, также добавленные в 64-битную конфигурацию клиента SQL Server.*

Есть идеи, как это сделать?

Спасибо.

Ответы [ 2 ]

3 голосов
/ 16 августа 2010

Я оставлю ответ реестра на месте, так как он жизнеспособен, но вы можете использовать Контекст в ConnectionOptions, чтобы указать арку (int, 32 или 64)

Пример доступа к обоим из 64-разрядных:

    static void Main(string[] args)
    {
        var options = new ConnectionOptions();

        if (Environment.Is64BitOperatingSystem && Environment.Is64BitProcess == false)
        {
            Console.WriteLine("Please build as AnyCPU or x64");
            return;
        }

        // default behavior, should be 64-bit WMI provider
        Console.WriteLine("Print 64-bit aliases");
        PrintAliases(options);

        // specify the 32-bit arch
        Console.WriteLine("Print 32-bit aliases");
        options.Context.Add("__ProviderArchitecture", 32);
        PrintAliases(options);
    }

    private static void PrintAliases(ConnectionOptions options)
    {
        var scope = new ManagementScope(@"\\.\root\Microsoft\SqlServer\ComputerManagement10", options);
        try
        {
            scope.Connect();
        }
        catch
        {
            scope = new ManagementScope(@"\\.\root\Microsoft\SqlServer\ComputerManagement");
        }
        var clientAlias = new ManagementClass(scope, new ManagementPath("SqlServerAlias"), null);
        clientAlias.Get();

        foreach (ManagementObject existingAlias in clientAlias.GetInstances())
        {
            existingAlias.Get();
            var propertiesToRead = new[] { "AliasName", "ServerName", "ProtocolName", "ConnectionString" };
            foreach (var propertyToRead  in propertiesToRead)
            {
                Console.WriteLine("Property {0} = {1}", propertyToRead, existingAlias.GetPropertyValue(propertyToRead));
            }
        }
    }

Пример доступа к обоим из 32-битных систем (ПРИМЕЧАНИЕ: конечно, можно просто заставить дугу 32 и 64 независимо от разрядности процесса)

class Program
{
    static void Main(string[] args)
    {
        var options = new ConnectionOptions();

        if (Environment.Is64BitProcess)
        {
            Console.WriteLine("Please run this sample as 32-bit");
            return;
        }

        // default behavior, should be 32-bit WMI provider since we build as x86
        Console.WriteLine("Print 32-bit aliases");
        PrintAliases(options);

        // also prints 32-bit aliases
        options.Context.Add("__ProviderArchitecture", 32);
        PrintAliases(options);

        // specify the 64-bit arch
        if (Environment.Is64BitOperatingSystem)
        {
            Console.WriteLine("Print 64-bit aliases");
            options.Context.Add("__ProviderArchitecture", 64);
            PrintAliases(options);
        }
    }

    private static void PrintAliases(ConnectionOptions options)
    {
        var scope = new ManagementScope(@"\\.\root\Microsoft\SqlServer\ComputerManagement10", options);
        try
        {
            scope.Connect();
        }
        catch
        {
            scope = new ManagementScope(@"\\.\root\Microsoft\SqlServer\ComputerManagement");
        }
        var clientAlias = new ManagementClass(scope, new ManagementPath("SqlServerAlias"), null);
        clientAlias.Get();

        foreach (ManagementObject existingAlias in clientAlias.GetInstances())
        {
            existingAlias.Get();
            var propertiesToRead = new[] { "AliasName", "ServerName", "ProtocolName", "ConnectionString" };
            foreach (var propertyToRead  in propertiesToRead)
            {
                Console.WriteLine("Property {0} = {1}", propertyToRead, existingAlias.GetPropertyValue(propertyToRead));
            }
        }
    }
1 голос
/ 16 августа 2010

Когда я в последний раз смотрел на это, псевдонимы клиентов просто сохранялись в реестре (HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ MSSQLServer \ Client \ ConnectTo), поэтому самый простой маршрут - запись в оба WoW (HKEY_LOCAL_MACHINE \ SOFTWARE \ Wow6432Node \ Microsoft \ MSSQLServer \ Client \ ConnectTo) и «нормальные» местоположения при работе на x64. Обратите внимание, что если вы работаете как 32-битный процесс, вам нужно либо вызвать p / invoke, либо (если используется .net 4) указать 64-битное представление при написании 64-битной версии.

...