<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>A Developer&#039;s Blog &#187; Web Services</title>
	<atom:link href="http://blog.hoegaerden.be/tag/web-services/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.hoegaerden.be</link>
	<description>SQL Server, BI, .NET, IT and anything else I have been playing with.</description>
	<lastBuildDate>Wed, 01 Feb 2012 16:15:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Calling A Web Service From SQL Server 2005</title>
		<link>http://blog.hoegaerden.be/2008/11/11/calling-a-web-service-from-sql-server-2005/</link>
		<comments>http://blog.hoegaerden.be/2008/11/11/calling-a-web-service-from-sql-server-2005/#comments</comments>
		<pubDate>Tue, 11 Nov 2008 13:09:09 +0000</pubDate>
		<dc:creator>Valentino Vranken</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[SQL Server 2005]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Web Services]]></category>

		<guid isPermaLink="false">http://blog.hoegaerden.be/2008/11/11/calling-a-web-service-from-sql-server-2005/</guid>
		<description><![CDATA[This may not be your daily routine but in today&#8217;s world of interoperability and loosely-coupled systems you sometimes don&#8217;t have another option.  Imagine a situation where a scheduled task (using SQL Agent) needs to get data from a web service or trigger some code through a web service. In the following explanation I will show [...]]]></description>
			<content:encoded><![CDATA[<p>This may not be your daily routine but in today&#8217;s world of interoperability and loosely-coupled systems you sometimes don&#8217;t have another option.  Imagine a situation where a scheduled task (using SQL Agent) needs to get data from a web service or trigger some code through a web service.</p>
<p>In the following explanation I will show how to use SQL CLR (Common Language Runtime) Integration to get a weather report from a web service, or WS in short.</p>
<p>For this I am using a free web service: <a title="http://www.webservicex.net/globalweather.asmx" href="http://www.webservicex.net/globalweather.asmx">http://www.webservicex.net/globalweather.asmx</a>.  Or not&#8230;  Seems that the weather web service gods don&#8217;t like me, this WS has (temporarily?) stopped working after I completed the sample and part of this article.  I haven&#8217;t found a replacement that can deliver global weather so we&#8217;ll have to do with US-only, delivered through this web service: <a title="http://ws.cdyne.com/WeatherWS/Weather.asmx" href="http://ws.cdyne.com/WeatherWS/Weather.asmx">http://ws.cdyne.com/WeatherWS/Weather.asmx</a>.</p>
<p>Now is a good time to warn you about the usage of external services.  If you need your code to work all the time, make sure that you can trust the web services that you use.  Otherwise you may just end up as I did, with a dead function&#8230;</p>
<p>Basic knowledge on building .NET assemblies and using SQL Server is required.</p>
<h2>The assembly</h2>
<p>Let&#8217;s start with creating our .NET assembly with the custom stored procedure.  Using Visual Studio 2005, create a new Database Project:</p>
<p><a href="http://blog.hoegaerden.be/wp-content/uploads/database-project.png"><img style="border-width: 0px;" src="http://blog.hoegaerden.be/wp-content/uploads/database-project-thumb.png" border="0" alt="Database_project" width="468" height="339" /></a></p>
<p>Add a Web Reference to your project pointing to the .asmx mentioned earlier.</p>
<p><a href="http://blog.hoegaerden.be/wp-content/uploads/add-web-reference.png"><img style="border-width: 0px;" src="http://blog.hoegaerden.be/wp-content/uploads/add-web-reference-thumb.png" border="0" alt="Add_Web_Reference" width="462" height="277" /></a></p>
<p>Add a Stored Procedure to your project:</p>
<p><a href="http://blog.hoegaerden.be/wp-content/uploads/weathersp.png"><img style="border-width: 0px;" src="http://blog.hoegaerden.be/wp-content/uploads/weathersp-thumb.png" border="0" alt="WeatherSP" width="463" height="286" /></a></p>
<p>This class is going to contain the code to call the web service and return a result to the client.</p>
<p>Following code fetches the weather report for a given US Zip code.</p>
<pre class="code"><span style="color: blue;">using </span>System;
<span style="color: blue;">using </span>System.Data;
<span style="color: blue;">using </span>System.Data.SqlClient;
<span style="color: blue;">using </span>System.Data.SqlTypes;
<span style="color: blue;">using </span>Microsoft.SqlServer.Server;
<span style="color: blue;">using </span>MyStoredProcedures.com.cdyne.ws;

<span style="color: blue;">public partial class </span><span style="color: #2b91af;">StoredProcedures
</span>{
    [Microsoft.SqlServer.Server.<span style="color: #2b91af;">SqlProcedure</span>]
    <span style="color: blue;">public static void </span>WeatherSP(<span style="color: blue;">string </span>zipCode)
    {
        <span style="color: #2b91af;">Weather </span>myWeatherWS = <span style="color: blue;">new </span><span style="color: #2b91af;">Weather</span>();
        <span style="color: #2b91af;">WeatherReturn </span>weatherResult = myWeatherWS.GetCityWeatherByZIP(zipCode);

        <span style="color: #2b91af;">SqlMetaData</span>[] recordMetaData = <span style="color: blue;">new </span><span style="color: #2b91af;">SqlMetaData</span>[2];
        <span style="color: green;">// layout of the records that we'll return
        </span>recordMetaData[0] = <span style="color: blue;">new </span><span style="color: #2b91af;">SqlMetaData</span>(<span style="color: #a31515;">"Description"</span>, <span style="color: #2b91af;">SqlDbType</span>.Char, 100);
        recordMetaData[1] = <span style="color: blue;">new </span><span style="color: #2b91af;">SqlMetaData</span>(<span style="color: #a31515;">"Value"</span>, <span style="color: #2b91af;">SqlDbType</span>.Char, 1000);

        <span style="color: green;">// build a record based on the metadata
        </span><span style="color: #2b91af;">SqlDataRecord </span>record = <span style="color: blue;">new </span><span style="color: #2b91af;">SqlDataRecord</span>(recordMetaData);

        <span style="color: green;">// let's start sending result into the active pipe
        </span><span style="color: #2b91af;">SqlContext</span>.Pipe.SendResultsStart(record);

        <span style="color: green;">// one way of adding a new record to the pipe
        </span>record.SetString(0, <span style="color: #a31515;">"ResponseText"</span>);
        record.SetString(1, weatherResult.ResponseText);
        <span style="color: #2b91af;">SqlContext</span>.Pipe.SendResultsRow(record);

        <span style="color: green;">// another way of adding a new record, using an array initializer
        </span>record.SetValues(<span style="color: blue;">new </span><span style="color: #2b91af;">String</span>[2] { <span style="color: #a31515;">"City"</span>, weatherResult.City });
        <span style="color: #2b91af;">SqlContext</span>.Pipe.SendResultsRow(record);

        record.SetValues(<span style="color: blue;">new </span><span style="color: #2b91af;">String</span>[2] { <span style="color: #a31515;">"State"</span>, weatherResult.State });
        <span style="color: #2b91af;">SqlContext</span>.Pipe.SendResultsRow(record);

        record.SetValues(<span style="color: blue;">new </span><span style="color: #2b91af;">String</span>[2] { <span style="color: #a31515;">"Description"</span>, weatherResult.Description });
        <span style="color: #2b91af;">SqlContext</span>.Pipe.SendResultsRow(record);

        record.SetValues(<span style="color: blue;">new </span><span style="color: #2b91af;">String</span>[2] { <span style="color: #a31515;">"Temperature"</span>, weatherResult.Temperature });
        <span style="color: #2b91af;">SqlContext</span>.Pipe.SendResultsRow(record);

        record.SetValues(<span style="color: blue;">new </span><span style="color: #2b91af;">String</span>[2] { <span style="color: #a31515;">"Timestamp"</span>, <span style="color: #2b91af;">DateTime</span>.Now.ToString() });
        <span style="color: #2b91af;">SqlContext</span>.Pipe.SendResultsRow(record);

        <span style="color: green;">// finished sending result
        </span><span style="color: #2b91af;">SqlContext</span>.Pipe.SendResultsEnd();
    }

};</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>In the code above you can see that the stored procedure has a parameter called zipCode.  This incoming value is passed to the web service call.</p>
<p>Our result consists of several records, each record containing 2 string fields.</p>
<p>The web service that we&#8217;ve used returns an object of type WeatherResult.  This makes it easy for us to read the result.  The WS that I used initially didn&#8217;t return an object but an XML string.  In that case you can use the XmlDocument.LoadXml from the System.Xml namespace to get an XmlDocument.  Then use the SelectSingleNode method to get to the details, for instance myXmlDoc.SelectSingleNode(&#8220;//Temperature&#8221;).InnerText would return the value for the Temperature node.</p>
<p>And this is what it looks like when our stored procedure gets called from the Management Studio:</p>
<p><a href="http://blog.hoegaerden.be/wp-content/uploads/weathersp-ssms-result.png"><img style="border-width: 0px;" src="http://blog.hoegaerden.be/wp-content/uploads/weathersp-ssms-result-thumb.png" border="0" alt="WeatherSP_SSMS_result" width="234" height="237" /></a></p>
<h3>Building the assembly</h3>
<p>Before we build our assembly there are a couple of project settings that need modification.</p>
<p>Here we ask Visual Studio to also generate an assembly containing the XML Serializers.  This is needed because our code is calling a web service and code running in SQL Server is not allowed to use the serializers that are normally generated dynamically.</p>
<p><a href="http://blog.hoegaerden.be/wp-content/uploads/project-properties-build-tab.png"><img style="border-width: 0px;" src="http://blog.hoegaerden.be/wp-content/uploads/project-properties-build-tab-thumb.png" border="0" alt="Project_properties_Build_tab" width="489" height="434" /></a></p>
<p>Another setting that we need to change is the Permission Level.  This is also required because our code is calling a web service, hence external.</p>
<p><a href="http://blog.hoegaerden.be/wp-content/uploads/project-properties-database-tab.png"><img style="border-width: 0px;" src="http://blog.hoegaerden.be/wp-content/uploads/project-properties-database-tab-thumb.png" border="0" alt="Project_properties_Database_tab" width="490" height="218" /></a></p>
<h2>Server and Database Settings</h2>
<p>Now that we&#8217;ve covered the actual development of the stored procedure we would like to install it on our database server.  This requires us to modify some settings on the server and database.  If you are not the DBA of the server and you are in the luxurious situation that such a person exists, please verify with him/her if you are allowed to modify these settings.</p>
<h3>Enabling CLR Integration</h3>
<p>By default SQL Server does not allow CLR Integration.  This setting can be easily modified with the following script:</p>
<pre class="code"><span style="color: blue;">exec </span><span style="color: maroon;">sp_configure </span><span style="color: red;">'clr enabled'</span><span style="color: gray;">, </span><span style="color: red;">'1'</span><span style="color: gray;">;
</span><span style="color: blue;">reconfigure</span><span style="color: gray;">;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<div></div>
<h3>Our database we trust</h3>
<p>As our stored procedure needs external access permission, we need to create the assembly with external access (as shown in next chapter).  To get this to work we need to convince SQL Server that our database can be trusted: (I&#8217;ve used AdventureWorks in this article but this can be any existing database)</p>
<pre class="code"><span style="color: blue;">ALTER DATABASE </span>AdventureWorks <span style="color: blue;">SET TRUSTWORTHY ON</span><span style="color: gray;">;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<div></div>
<h3>Owner needs external access</h3>
<div>To be allowed to create an assembly with external access, the database owner needs to have EXTERNAL ACCESS ASSEMBLY permission.  If that&#8217;s not the case you will see the following error when trying to create the assembly:</div>
<div></div>
<blockquote>
<div><span style="color: #ff0000;">Msg 10327, Level 14, State 1, Line 1 CREATE ASSEMBLY for assembly &#8216;MyStoredProcedures&#8217; failed because assembly &#8216;MyStoredProcedures&#8217; is not authorized for PERMISSION_SET = EXTERNAL_ACCESS. The assembly is authorized when either of the following is true: the database owner (DBO) has EXTERNAL ACCESS ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with EXTERNAL ACCESS ASSEMBLY permission. If you have restored or attached this database, make sure the database owner is mapped to the correct login on this server. If not, use sp_changedbowner to fix the problem.</span></div>
</blockquote>
<div></div>
<div>So to avoid this error make sure that your DB owner has sufficient permissions.  The following script makes sa the owner of the active database:</div>
<div></div>
<div>
<pre class="code"><span style="color: blue;">EXEC </span><span style="color: maroon;">sp_changedbowner </span><span style="color: red;">'sa'</span><span style="color: gray;">, </span>false<span style="color: gray;">;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
</div>
<h2>Installing the Stored Procedure</h2>
<p>We&#8217;re almost there, all that remains to be done is to tell SQL Server where our stored procedure can be found and that it actually exists.  Assemblies, just like stored procedures, live in a database (AdventureWorks in our case).  In Management Studio you can see your assemblies in the Object explorer under the Programmability node of your database:</p>
<p><a href="http://blog.hoegaerden.be/wp-content/uploads/ssms-assemblies.png"><img style="border-width: 0px;" src="http://blog.hoegaerden.be/wp-content/uploads/ssms-assemblies-thumb.png" border="0" alt="SSMS_assemblies" width="208" height="203" /></a></p>
<h3>Adding the assemblies</h3>
<p>Following script adds the two assemblies that we&#8217;ve created earlier to your database.  An assembly is given a name, like MyStoredProcedures.  Here you can finally see the EXTERNAL_ACCESS permission that we need for our web service call.</p>
<pre class="code"><span style="color: blue;">CREATE ASSEMBLY </span>MyStoredProcedures
<span style="color: blue;">FROM </span><span style="color: red;">'D:\vvr\techtests\dotnet\MyStoredProcedures\MyStoredProcedures\bin\Debug\MyStoredProcedures.dll'
</span><span style="color: blue;">WITH PERMISSION_SET </span><span style="color: gray;">= </span><span style="color: blue;">EXTERNAL_ACCESS</span><span style="color: gray;">;
</span><span style="color: blue;">GO

CREATE ASSEMBLY </span>MyXmlSerializers
<span style="color: blue;">FROM
</span><span style="color: red;">'D:\vvr\techtests\dotnet\MyStoredProcedures\MyStoredProcedures\bin\Debug\MyStoredProcedures.XmlSerializers.dll'
</span><span style="color: blue;">WITH PERMISSION_SET </span><span style="color: gray;">= </span><span style="color: blue;">SAFE</span><span style="color: gray;">;
</span><span style="color: blue;">GO</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<div></div>
<h3>Adding our stored procedure</h3>
<p>Last step is to create our stored procedure.  We tell SQL Server that it can be found in the MyStoredProcedures assembly, in the class StoredProcedures and that the method is called WeatherSP.  We have one parameter of type string in our method definition, which translates to nvarchar in the stored procedure.  A length of 10 is more than enough for our ZIP code.</p>
<pre class="code"><span style="color: blue;">CREATE PROCEDURE </span>WeatherSP
    @zipCode <span style="color: blue;">nvarchar</span><span style="color: gray;">(</span>10<span style="color: gray;">)
</span><span style="color: blue;">AS EXTERNAL </span>NAME MyStoredProcedures<span style="color: gray;">.</span>StoredProcedures<span style="color: gray;">.</span>WeatherSP<span style="color: gray;">;
</span><span style="color: blue;">GO</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<div></div>
<h2>Configuring the Stored Procedure</h2>
<p>In some (most?) cases we don&#8217;t want to hard-code connection details. In this case it means the path to the web service. Imagine a situation where you are consuming a web service that you&#8217;ve developed yourself, or another team in your company. And the web service is running in several environments: development, acceptance, production. Of course we don&#8217;t want to change our code and recompile each time we need to deploy to a different environment. So we need a way to configure the web service location.</p>
<p>The answer here lies in the sqlservr.exe.config file. This is a file like any other .config file, with a possible content like this:</p>
<pre class="code"><span style="color: blue;">&lt;?</span><span style="color: #a31515;">xml </span><span style="color: red;">version</span><span style="color: blue;">=</span>"<span style="color: blue;">1.0</span>" <span style="color: red;">encoding</span><span style="color: blue;">=</span>"<span style="color: blue;">utf-8</span>" <span style="color: blue;">?&gt;
&lt;</span><span style="color: #a31515;">configuration</span><span style="color: blue;">&gt;
  &lt;</span><span style="color: #a31515;">appSettings</span><span style="color: blue;">&gt;
    &lt;</span><span style="color: #a31515;">add </span><span style="color: red;">key</span><span style="color: blue;">=</span>"<span style="color: blue;">MyWebService</span>" <span style="color: red;">value</span><span style="color: blue;">=</span>"<span style="color: blue;">http://MyWebServiceServer:MyWSPort/PathTo/MyWebService.asmx</span>" <span style="color: blue;">/&gt;
  &lt;/</span><span style="color: #a31515;">appSettings</span><span style="color: blue;">&gt;
&lt;/</span><span style="color: #a31515;">configuration</span><span style="color: blue;">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<div></div>
<p>This file needs to be put in the same folder as your sqlservr.exe that&#8217;s running your SQL Server instance.  By default this path is C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\.  When you restart your SQL Server instance while this file is in that folder, SQL Server will pick up any configuration settings from that file.  These can then be accessed from your custom stored procedure in this way:</p>
<pre class="code"><span style="color: green;">/* The following call is made in order to workaround an "anomaly"
   * where reading an appSettings key value results in the error:
   * "The value of the property 'key' cannot be parsed.
   * The error is: Request failed. (sqlservr.exe.Config line X)"
   *
   * So, just a call to another section alleviates the issue.
   * This error only occurs on the first call to an assembly after
   * it's been loaded by the sqlservr.exe
   */
</span><span style="color: blue;">int </span>firstcall = ConfigurationManager.ConnectionStrings.Count;

MyWebService myWS = <span style="color: blue;">new </span>MyWebService();
myWS.Url = ConfigurationManager.AppSettings[<span style="color: #a31515;">"MyWebService"</span>];
myWS.MyWebMethod();</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<div></div>
<p>That’s it, that’s all it takes.  It’s not that difficult, once you know it, right? <img src='http://blog.hoegaerden.be/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Have fun!</p>
<p>Valentino.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.hoegaerden.be%2F2008%2F11%2F11%2Fcalling-a-web-service-from-sql-server-2005%2F&amp;title=Calling%20A%20Web%20Service%20From%20SQL%20Server%202005" id="wpa2a_2"><img src="http://blog.hoegaerden.be/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.hoegaerden.be/2008/11/11/calling-a-web-service-from-sql-server-2005/feed/</wfw:commentRss>
		<slash:comments>38</slash:comments>
		</item>
	</channel>
</rss>

