TaCode Tuesday: How to Use Zang in Open Source .NET

Posted by Pedram Mohammadi on February 28, 2017

Mono is a free, open source development platform based on the .NET Framework that enables the creation of cross-platform applications, improving overall programmer productivity. Its development is led by Xamarin, a Microsoft subsidiary which aims to not only run Microsoft.Net applications on different platforms, but also provides tools to Linux developers. Mono can run on Android, PlayStation 3, Wii, Xbox, OS X, Solaris, BSD, and most Linux distributions.

 TaCode Tuesday: Developer API Cheat Sheet for Zang Using C# / Mono |  http://blog.zang.io/

 

Why Use Mono?

Mono is composed of several components such as C# Compiler, Mono Runtime, and Class Library that are all compatible with .NET Framework, Unix, and other open source libraries like Gtk+, Zip files, LDAP, OpenGL, Cairo, and POSIX.

 Simplified Mono Architecture | http://blog.zang.io/

Source: Mono Project

It is also multi-platform, multi-language, binary compatible, API compatible, and has a comprehensive technology coverage. Because of this flexibility, millions of developers are using it.  The popularity of Mono is primarily driven by the success of .NET which gives its users the necessary foundation in using the C# language.

Thousands of books and websites with sample codes are made readily available, making its usage very easy. Many runtime features are also incorporated in Mono, like automatic memory management, reflection, generics, and threading. This allows developers to focus more on writing their applications rather than the infrastructure code. Mono’s built-in classes and common language runtime (CLR) also further contribute to developer productivity.

Why Should You Use Mono on Zang?

Using Mono to build your applications consuming Zang’s REST API and InboundXML is perfect due to its asynchronous programming feature. As defined by E. Vorgel, async programming is:

A means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure or progress.

Async programming will make your Zang apps faster and more responsive because it allows potentially blocking activities to be managed efficiently. There are times where your access to a web resource like Zang APIs may be slow or delayed, making your entire app wait. In async process, instead of having to pause, your app will continue working on other processes that it needs to fulfill and just return to the pending process until its responsiveness returns to an optimum level.  

 

Now that you know what Mono can do for your next project, let’s go ahead and map Zang’s call and SMS APIs to C#.  But before we start, we suggest that you have some basic knowledge of:

  • C# 
  • C# asynchronous programming
  • Terminal window commands
  • REST architecture

 

Let’s start coding!

 

1.0 First, download and install Mono through this link

2.0 Then, create Class Members to be included in your library

using System;

using System.Net;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Threading.Tasks;

 

2.1 Create a Namespace

// lets name our namespace to "HttpZangApiConsoleApplication

namespace HttpZangAPIConsoleApplication

{

/*

Mapped all the properties of an API into a class in such a way that it has its own getter/setter

*/

 

/*

Setup your Zang Server Authentication properties

*/

   public class Auth

   {   //A const object is always static.

public const string AccountSid =@"{AccountSid}";

public const string  AuthToken = @"{AuthToken}";

}

/*

Optional setup for Zang's Url properties

*/

   public class Url

   {   //A const object is always static.

public const string CallApi =@"{call-api-domain}";

public const string SMSSpi '

public const string UsageAPi;

public const string;

...

}

3.0 Map Zang API Properties

The following classes show how to map the properties of basic Zang API's to make a call, send SMS, and view an account.

 

3.1 Make a Call Class

public class MakeACall

{

public string From;

public string Call;

public string To;

}

 

3.2 Send a SMS Class

public class SendSMS

   {

public string To;

public string From;

public string Body;

   }

 

3.3 View Account Class

public class ViewAccount

{

public int sid;

public string friendly_name;

public string status;

public float account_balance;

public DateTime date_created

public DateTime date_updated

public string uri

public string max_outbound_limit;

public string type;

    ...

            }

 

3.4 View Account Usage Class

public class ViewAccountUsage

{

public int sid;

public string product;

public int product_id;

public string month;

public string year;

public int quantity;

public float average_cost;

public float total_cost;

public string uri;

}

 

public class Conference

{

public int sid;

public string friendly_name;

...

}

 

3.5 Program Class

The following shows the async enabled C# code:

 

3.5.1 Make a Call Async Method

/*Implement an Asycnhronous call for the Zang "MAKE A CALL" Api using http POST method and in JSON format */

static async Task<Uri> MakeACallAsync(MakeACall call)

{

HttpResponseMessage response = await client.PostAsJsonAsync("{AccountSid}/Calls.json", call);

response.EnsureSuccessStatusCode();

// return URI of the created resource.

return response.Headers.Location;

}

 

3.5.2 View Account Async Method

/*Implement an Asycnhronous call for the Zang "VIEW ACCOUNT" Api using http POST method and in JSON format */

static async Task<Uri> ViewAccountAsync()

{

//curl -X GET 'https://api.zang.io/v2/Accounts/{AccountSid}.json' -u '{AccountSid}:{AuthToken}'

HttpResponseMessage response = await client.GetAsync(url.PathAndQuery + "Accounts/{AccountSid}.json");

if (response.IsSuccessStatusCode)

{

ViewAccountItems = await response.Content.ReadAsAsync<ViewAccount>();

}

   return ViewAccountItems;

}

 

3.5.3 View Account Usage Async Method

/*Implement an Asycnhronous call for the Zang "VIEW ACCOUNT USAGE" Api using http POST method and in JSON format */

static async Task<Uri> ViewAccountAsyncUsage()

{

//curl -X GET 'https://api.zang.io/v2/Accounts/{AccountSid}.json' -u '{AccountSid}:{AuthToken}'

HttpResponseMessage response = await client.GetAsync(url.PathAndQuery + "Accounts/{AccountSid}.json");

if (response.IsSuccessStatusCode)

{

ViewAccountItems = await response.Content.ReadAsAsync<ViewAccount>();

}

   return ViewAccountItems;

}

 

3.5.4 View Conference Async Method

/* Example implementation of Zang's "VIEW CONFERENCE" API using Async */

static async Task<Uri> ViewConference(int ConferenceSid)

{

HttpResponseMessage response = await client.GetAsync(url.PathAndQuery + "/Accounts/:AccountSid/Conferences/:ConferenceSid.json");

if (response.IsSuccessStatusCode)

{

ConferenceItems = await response.Content.ReadAsAsync<Conference>();

}

   return ConferenceItems;

}

 

3.5.5 Run all Async methods

/* Run our Async call via C# "Main()" program entry point */

static void Main()

{

RunAsync().Wait();

}

 

/*

Implementation of method RunSyc() example usage of the methods from class program

*/

       static async Task RunAsync()

       {

           //Set the url base address

           client.BaseAddress = new Uri("https://api.zang.io/v2/Accounts/");

           client.DefaultRequestHeaders.Accept.Clear();

           //use JSON as Header Data Format

           client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

try

           {

//invoke Make a Call method

 

MakeACall call = new MakeACall{From ="XXX-XXX-XXXX",To="XXX-XXX-XXXX",Url="http://zang.io/ivr/welcome/call" };

var call_response = await MakeACallAsync(call);

 

//invoke Send SMS method

SendSMS sms = new SendSMS{

To="XXX-XXX-XXXX",

From="XXX-XXX-XXXX",

Body="This is an SMS sent from Zang"

}

//parse JSON response

var sms_response = await SendSMSAsync(sms);

 

//curl -X GET 'https://api.zang.io/v2/Accounts/{AccountSid}.json' -u '{AccountSid}:{AuthToken}'

//Invoke the method View Account Items

var account_response = ViewAccountAsync();

//Invoke the method View Account Usage

var usage_response = ViewAccountUsage({UsageSid});

 

//https://api.zang.io/v2/Accounts/:AccountSid/Conferences/:ConferenceSid.json

//View Conference

var conference_response = ViewConference({ConferenceSid});

}

           catch (Exception e)

           { //Handle errors

               Console.WriteLine(e.Message);

           }

 

           Console.ReadLine();

       }

 

   }

}

 

4.0 Data Format

All of Zang's APIs gives out three types of data format once invoked: XML, JSON and CSV. Although most of the time, it gives out a JSON response.

 

4.1 Make a Call XML Response

The following is an example of HTTP Response in XML format invoking Make a Call

<?xml version="1.0" ?>

 <Response>

   <Call>

     <DateUpdated>Wed, 13 Jul 2016 15:11:37 -0000</DateUpdated>

     <ParentCallSid></ParentCallSid>

     <Duration>0</Duration>

     <From>+15555555555</From>

     <To>+19999999999</To>

     <CallerIdBlocked>false</CallerIdBlocked>

     <AnsweredBy>nobody</AnsweredBy>

     <Sid>{CallSid}</Sid>

     <RecordingsCount></RecordingsCount>

     <Price>0.00</Price>

     <ApiVersion>v2</ApiVersion>

     <Status>queued</Status>

     <Direction>outbound-api</Direction>

     <StartTime>None</StartTime>

     <DateCreated>Wed, 13 Jul 2016 15:11:37 -0000</DateCreated>

     <SubresourceUris>

       <Notifications>/v2/Accounts/{AccountSid}/Calls/{CallSid}/Notifications</Notifications>

       <Recordings>/v2/Accounts/{AccountSid}/Calls/{CallSid}/Recordings</Recordings>

     </SubresourceUris>

     <ForwardedFrom></ForwardedFrom>

     <Uri>/v2/Accounts/{AccountSid}/Calls/{CallSid}</Uri>

     <AccountSid>{AccountSid}</AccountSid>

     <DurationBilled>0</DurationBilled>

     <EndTime>None</EndTime>

     <PhoneNumberSid></PhoneNumberSid>

   </Call>

 </Response>

 

4.2 Make a Call HTTP Response

The following is an example of HTTP Response in CSV format invoking Make a Call

date_updated,parent_call_sid,duration,from,to,caller_id_blocked,answered_by,sid,

recordings_count,price

,api_version,status,direction,start_time,date_created,subresource_uris,forwarded_from,uri,

account_sid,duration_billed,end_time,phone_number_sid

Wed, 13 Jul 2016 15:19:13 -0000,,,+15555555555,+19999999999,false,nobody,{CallSid},

,0.00,v2,queued,outbound-api,

,Wed, 13 Jul 2016 15:19:13 -0000,{'notifications': u'/v2/Accounts/{AccountSid}/Calls/{CallSid}/Notifications', 'recordings': u'/v2/Accounts/{AccountSid}/Calls/{CallSid}/Recordings'},,/v2/Accounts/{AccountSid}/Calls/{CallSid},{AccountSid},,,

 

4.3 Send SMS and View Account HTTP Response

The following is an example of the Send SMS and View Account HTTP Response after calling the API method in JSON format.

Send SMS

{

   "api_version": "v2",

   "sid": "{SmsSid}",

   "account_sid": "{AccountSid}",

   "date_created": "Tue, 24 Jul 2012 14:08:23 +0000",

   "date_updated": "Tue, 24 Jul 2012 14:08:24 +0000",

   "date_sent": "Tue, 24 Jul 2012 14:08:24 +0000",

   "to": "+17325551234",

   "from": "+14245551234",

   "body": "Test message sent from TelAPI!",

   "status": "sent",

   "direction": "outbound-api",

   "price": "0.070000",

   "uri": "/v2/Accounts/AC5521767e53d04deeb0a06f660cee50f9/SMS/Messages/{SmsSid}.json"

}

 

{

   "sid": "AccountSid",

   "friendly_name": "foo@bar.com",

   "status": "active",

 

   "account_balance": "25.00",



   "date_created": "Tue, 21 Aug 2012 14:27:03 +0000",

   "date_updated": "Thu, 1 Nov 2012 19:54:05 +0000",

   "uri": "/v2/Accounts/AccountSid.json",

   "max_outbound_limit" : "0.400000",

   "type": "Full",

   "time_zone": "America/New_York",

 

   "subresource_uris": {

       "available_phone_numbers": "/v2/Accounts/AccountSid/AvailablePhoneNumbers.json",

       "calls": "/v2/Accounts/AccountSid/Calls.json",

       "conferences": "/v2/Accounts/AccountSid/Conferences.json",

       "incoming_phone_numbers": "/v2/Accounts/AccountSid/IncomingPhoneNumbers.json",

       "notifications": "/v2/Accounts/AccountSid/Notifications.json",

       "recordings": "/v2/Accounts/AccountSid/Recordings.json",

       "sms_messages": "/v2/Accounts/AccountSid/SMS/Messages.json",

       "transcriptions": "/v2/Accounts/AccountSid/Transcriptions.json",

       "transactions": "/v2/Accounts/AccountSid/Transactions.json",

       "applications": "/v2/Accounts/AccountSid/Applications.json",

       "fraud": "/v2/Accounts/AccountSid/Fraud.json",

       "cnam": "/v2/Accounts/AccountSid/CNAM.json",

       "carrier": "/v2/Accounts/AccountSid/Carrier.json",

       "usages": "/v2/Accounts/AccountSid/Usages.json"

       }

}

 

That’s it!

Using Mono for Zang is a great way to build reliable and cost-efficient cross platform applications. Through Mono, asynchronous programming can be used to prevent bottlenecks at the event of a slow API or XML response.

Leveraging Mono for Zang also allows development of any web, desktop, or mobile applications without a huge upfront cost. Since Mono is open source, you can use it without the hefty license costs associated with .NET. Also, Zang SMS and Call APIs are more affordable compared to its counterparts, enabling you to create products that have a good chance of competing in the market. If you want to try Zang for free, you can sign up here.

Start building on Zang

Topics: APIs, TaCode Tuesday, cPaaS