Condividi tramite


Esempio Pronto di Hello World

L'esempio Hello World Ready illustra le operazioni di base coinvolte nella creazione, distribuzione e test di una stored procedure semplice basata sull'integrazione basata su CLR (World Ready). Un componente pronto per il mondo può essere facilmente localizzato in lingue diverse per diversi mercati in tutto il mondo senza modificare il codice sorgente del componente. In questo esempio viene inoltre illustrato come restituire dati tramite un parametro di output e tramite un record, costruito dinamicamente dalla stored procedure e restituito al client. Questo esempio è quasi identico all'esempio Hello World, ad eccezione del fatto che è molto più semplice e sicuro localizzare questa applicazione. Per modificare il testo localizzato, è necessario quanto segue:

  1. Modifica di un file XML (file .resx ) per le impostazioni cultura specifiche nella directory resources

  2. Compilazione del file di risorse delle impostazioni cultura tramite resgen

  3. Compilazione della DLL satellite aggiornata per tali impostazioni cultura

  4. Eliminazione e aggiunta di tale assembly in SQL Server

Il codice sorgente e l'assembly per la stored procedure CLR stessa non cambia. Viene build.cmd fornito uno script che illustra come compilare e collegare gli assembly di risorse. Anche se il codice sorgente per l'applicazione crea un gestore risorse basato sull'assembly attualmente in esecuzione, non è necessario incorporare le risorse indipendenti dalle impostazioni cultura nella DLL che contiene la stored procedure. System.Resources.NeutralResourcesLanguage attribute consente l'esistenza di risorse indipendenti dalle impostazioni cultura in una DLL satellite. È molto meglio usare una DLL separata a questo scopo in modo che, quando è necessario aggiungere o modificare il testo localizzato, la DLL primaria che contiene la stored procedure CLR non deve essere modificata. Ciò è particolarmente utile per i tipi CLR definiti dall'utente che potrebbero avere colonne e altre dipendenze che renderebbero difficile eliminare e riaggiungere il tipo. In genere, le versioni dll satellite devono essere identiche alla versione principale dell'assembly. Tuttavia, è possibile usare l'attributo SatelliteContractVersion per consentire l'aggiornamento dell'assembly principale senza aggiornare anche gli assembly satellite. Per altre informazioni, vedere la ResourceManager classe nella documentazione di Microsoft .NET.

Prerequisiti

Questo esempio funziona solo con SQL Server 2005 e versioni successive.

Per creare ed eseguire questo progetto, è necessario installare il software seguente:

  • SQL Server o SQL Server Express. È possibile ottenere gratuitamente SQL Server Express dalla documentazione di SQL Server Express e dal sito Web degli esempi

  • Database AdventureWorks disponibile nel sito Web per sviluppatori di SQL Server

  • .NET Framework SDK 2.0 o versione successiva o Microsoft Visual Studio 2005 o versione successiva. È possibile ottenere gratuitamente .NET Framework SDK.

  • Inoltre, devono essere soddisfatte le condizioni seguenti:

  • L'istanza di SQL Server in uso deve avere l'integrazione CLR abilitata.

  • Per abilitare l'integrazione con CLR, seguire questa procedura:

    Abilitazione dell'integrazione con CLR

    • Eseguire i comandi di Transact-SQL seguenti:

    sp_configure 'clr enabled', 1

    GO

    RECONFIGURE

    GO

    Annotazioni

    Per abilitare CLR, è necessario disporre ALTER SETTINGS dell'autorizzazione a livello di server, che viene mantenuta in modo implicito dai membri dei ruoli predefiniti del sysadmin server e serveradmin .

  • Il database AdventureWorks deve essere installato nell'istanza di SQL Server in uso.

  • Se non si è un amministratore per l'istanza di SQL Server in uso, è necessario disporre di un amministratore che conceda l'autorizzazione CreateAssembly per completare l'installazione.

Compilazione dell'esempio

Creare ed eseguire l'esempio usando le istruzioni seguenti:

  1. Aprire un prompt dei comandi di Visual Studio o .NET Framework.

  2. Se necessario, creare una directory per l'esempio. Per questo esempio si userà C:\MySample.

  3. In c:\MySample creare HelloWorld.vb (per l'esempio di Visual Basic) o HelloWorld.cs (per l'esempio C#) e copiare il codice di esempio di Visual Basic o C# appropriato (di seguito) nel file.

  4. In c:\MySample creare il file messages.resx e copiare il codice di esempio nel file.

  5. In c:\MySample creare il file salvando il file messages.de.resxmessages.resx come messages.de.resx dopo aver modificato la riga

    • <value xml:space="preserve">Hello, World!</value>

    • Leggere

    • <value xml:space="preserve">Hallo Welt!</value>

  6. In c:\MySample creare il file salvando il file messages.es.resxmessages.resx come messages.es.resx dopo aver modificato la riga

    • <value xml:space="preserve">Hello, World!</value>

    • Leggere

    • <value xml:space="preserve">Hola a todos</value>

  7. In c:\MySample creare il file salvando il file messages.fr.resxmessages.resx come messages.fr.resx dopo aver modificato la riga

    • <value xml:space="preserve">Hello, World!</value>

    • Leggere

    • <value xml:space="preserve">Bonjour !</value>

  8. In c:\MySample creare il file salvando il file messages.fr-FR.resxmessages.resx come messages.fr-FR.resx dopo aver modificato la riga

    • <value xml:space="preserve">Hello, World!</value>

    • Leggere

    • <value xml:space="preserve">Bonjour de France!</value>

  9. In c:\MySample creare il file salvando il file messages.it.resxmessages.resx come messages.it.resx dopo aver modificato la riga

    • <value xml:space="preserve">Hello, World!</value>

    • Leggere

    • <value xml:space="preserve">Buongiorno</value>

  10. In c:\MySample creare il file salvando il file messages.ja.resxmessages.resx come messages.ja.resx dopo aver modificato la riga

    • <value xml:space="preserve">Hello, World!</value>

    • Leggere

    • <value xml:space="preserve"> ã"ã‚"にちは</value>

  11. In c:\MySample creare il file build.com e copiare il codice di esempio nel file

  12. Compilare il satellite assembla eseguendo la compilazione del file al prompt dei comandi.

  13. Compilare il codice di esempio dal prompt della riga di comando eseguendo una delle operazioni seguenti:

    • Vbc /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll,C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll,C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /out:HelloWorldReady.dll /target:library HelloWorld.vb

    • Csc /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.XML.dll /out:HelloWorldReady.dll /target:library Hello.csCopy the tsql installation code into a file and save it as Install.sql in the sample directory.

  14. Se l'esempio viene installato in una directory diversa, C:\MySample\modificare il file Install.sql come indicato in modo che punti a tale percorso.

  15. Distribuire l'assembly e la stored procedure eseguendo

    • sqlcmd -E -I -i install.sql
  16. Copiare Transact-SQL script del comando di test in un file e salvarlo come test.sql nella directory di esempio.

  17. Eseguire lo script di test con il comando seguente

    • sqlcmd -E -I -i test.sql
  18. Copiare lo script di pulizia Transact-SQL in un file e salvarlo come cleanup.sql nella directory di esempio.

  19. Eseguire lo script con il comando seguente

    • sqlcmd -E -I -i cleanup.sql

Codice di esempio

Di seguito sono riportati gli elenchi di codice per questo esempio.

C#

using System;  
using System.Data;  
using System.Data.Sql;  
using System.Data.SqlTypes;  
using Microsoft.SqlServer.Server;  
using System.Globalization;  
using System.Threading;  
using System.Resources;  
using System.Reflection;  
using System.Runtime.CompilerServices;  
  
[assembly: System.Resources.NeutralResourcesLanguage("", System.Resources.UltimateResourceFallbackLocation.Satellite)]  
[assembly: System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum)]  
[assembly: System.Runtime.ConstrainedExecution.ReliabilityContract(System.Runtime.ConstrainedExecution.Consistency.MayCorruptInstance, System.Runtime.ConstrainedExecution.Cer.None)]  
  
    public sealed partial class StoredProcedures  
    {  
        private StoredProcedures()  
        {  
        }  
  
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters"), Microsoft.SqlServer.Server.SqlProcedure]  
        public static void HelloWorldReady(string culture, out string greeting)  
        {  
ResourceManager rm   
= new ResourceManager("Messages",   
Assembly.GetExecutingAssembly());  
  
string message = rm.GetString("HelloWorld", CultureInfo.GetCultureInfo(culture));  
  
            Microsoft.SqlServer.Server.SqlMetaData columnInfo  
                = new Microsoft.SqlServer.Server.SqlMetaData("Column1", SqlDbType.NVarChar, 24);  
            SqlDataRecord greetingRecord  
                = new SqlDataRecord(new Microsoft.SqlServer.Server.SqlMetaData[] { columnInfo });  
            greetingRecord.SetString(0, message);  
            SqlContext.Pipe.Send(greetingRecord);  
            greeting = message;  
        }  
    }  
  

Visual Basic

Imports System  
Imports System.Data  
Imports System.Data.Sql  
Imports System.Data.SqlTypes  
Imports Microsoft.SqlServer.Server  
Imports System.Globalization  
Imports System.Resources  
Imports System.Reflection  
Imports System.Runtime.InteropServices  
<Assembly: AssemblyVersion("1.0.*")>   
<Assembly: System.Runtime.InteropServices.ComVisible(False)>   
<Assembly: System.CLSCompliant(True)>   
<Assembly: System.Resources.NeutralResourcesLanguage("", System.Resources.UltimateResourceFallbackLocation.Satellite)>   
<Assembly: System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.RequestMinimum)>   
<Assembly: System.Runtime.ConstrainedExecution.ReliabilityContract(System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, Runtime.ConstrainedExecution.Cer.None)>   
  
Partial Public NotInheritable Class StoredProcedures  
    Private Sub New()  
    End Sub  
    <Microsoft.SqlServer.Server.SqlProcedure()> _  
    Public Shared Sub HelloWorldReady(ByVal culture As String, ByRef greeting As String)  
        Dim rm As New ResourceManager("Messages", Assembly.GetExecutingAssembly())  
        Dim message As String = rm.GetString("HelloWorld", CultureInfo.GetCultureInfo(culture))  
        Dim columnInfo As New Microsoft.SqlServer.Server.SqlMetaData("Column1", _  
            SqlDbType.NVarChar, 24)  
        Dim greetingRecord As New SqlDataRecord(New  _  
            Microsoft.SqlServer.Server.SqlMetaData() {columnInfo})  
        greetingRecord.SetString(0, message)  
        SqlContext.Pipe.Send(greetingRecord)  
        greeting = message  
    End Sub  
End Class  
  

Si tratta di build.com, che compila gli assembly satellite.

resgen Messages.resx  
resgen Messages.de.resx  
resgen Messages.es.resx  
resgen Messages.fr.resx  
resgen Messages.fr-Fr.resx  
resgen Messages.it.resx  
resgen Messages.ja.resx  
if not exist de/ mkdir de  
if not exist es/ mkdir es  
if not exist fr/ mkdir fr  
if not exist fr-FR/ mkdir fr-FR  
if not exist it/ mkdir it  
if not exist ja/ mkdir ja  
al /t:lib /culture:de /embed:Messages.de.resources /out:de\HelloWorldReady.resources.dll  
al /t:lib /culture:es /embed:Messages.es.resources /out:es\HelloWorldReady.resources.dll  
al /t:lib /culture:fr /embed:Messages.fr.resources /out:fr\HelloWorldReady.resources.dll  
al /t:lib /culture:fr-FR /embed:Messages.fr-FR.resources /out:fr-FR\HelloWorldReady.resources.dll  
al /t:lib /culture:it /embed:Messages.it.resources /out:it\HelloWorldReady.resources.dll  
al /t:lib /culture:ja /embed:Messages.ja.resources /out:ja\HelloWorldReady.resources.dll  
al /t:lib /culture:"" /embed:Messages.resources /out:HelloWorldReady.resources.dll  

Si tratta dell'Transact-SQL script di installazione (Install.sql), che distribuisce gli assembly e crea la stored procedure all'interno del database.

USE AdventureWorks  
GO  
  
-- Drop existing sproc and assembly if any.  
  
IF EXISTS (SELECT * FROM sys.procedures WHERE [name] = 'usp_HelloWorldReady')  
DROP PROCEDURE usp_HelloWorldReady;  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady')  
DROP ASSEMBLY HelloWorldReady;  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.neutral')  
DROP ASSEMBLY [HelloWorldReady.resources.neutral]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.de')  
DROP ASSEMBLY [HelloWorldReady.resources.de]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.es')  
DROP ASSEMBLY [HelloWorldReady.resources.es]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.fr')  
DROP ASSEMBLY [HelloWorldReady.resources.fr]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.fr-FR')  
DROP ASSEMBLY [HelloWorldReady.resources.fr-FR]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.it')  
DROP ASSEMBLY [HelloWorldReady.resources.it]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.ja')  
DROP ASSEMBLY [HelloWorldReady.resources.ja]  
GO  
  
DECLARE @SamplesPath nvarchar(1024)  
-- You may need to modify the value of this variable if you have installed the sample someplace other than the default location.  
Set @SamplesPath = N'C:\MySample\'  
  
-- Add the assembly and CLR integration based stored procedure  
  
CREATE ASSEMBLY HelloWorldReady  
FROM @SamplesPath + 'HelloWorldReady.dll'  
WITH permission_set = Safe;  
  
CREATE ASSEMBLY [HelloWorldReady.resources.neutral]  
FROM @SamplesPath + 'HelloWorldReady.resources.dll'  
WITH permission_set = Safe;   
  
CREATE ASSEMBLY [HelloWorldReady.resources.de]  
FROM @SamplesPath + '\de\HelloWorldReady.resources.dll'  
WITH permission_set = Safe;  
  
CREATE ASSEMBLY [HelloWorldReady.resources.es]  
FROM @SamplesPath + '\es\HelloWorldReady.resources.dll'  
WITH permission_set = Safe;  
  
CREATE ASSEMBLY [HelloWorldReady.resources.fr]  
FROM @SamplesPath + '\fr\HelloWorldReady.resources.dll'  
WITH permission_set = Safe;  
  
CREATE ASSEMBLY [HelloWorldReady.resources.fr-FR]  
FROM @SamplesPath + '\fr-FR\HelloWorldReady.resources.dll'  
WITH permission_set = Safe;  
  
CREATE ASSEMBLY [HelloWorldReady.resources.it]  
FROM @SamplesPath + '\it\HelloWorldReady.resources.dll'  
WITH permission_set = Safe;  
  
CREATE ASSEMBLY [HelloWorldReady.resources.ja]  
FROM @SamplesPath + '\ja\HelloWorldReady.resources.dll'  
WITH permission_set = Safe;  
GO  
  
CREATE PROCEDURE usp_HelloWorldReady  
(  
@Culture NVarchar(12),  
@Greeting NVarchar(24) OUTPUT  
)  
AS EXTERNAL NAME HelloWorldReady.StoredProcedures.HelloWorldReady;  
GO  
  
USE master;  
GO  

Si tratta di test.sql, che testa l'esempio eseguendo le funzioni in ogni impostazione locale.

USE AdventureWorks  
GO  
  
DECLARE @GreetingDe nvarchar(24);  
DECLARE @GreetingDe_CH nvarchar(24);  
DECLARE @GreetingEn nvarchar(24);  
DECLARE @GreetingEs nvarchar(24);  
DECLARE @GreetingFr nvarchar(24);  
DECLARE @GreetingFr_FR nvarchar(24);  
DECLARE @GreetingIt nvarchar(24);  
DECLARE @GreetingJa nvarchar(24);  
  
--German as spoken anywhere in the world (the neutral German culture)  
EXEC usp_HelloWorldReady 'de', @GreetingDe OUTPUT;  
--German as spoken in Switzerland.  Because we don't have a specific assembly  
--for this case, the .NET Framework will automatically fall back to the neutral German culture DLL.  
EXEC usp_HelloWorldReady 'de-CH', @GreetingDe_CH OUTPUT;  
EXEC usp_HelloWorldReady 'en', @GreetingEn OUTPUT;  
EXEC usp_HelloWorldReady 'es', @GreetingEs OUTPUT;  
--French as spoken anywhere in the world (the neutral French culture)  
EXEC usp_HelloWorldReady 'fr', @GreetingFr OUTPUT  
--French as spoken in France.  Since we do have a specific assembly for this case, a specific   
--greeting is provided from that DLL.  The neutral French culture DLL is not used in this case.  
EXEC usp_HelloWorldReady 'fr-FR', @GreetingFr_FR OUTPUT  
EXEC usp_HelloWorldReady 'it', @GreetingIt OUTPUT;  
EXEC usp_HelloWorldReady 'ja', @GreetingJa OUTPUT;  
  
SELECT @GreetingDe AS OUTPUT_PARAMETER_DE;  
SELECT @GreetingDe_CH AS OUTPUT_PARAMETER_De_CH;  
SELECT @GreetingEn AS OUTPUT_PARAMETER_EN;  
SELECT @GreetingEs AS OUTPUT_PARAMETER_ES;  
SELECT @GreetingFr AS OUTPUT_PARAMETER_FR;  
SELECT @GreetingFr_FR AS OUTPUT_PARAMETER_Fr_FR;  
SELECT @GreetingIt AS OUTPUT_PARAMETER_IT;  
SELECT @GreetingJa AS OUTPUT_PARAMETER_JA;  
  
GO  

Nell'Transact-SQL seguente vengono rimossi gli assembly e la stored procedure dal database.

USE AdventureWorks;  
GO  
  
-- Drop existing sproc and assembly if any.  
  
IF EXISTS (SELECT * FROM sys.procedures WHERE [name] = 'usp_HelloWorldReady')  
DROP PROCEDURE usp_HelloWorldReady;  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady')  
DROP ASSEMBLY HelloWorldReady;  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.neutral')  
DROP ASSEMBLY [HelloWorldReady.resources.neutral]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.de')  
DROP ASSEMBLY [HelloWorldReady.resources.de]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.es')  
DROP ASSEMBLY [HelloWorldReady.resources.es]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.fr')  
DROP ASSEMBLY [HelloWorldReady.resources.fr]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.fr-FR')  
DROP ASSEMBLY [HelloWorldReady.resources.fr-FR]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.it')  
DROP ASSEMBLY [HelloWorldReady.resources.it]  
GO  
  
IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'HelloWorldReady.resources.ja')  
DROP ASSEMBLY [HelloWorldReady.resources.ja]  
GO  
  
USE master;  
GO  

Vedere anche

Scenari di utilizzo ed esempi per l'integrazione con CLR (Common Language Runtime)