Thursday, February 26, 2015

Making external webservice call in C# rule

In a C# rule, you can also make external web service call. Before doing this first we have to make some configuration settings (like security and adding reference). If the security configuration is left as default you probably are going to get "System.Security.SecurityException: Request for the permission of type 'System.Net.WebPermission'" error.
Security configuration for making external web service call.

SV Server Side:
Add the following line into the file: C:\Program Files\HP\HP Service Virtualization Server\Server\bin\HP.SV.StandaloneServer.exe.config and restart SV Server.

    <!-- secure mode C# scripting -->
    <add key="Simulator.Scripting.Sandbox" value="false"/>

If this line exists with true value, change it to false.

SV Designer Side:
AFAIK Nothing needed for the designer.

By using following code template you can make external web service call from your C# rule.
Since this code template uses System.Xml namespace you have to follow these steps before running following code.

using System;
using System.Net;
using System.IO;
using System.Xml;
using HP.SV.DotNetRuleApi;
using HP.SV.CSharp; 

namespace HP.SV{
 public class CSharpRule{
  public static void Execute(HpsvRootObject hpsv){
    string host = "<<<YourExternalHost>>>";
    string xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-9\"?><XML>Your xml request goes here</XML>";
    string url = "http://"+host+"/EndpointURL";

    System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(url);
    byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(xml);
    request.Method = "POST";
    request.ContentType = "text/xml;charset=utf-8";
    request.ContentLength = requestBytes.Length;
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(requestBytes, 0, requestBytes.Length);
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    XmlDocument xmlDoc = new XmlDocument();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
    nsmgr.AddNamespace("ns", "You can add namespaces if exists");
    string out_version = "1.0";
    string out_returnCode = xmlDoc.SelectSingleNode("/XPATH/For/ReturnCode", nsmgr).InnerText;
    string out_detailCode = xmlDoc.SelectSingleNode("/XPATH/For/DetailCode", nsmgr).InnerText;
    string out_tid = xmlDoc.SelectSingleNode("/XPATH/For/TID", nsmgr).InnerText;

No comments: