SwitchVox .NET API

Talk with others about developing applications for Switchvox

Moderators: bmdhacks, dpodolsky, tristand, jwitt, joshuas

SwitchVox .NET API

Postby kaebig » Thu Jun 14, 2012 4:43 pm

I thought someone might appreciate this. I'm already using it with 3 production solutions.

Code: Select all
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Xml;

namespace KES.SwitchVox
{
    /*            +=    SwitchVox .NET API    =+
     *                   www.keslabs.com
     *                   
     *      Created in 45 minutes... you've been warned.
     *
     *      // GENERIC API USAGE ---
     
            NameValueCollection params = new NameValueCollection();
            myCol.Add("name", "value");
            myCol.Add("name", "value");
            myCol.Add("name", "value");
     
            SwitchVoxAPI api = new SwitchVoxAPI("myhostnameOrIP", "myUser", "myPass");
            if (api.Request("one.of.the.methods", params))
                Console.Write(api.Response);
     
            // SPECIFIC API USAGE ---
     
            private int? getUserAccountId(string ext)
            {
                NameValueCollection parameters = new NameValueCollection();
                SwitchVoxAPI api = new SwitchVoxAPI("192.168.0.1", ext, "myPassword");
                if (api.Request("switchvox.users.getMyInfo", parameters))
                {
                    int accountId;
                    XDocument document = XDocument.Parse(api.Response, LoadOptions.None);
                    if (int.TryParse(document.Descendants("extension").First().Attribute("account_id").Value, out accountId))
                    {
                        return accountId;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
     
     */

    public class SwitchVoxAPI
    {
        public string Username;
        public string Password;
        public string Hostname;

        public Uri Uri
        {
            get
            {
                return new Uri(string.Format("https://{0}/xml", Hostname));
            }
        }
        public string Response
        {
            private set;
            get;
        }

        public SwitchVoxAPI(string hostname, string username, string password)
        {
            Hostname = hostname;
            Username = username;
            Password = password;
        }

        public Boolean Request(string method, NameValueCollection arguments)
        {
           
            if (method == null || method == string.Empty)
                throw new NullReferenceException();

            if (arguments == null)
                throw new NullReferenceException();

            try
            {
                XmlDocument doc = new XmlDocument();
                XmlElement request = doc.CreateElement("request");
                request.SetAttribute("method", method);

                XmlElement parameters = doc.CreateElement("parameters");
                foreach (String name in arguments.AllKeys)
                {
                    XmlElement arg = doc.CreateElement(name);
                    arg.InnerText = arguments[name];

                    parameters.AppendChild(arg);
                }

                request.AppendChild(parameters);
                doc.AppendChild(request);

                return Send(doc.OuterXml);
            }
            catch
            {
                return false;
            }         
        }

        public Boolean Send(string xmlPackage)
        {
            try
            {
                if (Hostname == null || Hostname == string.Empty)
                    throw new NullReferenceException();

                if (Username == null || Username == string.Empty)
                    throw new NullReferenceException();

                if (Password == null || Password == string.Empty)
                    throw new NullReferenceException();

                Response = string.Empty;

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
                CookieContainer cookies = new CookieContainer();

                // allows for validation of SSL conversations -- Only for trusted hosts!
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                CredentialCache creds = new CredentialCache();
                creds.Add(Uri, "Digest", new NetworkCredential(Username, Password));

                request.Credentials = creds;
                request.Method = WebRequestMethods.Http.Post;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.3; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.PreAuthenticate = true;
                request.CookieContainer = cookies;
                request.ContentLength = xmlPackage.Length;
                request.ContentType = "application/xml";

                StreamWriter writer = new StreamWriter(request.GetRequestStream());
                writer.Write(xmlPackage);
                writer.Close();
               
                HttpWebResponse oResponse = (HttpWebResponse)request.GetResponse();
                if (oResponse.StatusCode != HttpStatusCode.OK)
                {
                    return false;
                }

                StreamReader reader = new StreamReader(oResponse.GetResponseStream());
                Response = reader.ReadToEnd();

                // Check for result or error
                // response > result
                // response > err


                oResponse.Close();

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.ToString());
                return false;
            }
        }
    }
}

-------------------------------------------------------
[ ! K E S L A B S ]
www.keslabs.com
kaebig
Newsterisk
 
Posts: 15
Joined: Thu Jun 14, 2012 4:18 pm

Re: SwitchVox .NET API

Postby dpodolsky » Tue Jun 19, 2012 9:28 am

Thanks for the code snippet. We have had previous posts where people ask for .NET help, so I am sure this will be valuable.
dpodolsky
Oldsterisk
 
Posts: 325
Joined: Thu Apr 23, 2009 2:35 pm

Re: SwitchVox .NET API

Postby kschmutz » Thu Jun 21, 2012 9:36 am

Hi,

This API is great however there is one part I am stuck on. How does one embed a NameValueCollection within a NameValueCollection. I haven't worked too much with this type of object and none of the .NET documentation shows that how this is possible.

I would be trying to create a data structure needed with an API like "switchvox.extensions.search":
<extension_types>
<extension_type>sip</extension_type>
<extension_type>zap</extension_type>
</extension_types>
<min_extension>
1000
</min_extension>

The extension_types array is what I am having trouble with. I have tried things like:

Code: Select all
        Dim SwitchvoxParams As New NameValueCollection()
        SwitchvoxParams.Add("extension_types", "<extension_types><extension_type>sip</extension_type><extension_type>zap</extension_type></extension_types>")
        SwitchvoxParams.Add("min_extension", "1000")
        SwitchvoxParams.Add("max_extension", "9999")

and

Code: Select all
        Dim Extension_Types As New NameValueCollection()
        Extension_Types.Add("extension_type", "sip")
        Extension_Types.Add("extension_type", "zap")


        Dim SwitchvoxParams As New NameValueCollection()
        SwitchvoxParams.Add(Extension_Types)
        SwitchvoxParams.Add("min_extension", "1000")
        SwitchvoxParams.Add("max_extension", "9999")


but to no avail. For now I will continue using a straight XML doc and serialize it directly to the HTTP writer but I wouldn't mind getting your API working.

Thanks!
kschmutz
Newsterisk
 
Posts: 3
Joined: Mon Jun 11, 2012 4:22 pm

Re: SwitchVox .NET API

Postby kaebig » Mon Jun 25, 2012 9:37 am

Honestly, I haven't used any of the API calls that required that...

I'll revise the code and post changes that should work easily as the existing one might not handle that gracefully.
-------------------------------------------------------
[ ! K E S L A B S ]
www.keslabs.com
kaebig
Newsterisk
 
Posts: 15
Joined: Thu Jun 14, 2012 4:18 pm

Re: SwitchVox .NET API

Postby kaebig » Mon Jun 25, 2012 10:38 am

Here's a new version that handles things much better overall. Instead of using a base collection, there's a custom one that can be nested inside itself. As well, the parameters are generated using recursion, so it doesn't matter how many levels deep the arguments are or if there are multiple array arguments.

Please look over the examples as this issue has changed the usage slightly.

Code: Select all
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Xml;

namespace KES.SwitchVox
{
    /*            +=    SwitchVox .NET API    =+
     *                   www.keslabs.com
     *                   
     *      Created in 45 minutes... you've been warned.
     *
     *      // -----------------------------------
     *      // GENERIC API USAGE
     
            SwitchVoxArguments params = new SwitchVoxArguments();
            params.Add("name", "value");
            params.Add("name", "value");
            params.Add("name", "value");
     
            SwitchVoxAPI api = new SwitchVoxAPI("myhostnameOrIP", "myUser", "myPass");
            if (api.Request("one.of.the.methods", params))
                Console.Write(api.Response);
     
            // -----------------------------------
            // SPECIFIC API USAGE
            //
            // Get User Account Id by Extension #
            //
            private int? getUserAccountId(string ext)
            {
                SwitchVoxArguments parameters = new SwitchVoxArguments();
                SwitchVoxAPI api = new SwitchVoxAPI("192.168.0.1", ext, "myPassword");
                if (api.Request("switchvox.users.getMyInfo", parameters))
                {
                    int accountId;
                    XDocument document = XDocument.Parse(api.Response, LoadOptions.None);
                    if (int.TryParse(document.Descendants("extension").First().Attribute("account_id").Value, out accountId))
                    {
                        return accountId;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
     
            //
            // Array Type Arguments Example
            //
            int minExtension = 101;
            int maxExtension = 901;

            SwitchVoxArguments types = new SwitchVoxArguments();
            types.Add("extension_type", "ivr");
            types.Add("extension_type", "call_queue");

            SwitchVoxArguments parameters = new SwitchVoxArguments();
            parameters.Add("min_extension", minExtension.ToString());
            parameters.Add("max_extension", maxExtension.ToString());
            parameters.Add("extension_types", types);
     
            SwitchVoxAPI api = new SwitchVoxAPI("192.168.0.1", "myUser", "myPassword");
            if (api.Request("switchvox.extensions.search", parameters))
            {
                XDocument document = XDocument.Parse(api.Response, LoadOptions.None);
                Console.WriteLine("Extension Search Succeeded... Parse Me!");
            }
            else
            {
                Console.WriteLine("Extension Search Failed...");
            }
     */

    public class SwitchVoxAPI
    {
        public string Username;
        public string Password;
        public string Hostname;

        public Uri Uri
        {
            get
            {
                return new Uri(string.Format("https://{0}/xml", Hostname));
            }
        }
        public string Response
        {
            private set;
            get;
        }

        public SwitchVoxAPI(string hostname, string username, string password)
        {
            Hostname = hostname;
            Username = username;
            Password = password;
        }

        public Boolean Request(string method, SwitchVoxArguments arguments)
        {

            if (method == null || method == string.Empty)
                throw new NullReferenceException();

            if (arguments == null)
                throw new NullReferenceException();

            try
            {
                XmlDocument doc = new XmlDocument();
                XmlElement request = doc.CreateElement("request");
                request.SetAttribute("method", method);

                XmlElement parameters = doc.CreateElement("parameters");
                ParseArguments(arguments, doc, parameters);

                request.AppendChild(parameters);
                doc.AppendChild(request);

                return Send(doc.OuterXml);
            }
            catch
            {
                return false;
            }
        }

        private void ParseArguments(SwitchVoxArguments arguments, XmlDocument doc, XmlElement parent)
        {
            foreach (var e in arguments)
            {
                XmlElement arg = doc.CreateElement(e.Key);
                if (e.IsCollection)
                {
                    ParseArguments((SwitchVoxArguments)e.Value, doc, arg);
                }
                else
                {
                    arg.InnerText = e.Value.ToString();
                }
                parent.AppendChild(arg);
            }
        }

        public Boolean Send(string xmlPackage)
        {
            try
            {
                if (Hostname == null || Hostname == string.Empty)
                    throw new NullReferenceException();

                if (Username == null || Username == string.Empty)
                    throw new NullReferenceException();

                if (Password == null || Password == string.Empty)
                    throw new NullReferenceException();

                Response = string.Empty;

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Uri);
                CookieContainer cookies = new CookieContainer();

                // allows for validation of SSL conversations -- Only for trusted hosts!
                ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

                CredentialCache creds = new CredentialCache();
                creds.Add(Uri, "Digest", new NetworkCredential(Username, Password));

                request.Credentials = creds;
                request.Method = WebRequestMethods.Http.Post;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6.3; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.PreAuthenticate = true;
                request.CookieContainer = cookies;
                request.ContentLength = xmlPackage.Length;
                request.ContentType = "application/xml";

                StreamWriter writer = new StreamWriter(request.GetRequestStream());
                writer.Write(xmlPackage);
                writer.Close();
               
                HttpWebResponse oResponse = (HttpWebResponse)request.GetResponse();
                if (oResponse.StatusCode != HttpStatusCode.OK)
                {
                    return false;
                }

                StreamReader reader = new StreamReader(oResponse.GetResponseStream());
                Response = reader.ReadToEnd();

                // Check for result or error
                // response > result
                // response > err

                oResponse.Close();

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.ToString());
                return false;
            }
        }
    }

    public class SwitchVoxKeyValue
    {
        public string Key;
        public object Value;

        public SwitchVoxKeyValue(string key, object value)
        {
            Key = key;
            Value = value;
        }

        public bool IsCollection
        {
            get
            {
                return (Value.GetType() == typeof(SwitchVoxArguments));
            }
        }
    }

    public class SwitchVoxArguments : List<SwitchVoxKeyValue>
    {
        public void Add(string key, object value)
        {
            Add(new SwitchVoxKeyValue(key, value));
        }
    }
}
-------------------------------------------------------
[ ! K E S L A B S ]
www.keslabs.com
kaebig
Newsterisk
 
Posts: 15
Joined: Thu Jun 14, 2012 4:18 pm


Return to Switchvox Developers

Who is online

Users browsing this forum: No registered users and 2 guests