Technical Helpweb

Dialogic® PowerMedia™ Extended Media Server (PowerMedia XMS) - more articles

XMS 2.2 RESTful demo for C# Part 1

Introduction

  

This article is the first in a two part series which contains a simple demonstration of how to control a Dialogic® PowerMedia™ XMS 2.2 server using the RESTful API and a simple C# library.  This first article describes how to automatically generate a simple API from the XML schema definition that is provided with PowerMedia XMS and how to send and process HTTP and web service requests and responses.

The second article contains a sample library and working sample application that implements a call flow using the RESTful API and the techniques described in this first article.

Details

  

As per the RESTful API user interface guide (http://www.dialogic.com/webhelp/XMS/2.2/XMS_RESTfulAPIUser.pdf) page 12:

"PowerMedia XMS uses an XML schema definition (also referred to herein as "XSD"). The XSD formally describes the structure, content, and semantics of the XML payload for the PowerMedia XMS RESTful API call and media commands.

An XSD may be used to generate client-side code, allowing contents of XML documents to be treated as objects. The generated code usually enforces type-checking, thus supporting client-side validation of the XML payload before it is sent to the PowerMedia XMS."

Microsoft Visual Studio contains the "xsd.exe" tool for exactly this purpose. This can be run from the "Visual Studio Command Prompt". As of the PowerMedia XMS 2.2 release, the XSD is contained in the "xmsrest.xsd" file which is located on the PowerMedia XMS server in the /etc/xms directory. Note that the XSD will change periodically as features are added so it is worth regenerating the C# API when there is a new release or service update.

The "xsd.exe" tool is run as follows:

>xsd xmsrest.xsd /classes
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'xmsrest.cs'.

This will generate the file "xmsrest.cs" which contains the C# code.

From here, three additional functions are required to [1] convert from the generated API to XML, [2] convert from XML to the generated API and [3] to send the request via HTTP.

[1] Convert from the generated API to XML

      public static String RESTapiToXML(object api, Type type)
      {
         XmlSerializer serializer     = new XmlSerializer(type);
         StringBuilder requestContent = new StringBuilder();

         try
         {
            using (StringWriter writer = new StringWriter(requestContent))
            {
               XmlTextWriter xmlwriter = new XmlTextWriter(writer);
               xmlwriter.Formatting = Formatting.Indented;
               serializer.Serialize(xmlwriter, api);
            }
         }
         catch (Exception ex)
         {
            return String.Empty;
         }
 
         return requestContent.ToString();
      }

[2] Convert from XML to the generated API

      public static object XMLToRESTapi(String xml, Type type)
    {
         XmlSerializer serializer = new XmlSerializer(type);

         using (StringReader reader = new StringReader(xml))
         {
            return serializer.Deserialize(reader);
         }
      }

[3] Send a request via HTTP

      public static bool SendHttpRequest(out String responseString, String uri, String method, MCantale.XMS.RESTapi.web_service request)
      {
         String requestString = RestHelpers.RESTapiToXML(request, typeof(MCantale.XMS.RESTapi.web_service));
         return SendHttpRequest(out responseString, uri, method, requestString, "application/xml");
      }
...
      public static bool SendHttpRequest(out String responseString, String uri, String method = "GET", String requestContent = "", String contentType = "application/xml")
      {
         responseString = String.Empty;
         HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(uri);
         request.Accept          = null;
         request.ContentType     = null;
         request.Expect          = null;
         request.KeepAlive       = true;
         request.Method          = method;
         request.ProtocolVersion = HttpVersion.Version11;

         try
         {
            if (!String.IsNullOrWhiteSpace(requestContent))
            {
               request.ContentType   = contentType;
               request.ContentLength = requestContent.Length;

               using (StreamWriter stream = new StreamWriter(request.GetRequestStream()))
               {
                  stream.Write(requestContent);
                  stream.Close();
               }
            }

            LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug2,
                                              "XMLHelper::SendHttpRequest : Sent {0} {1}", method, uri);

            if (!String.IsNullOrWhiteSpace(requestContent))
            {
               LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug2,
                                                 "XMLHelper::SendHttpRequest : Sent web service request :\n{0}", requestContent);
            }

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
               using (StreamReader stream = new StreamReader(response.GetResponseStream()))
               {
                  String result = stream.ReadToEnd();
                  responseString = result;

                  /// Parse the response...
                  ///
                  LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug2, 
                                                    "XMLHelper::SendHttpRequest : Received {0:D} {1}",
                                                    response.StatusCode, response.StatusDescription);
               }
            }
         }
         catch (WebException ex)
         {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
               HttpWebResponse response = ex.Response as HttpWebResponse;

               if (response != null)
               {
                  LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Warning,
                                                    "XMLHelper::SendHttpRequest : Received HTTP failure response {0} {1}",
                                                    (int)response.StatusCode, response.StatusDescription);
               }
            }
            else
            {
               LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Warning,
                                                 "XMLHelper::SendHttpRequest : {0}\n{1}",
                                                 ex.Message.ToString(), ex.StackTrace.ToString());
            }

            return false;
         }
         catch (Exception ex)
         {
            LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Except,
                                              "XMLHelper::SendHttpRequest : {0}\n{1}",
                                              ex.Message.ToString(), ex.StackTrace.ToString());

            return false;
         }

         return true;
      }

Putting the above together, a web service request would be sent with a command to a PowerMedia XMS server to, for example, answer an incoming call:

      public bool AnswerCall(string CallURI)
      {
         RESTapi.web_service ws = new RESTapi.web_service()
         {
            Item = new RESTapi.call()
            {
               answer                    = RESTapi.boolean_type.yes,
               answerSpecified           = true,
               async_completion          = RESTapi.boolean_type.yes,
               async_completionSpecified = true,
               media                     = RESTapi.media_type.audiovideo,
               mediaSpecified            = true, 
            }
         };
 
         String responseString = String.Empty;
 
         if (RestHelpers.SendHttpRequest(out responseString, CallURI, "PUT", ws))
         {
            LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, "Call::AnswerCall : AnswerCall OK");
            LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Debug1, responseString);
         }
         else
         {
            LoggingSingleton.Instance.Message(LogType.Library, LogLevel.Error, "Call::AnswerCall : AnswerCall failed!");
            Hangup(ResourceID);
            return false;
         } 
         return true; 
      }

The following article, XMS RESTful demo for C# Part 2 describes the full library and sample application.


Product List:

Dialogic® PowerMedia™ XMS 2.2

Related Documentation

XMS RESTful demo for C# Part 2


See also:
XMS 2.2 RESTful demo for C# Part 2


Feedback

Please rate the usefulness of this page:  
0 - not useful at all
1 - potentially useful
2 - quite useful
3 - very useful
4 - exactly the information I needed     

Please enter a comment about this page:

First published: 12-Dec-2014
Open access: Product rule: open; Page rule: Auto