Il codice che segue implementa un generico web service (WS) che può essere usato anche come data source per InfoPath sia la versione client che quella Form Server per SharePoint 2007 (WSS3 - MOSS).
I metodi implementati di esempio sono due:
  • GetNewGuid ritorna un Guid
  • SelectTable che ritorna un DataSet tramite il richiamo di una store procedure passata come parametro del metodo

I file necessari per realizzare il WS sono 3 e precisamente:
  • file InfoPathUtility.asmx che espone il WS sul web
  • file InfoPathUtility.cs il codeice del WS (con i metodi GetNewGuid e SelectTable)
  • file web.cofig
questo è tutto quello che serve per realizzare un WS, che andrà poi deployato su un web server (IIS).

Per realizzare il WS un nuovo progetto di tipo web service in Visual Studio 2005 e inserire i seguenti file:

File: InfoPathUtility.asmx
XML
<%@ WebService Language="C#" CodeBehind="~/App_Code/InfoPathUtility.cs" Class="InfoPathUtility" %>

File: InfoPathUtility.cs (nella cartella App_Code)
C#
using System;
using System.Configuration;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;

[WebService(Namespace = "http://www.sgart.it/webservices"
    , Description = "Web services for InfoPath")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class InfoPathUtility : System.Web.Services.WebService
{
    #region GET

    /// <summary>
    /// Return a Guid
    /// </summary>
    /// <returns>Guid</returns>
    [WebMethod(Description = "Get a new Guid")]
    public Guid GetNewGuid()
    {
        return Guid.NewGuid();
    }
    #endregion

    #region SELECT

    /// <summary>
    /// Return a dataset by a store procedure
    /// </summary>
    /// <param name="spName">store procedure name</param>
    /// <returns>DataSet</returns>
    [WebMethod(Description = "Return a dataset by a store procedure")]
    public DataSet SelectTable(string spName)
    {
        DataSet ds = new DataSet("SelectTable");
        using (SqlConnection cnn = new SqlConnection(this.SqlConnectionString))
        {
            using (SqlCommand cmd = cnn.CreateCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = spName;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    try
                    {
                        da.Fill(ds);
                    }
                    catch (Exception ex)
                    {
                        //Utility.WriteToLogError(ex, "SelectTable:" + spName);
                    }
                }
            }
        }
        return ds;
    }
    #endregion

    #region Utility
    /// <summary>
    /// get connection string in web.config
    /// </summary>
    /// <returns>connection string</returns>
    private string SqlConnectionString
    {
        get { return ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString; }
    }
    #endregion
}

File: web.config
XML
<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <clear/>
    <add name="sqlConnection" 
         connectionString="Data Source=localhost; Initial Catalog=AdventureWorks; User Id=useraw; Password=password;"  />
  </connectionStrings>
  <system.web>
    <compilation debug="true" />
    <authentication mode="Windows" />
    <customErrors mode="Off" />
  </system.web>
</configuration>
Compila ed eseguire il codice.
In mancanza di visual studio è anche possibile creare il sito con Internet Information Server (IIS), impostarlo per lavorare con il FrameWork .NET 2.0 o superiore e creare i file con un editor di testo (ad esempio notepad).

Per testare se funziona, crea la seguente store procedure nel database di esempio AdventureWorks fornito dalla Microsoft.
SQL
-- example store procedure
CREATE PROCEDURE SpSelectCountryRegion
AS
BEGIN
	SET NOCOUNT ON;

	SELECT [CountryRegionCode], [Name]
	FROM [Person].[CountryRegion]
	ORDER BY [Name]
END
Ricordati di creare un utente che abbia accesso al DB e configurare correttamente la connection string del web.config

Vai sul browser e:
  • richiama il web service all'indirizzo: http://<server>:<porta>/<virtual directory>/InfoPathUtility.asmx
  • clicca sul metodo SelectTable
  • inserisci nel parametro spName la stringa SpSelectCountryRegion (il nome della store procedure)
  • premi il pulsante Invoke
se tutto funziona vedrai un xml come il seguente
XML
<?xml version="1.0" encoding="utf-8" ?>
 <DataSet xmlns="http://www.sgart.it/webservices">
  <xs:schema id="SelectTable" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
     <xs:element name="SelectTable" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
       <xs:complexType>
         <xs:choice minOccurs="0" maxOccurs="unbounded">
           <xs:element name="Table">
             <xs:complexType>
               <xs:sequence>
                <xs:element name="CountryRegionCode" type="xs:string" minOccurs="0" />
                <xs:element name="Name" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
   <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
     <SelectTable xmlns="">
       <Table diffgr:id="Table1" msdata:rowOrder="0">
        <CountryRegionCode>AF</CountryRegionCode>
        <Name>Afghanistan</Name>
      </Table>
       <Table diffgr:id="Table2" msdata:rowOrder="1">
        <CountryRegionCode>AL</CountryRegionCode>
        <Name>Albania</Name>
      </Table>
       
       ...
       
      <Table diffgr:id="Table238" msdata:rowOrder="237">
        <CountryRegionCode>ZW</CountryRegionCode>
        <Name>Zimbabwe</Name>
      </Table>
    </SelectTable>
  </diffgr:diffgram>
</DataSet>

Vedi anche InfoPath: Il primo form
Potrebbe interessarti anche: