Using the Channel API with C#

The following example shows how to use C# to call the Channel API. This example imports a project. Please post a comment if you have feedback or questions.

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Iguana.Api
{
  class Program
  {
    static void Main(string[] args)
    {
      string projectZipFilePath = @"C:\path\to\exported\project.zip";
      string translatorGuid =  "translator_guid";
      new ChannelAdapter().ImportProject(projectZipFilePath, translatorGuid);
    }
  }

  public class ChannelAdapter
  {
    private readonly string _iguanaServerUrl = "http://localhost:6543/";

    // Import a translator project into the sample channel.
    public void ImportProject(string projectZipFilePath, string projectGuid)
    {
      var projectStream = ConvertFileToBase64(projectZipFilePath);

      // There are better utilites to do this in a proper web app (not a console app)
      string uriEncodedProjectStream = Uri.EscapeDataString(projectStream);

      var channelUri = new Uri(string.Format("{0}import_project", _iguanaServerUrl));
      var parameters = string.Format("project={0}&guid={1}", uriEncodedProjectStream, projectGuid);

      PerformPostAction(channelUri, Encoding.UTF8.GetBytes(parameters));
    }

    private string PerformPostAction(Uri serverUri, byte[] requestMessageBytes, string contentType = "application/x-www-form-urlencoded")
    {
      if (serverUri == null) throw new ArgumentNullException("serverUri", "The URI cannot be null.");
      var iguanaServerRequest = WebRequest.Create(serverUri);
      var returnValue = string.Empty;
      try
      {
        iguanaServerRequest.Credentials = new NetworkCredential("admin", "password");
        iguanaServerRequest.Method = WebRequestMethods.Http.Post;
        iguanaServerRequest.ContentType = contentType;
        iguanaServerRequest.ContentLength = requestMessageBytes.Length;

        using (var httpRequest = iguanaServerRequest.GetRequestStream())
        {
          httpRequest.Write(requestMessageBytes, 0, requestMessageBytes.Length);
          httpRequest.Close();
        }

        using (var httpWebResponse = iguanaServerRequest.GetResponse() as HttpWebResponse)
        {
          if (httpWebResponse == null)
            throw new Exception(string.Format("No response was found at this address: {0}", iguanaServerRequest.RequestUri));

          Console.WriteLine("Received response from [{0}]\t::\t[{1}]", iguanaServerRequest.RequestUri.AbsolutePath,
            httpWebResponse.StatusDescription);

          using (var responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
          {
            returnValue = responseStream.ReadToEnd();

            // if (PrintWebResponse) Console.WriteLine(returnValue); // proper logging can be added here...
            // Just doing this here because we are in a console app and don't have the PrintWebResponse object
            if (true) Console.WriteLine(returnValue);
          }
        }
      }
      catch (WebException webException)
      {
        Console.WriteLine("Received response from [{0}]\t::\t[{1}]", iguanaServerRequest.RequestUri.AbsolutePath,
            webException.Status);
        Console.ReadKey();
      }

      return returnValue;
    }

    // Get the translator project zip file contents as base64 encoded stream...
    private static string ConvertFileToBase64(string zipFilePath)
    {
      if (!File.Exists(zipFilePath))
        throw new Exception(string.Format("A valid file path must be provided. The current value is: {0}", zipFilePath));

      byte[] binaryData = File.ReadAllBytes(zipFilePath);
      string outstr = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);
      return outstr;
    }
  }
}

Leave A Comment?

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.