Utilizzo di un DataSet da un servizio Web XML

Il DataSet è stato progettato con una struttura disconnessa, in parte per facilitare il trasporto di dati su Internet. Il DataSet e la DataTable sono "serializzabili", in quanto è possibile specificarli come input in o output da servizi Web XML, senza che sia necessaria la scrittura di codice aggiuntivo per eseguire lo streaming dei contenuti del DataSet da un servizio Web XML a un client e viceversa. Il DataSet viene convertito implicitamente in un flusso XML tramite il formato DiffGram, viene inviato in rete e ricreato come DataSet dal flusso XML nel punto di ricezione. Si tratta quindi di un metodo molto semplice e flessibile per la trasmissione e la restituzione di dati relazionali tramite i servizi Web XML. Per ulteriori informazioni sul formato DiffGram, vedere DiffGram.

Nell'esempio seguente vengono illustrati i passaggi per la creazione di un servizio Web XML e di un client per tale servizio, che si avvalgono del DataSet per il trasporto dei dati relazionali, incluse le modifiche a tali dati, e per la risoluzione di eventuali aggiornamenti fino all'origine dati originale.

Nota   Nella creazione di un servizio Web XML è opportuno tenere sempre presenti le implicazioni inerenti la protezione. Per informazioni sulla protezione dei servizi Web XML, vedere Protezione dei servizi Web XML creati con ASP.NET.

Per creare un servizio Web XML che restituisca e utilizzi un DataSet

  1. Creare il servizio Web XML.

    Nell'esempio seguente viene creato un servizio Web XML che restituisce dati, in questo caso un elenco di clienti contenuto nel database Northwind, e riceve un DataSet con aggiornamenti ai dati, che vengono risolti dal servizio Web XML fino all'origine dati originale.

    Due metodi vengono esposti dal servizio Web XML: GetCustomers, che consente la restituzione dell'elenco di clienti, e UpdateCustomers, che consente di risolvere gli aggiornamenti fino all'origine dati. Il servizio Web XML viene memorizzato in un file sul server Web denominato DataSetSample.asmx. Nel codice seguente vengono descritti i contenuti del file DataSetSample.asmx.

    <% @ WebService Language = "VB" Class = "Sample" %>
    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Web.Services
    
    <WebService(Namespace:="https://microsoft.com/webservices/")> _
    Public Class Sample
    
      Public nwindConn As SqlConnection = New SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind")
    
      <WebMethod( Description := "Returns Northwind Customers", EnableSession := False )> _
      Public Function GetCustomers() As DataSet
        Dim custDA As SqlDataAdapter = New SqlDataAdapter("SELECT CustomerID, CompanyName FROM Customers", nwindConn)
    
        Dim custDS As DataSet = New DataSet()
        custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey
        custDA.Fill(custDS, "Customers")
    
        GetCustomers = custDS
      End Function
    
      <WebMethod( Description := "Updates Northwind Customers", EnableSession := False )> _
      Public Function UpdateCustomers(custDS As DataSet) As DataSet
        Dim custDA As SqlDataAdapter = New SqlDataAdapter()
    
        custDA.InsertCommand = New SqlCommand("INSERT INTO Customers (CustomerID, CompanyName) " & _
                                              "Values(@CustomerID, @CompanyName)", nwindConn)
        custDA.InsertCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID")
        custDA.InsertCommand.Parameters.Add("@CompanyName", SqlDbType.NChar, 15, "CompanyName")
    
        custDA.UpdateCommand = New SqlCommand("UPDATE Customers Set CustomerID = @CustomerID, " & _
                                              "CompanyName = @CompanyName WHERE CustomerID = @OldCustomerID", nwindConn)
        custDA.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID")
        custDA.UpdateCommand.Parameters.Add("@CompanyName", SqlDbType.NChar, 15, "CompanyName")
    
        Dim myParm As SqlParameter = custDA.UpdateCommand.Parameters.Add("@OldCustomerID", SqlDbType.NChar, 5, "CustomerID")
        myParm.SourceVersion = DataRowVersion.Original
    
        custDA.DeleteCommand = New SqlCommand("DELETE FROM Customers WHERE CustomerID = @CustomerID", nwindConn)
        myParm = custDA.DeleteCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID")
        myParm.SourceVersion = DataRowVersion.Original
    
        custDA.Update(custDS, "Customers")
    
        UpdateCustomers = custDS
      End Function
    End Class
    [C#]
    <% @ WebService Language = "C#" Class = "Sample" %>
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Web.Services;
    
    [WebService(Namespace="https://microsoft.com/webservices/")]
    public class Sample
    {
      public SqlConnection nwindConn = new SqlConnection("Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");
    
      [WebMethod( Description = "Returns Northwind Customers", EnableSession = false )]
      public DataSet GetCustomers()
      {
        SqlDataAdapter custDA = new SqlDataAdapter("SELECT CustomerID, CompanyName FROM Customers", nwindConn);
    
        DataSet custDS = new DataSet();
        custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
        custDA.Fill(custDS, "Customers");
    
        return custDS;
      }
    
      [WebMethod( Description = "Updates Northwind Customers", EnableSession = false )]
      public DataSet UpdateCustomers(DataSet custDS)
      {
        SqlDataAdapter custDA = new SqlDataAdapter();
    
        custDA.InsertCommand = new SqlCommand("INSERT INTO Customers (CustomerID, CompanyName) " +
                                              "Values(@CustomerID, @CompanyName)", nwindConn);
        custDA.InsertCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
        custDA.InsertCommand.Parameters.Add("@CompanyName", SqlDbType.NChar, 15, "CompanyName");
    
        custDA.UpdateCommand = new SqlCommand("UPDATE Customers Set CustomerID = @CustomerID, " +
                                              "CompanyName = @CompanyName WHERE CustomerID = @OldCustomerID", nwindConn);
        custDA.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
        custDA.UpdateCommand.Parameters.Add("@CompanyName", SqlDbType.NChar, 15, "CompanyName");
        SqlParameter myParm = custDA.UpdateCommand.Parameters.Add("@OldCustomerID", SqlDbType.NChar, 5, "CustomerID");
        myParm.SourceVersion = DataRowVersion.Original;
    
        custDA.DeleteCommand = new SqlCommand("DELETE FROM Customers WHERE CustomerID = @CustomerID", nwindConn);
        myParm = custDA.DeleteCommand.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
        myParm.SourceVersion = DataRowVersion.Original;
    
        custDA.Update(custDS, "Customers");
    
        return custDS;
      }
    }
    

    In uno scenario tipico il metodo UpdateCustomers verrebbe scritto in modo da rilevare eventuali violazioni alla concorrenza ottimistica. Per semplicità, questa opzione non è stata inclusa nell'esempio. Per ulteriori informazioni sulla concorrenza ottimistica, vedere Concorrenza ottimistica.

  2. Creare un proxy del servizio Web XML.

    Un proxy SOAP verrà richiesto dai client del servizio Web XML per l'utilizzo dei metodi esposti. Per creare un proxy, è possibile utilizzare lo Strumento Linguaggio descrittivo del servizio Web (Wsdl.exe). Se ad esempio il servizio Web XML viene esposto nell'URL http://myserver/data/DataSetSample.asmx, per creare un proxy di Visual Basic .NET con spazio dei nomi WebData.DSSample e memorizzarlo nel file sample.vb, è necessario eseguire un comando simile al seguente.

    wsdl /l:VB /out:sample.vb http://myserver/data/DataSetSample.asmx /n:WebData.DSSample
    

    Per creare un proxy C# nel file sample.cs, eseguire il comando seguente.

    wsdl /:CS /out:sample.cs http://myserver/data/DataSetSample.asmx /n:WebData.DSSample
    

    È quindi possibile compilare il proxy come libreria e importarlo nel client del servizio Web XML. Per compilare il codice del proxy di Visual Basic .NET memorizzato nel file sample.vb come sample.dll, eseguire il comando seguente.

    vbc /t:library /out:sample.dll sample.vb /r:System.dll /r:System.Web.Services.dll /r:System.Data.dll /r:System.Xml.dll
    

    Per compilare il codice del proxy C# memorizzato nel file sample.cs come sample.dll, eseguire il comando seguente.

    csc /t:library /out:sample.dll sample.cs /r:System.dll /r:System.Web.Services.dll /r:System.Data.dll /r:System.Xml.dll
    
  3. Creare un client del servizio Web XML.

    Una volta creato il proxy del servizio Web XML, è possibile importarlo nel codice del client e utilizzare i metodi del servizio Web XML. Il codice di esempio seguente consente di importare la libreria del proxy, chiamare GetCustomers per ottenere un elenco di clienti, aggiungere un nuovo cliente e infine restituire un DataSet contenente gli aggiornamenti a UpdateCustomers. Si noti che nell'esempio il DataSet restituito DataSet.GetChanges viene passato a UpdateCustomers, poiché è necessario passare a UpdateCustomers solo le righe modificate. UpdateCustomers restituisce il DataSet risolto, su cui è possibile eseguire il Merge nel DataSet esistente, in modo da incorporare le modifiche risolte ed eventuali informazioni relative agli errori provenienti dall'aggiornamento.

    Imports System
    Imports System.Data
    Imports WebData.DSSample
    
    Public Class Client
    
      Public Shared Sub Main()
        Dim mySamp As Sample = New Sample()  ' Proxy object.
    
        Dim myDS As DataSet = mySamp.GetCustomers()
    
        Dim myTable As DataTable = myDS.Tables("Customers")
    
        Dim newRow As DataRow = myTable.NewRow()
        newRow("CustomerID") = "ABCDE"
        newRow("CompanyName") = "New Company Name"
        myTable.Rows.Add(newRow)
    
        Dim updDS As DataSet = mySamp.UpdateCustomers(myDS.GetChanges())
    
        myDS.Merge(updDS)
        myDS.AcceptChanges()
      End Sub
    End Class
    [C#]
    using System;
    using System.Data;
    using WebData.DSSample;
    
    public class Client
    {
      public static void Main()
      {
        Sample mySamp = new Sample();  // Proxy object.
    
        DataSet myDS = mySamp.GetCustomers();
    
        DataTable myTable = myDS.Tables["Customers"];
    
        DataRow newRow = myTable.NewRow();
        newRow["CustomerID"] = "ABCDE";
        newRow["CompanyName"] = "New Company Name";
        myTable.Rows.Add(newRow);
    
        DataSet updDS = new DataSet();
    
        updDS = mySamp.UpdateCustomers(myDS.GetChanges());
    
        myDS.Merge(updDS);
        myDS.AcceptChanges();
      }
    }
    

    Per compilare l'esempio, è necessario fornire la libreria del proxy creata (sample.dll), e le librerie .NET correlate. Per compilare la versione di Visual Basic .NET dell'esempio, memorizzata nel file client.vb, eseguire il comando seguente.

    vbc client.vb /r:sample.dll /r:System.dll /r:System.Data.dll /r:System.Xml.dll /r:System.Web.Services.dll
    

    Per compilare la versione C# dell'esempio, memorizzata nel file client.cs, eseguire il comando seguente.

    csc client.cs /r:sample.dll /r:System.dll /r:System.Data.dll /r:System.Xml.dll /r:System.Web.Services.dll
    

Vedere anche

Scenari ADO.NET di esempio | Accesso ai dati tramite ADO.NET | Utilizzo di provider di dati .NET Framework per accedere ai dati | Creazione e utilizzo di DataSet | Creazione e utilizzo di DataTable | Compilazione di un DataSet da un DataAdapter | Aggiornamento del database tramite DataAdapter e DataSet | Utilizzo di parametri con un DataAdapter