Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

The following code is in C#. It gives an idea on how to use the WebRequest class of .Net with the API.

Use this code as a basis for your developments. However keep in mind:

  • The sample code does basic error handling only. For example you would need to intercept exceptions systematically.
  • The sample code is all synchronous. If you are calling the API on a UI thread you should switch to asynchronous approaches (while still using the WebRequest class).

 

using System;
using System.Collections.Specialized;
using System.IO;
using System.IO.Compression;
using System.Net;
using Newtonsoft.Json.Linq;
namespace UnitTestProject1
{

	/// <summary>
	/// Sample proxy class to use the API.
	/// 
	/// Please note:
	/// 
	/// - This class only implements very basic error handling.
	///   In production code, full error handling needs to be implemented.
	/// 
	/// - API calls running in a UI should be better implemented using asynchronous web calls.
	/// 
	/// </summary>
	public class ApiProxy
	{
		// The API end point
		private string mApiUrl;
		/// <summary>
 

		/// Constructor
		/// </summary>
		/// <param name="apiurl"></param>
		public ApiProxy(string apiurl)
		{
			mApiUrl = apiurl;
		}
 

		/// <summary>
		/// Connect and get token.
		/// Throws exception if anything fails.
		/// </summary>
		/// <param name="domain"></param>
		/// <param name="ui"></param>
		/// <returns></returns>
		public string Connect(string account, string login, string pwd, string domain, string ui)
		{
			// Parameters
			UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/connect", mApiUrl));
			ub.AddParameter("account", account);
			ub.AddParameter("login", login);
			ub.AddParameter("pwd", pwd);
			ub.AddParameter("domain", domain);
			ub.AddParameter("ui", ui);
			// Create request
			var request = WebRequest.Create(ub.Uri);
			request.Method = "GET";
			// Submit
			bool error;
			JObject json = GetJsonResult(request, out error);
			// If there is an error, we should handle it better than this:
			if (error) throw new Exception(json.ToString());
			// Ok let's get the session token
			return (string)json["token"];
		}



		/// <summary>
		/// Connect and get token.
		/// Throws exception if anything fails.
		/// </summary>
		/// <param name="domain"></param>
		/// <param name="ui"></param>
		/// <returns></returns>
		public void Disconnect(string token)
		{
			// Parameters
			UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/disconnect", mApiUrl));
			ub.AddParameter("token", token);
			// Create request
			var request = WebRequest.Create(ub.Uri);
			request.Method = "PUT";
			request.ContentType = "application/json";
			request.ContentLength = 0;
			using (WebResponse response = request.GetResponse())
			{
				var status = ((HttpWebResponse)response).StatusCode;
			}
		}



		/// <summary>
		/// Connect and get token.
		/// Throws exception if anything fails.
		/// </summary>
		/// <param name="domain"></param>
		/// <param name="ui"></param>
		/// <returns></returns>
		public JObject GetConfiguration(string token, int option)
		{
			// Parameters
			UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/it/configuration", mApiUrl));
			ub.AddParameter("token", token);
			ub.AddParameter("option", option.ToString());
			var request = WebRequest.Create(ub.Uri);
			request.Method = "GET";
			// Submit
			bool error;
			JObject json = GetJsonResult(request, out error);
			if (error) throw new Exception(json.ToString());
			return json;
		}



		/// <summary>
		/// Connect and get token.
		/// Throws exception if anything fails.
		/// </summary>
		/// <param name="domain"></param>
		/// <param name="ui"></param>
		/// <returns></returns>
		public int SubmitRequest(string token, string filepath, string src, string trg, int option, int foption)
		{
			// Parameters
			UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/it/requests", mApiUrl));
			ub.AddParameter("token", token);
			ub.AddParameter("filename", Path.GetFileName(filepath));
			ub.AddParameter("src", src);
			ub.AddParameter("trg", trg);
			ub.AddParameter("option", option.ToString());
			ub.AddParameter("foption", foption.ToString());
			// Create request
			var request = WebRequest.Create(ub.Uri);
			request.Method = "POST";
			request.ContentType = "stream";
			request.Timeout = 1000 * 360;	// 1 sec * 100
			// Upload file
			using (Stream requeststream = request.GetRequestStream())
			{
				using (Stream filestream = File.OpenRead(filepath))
				{
					using (DeflateStream dstream = new DeflateStream(requeststream, CompressionMode.Compress, true))
					{
						filestream.CopyTo(dstream);
					}
				}
			}
				
			// Get response
			bool error;
			JObject result = GetJsonResult(request, out error);
			if (error) throw new Exception();
			int id = (int)result["id"];
			return id;
		}



		/// <summary>
		/// Connect and get token.
		/// Throws exception if anything fails.
		/// </summary>
		/// <param name="domain"></param>
		/// <param name="ui"></param>
		/// <returns></returns>
		public string DownloadTranslation(string token, int requestId)
		{
			// Parameters
			UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/it/requests/file", mApiUrl));
			ub.AddParameter("token", token);
			ub.AddParameter("id", requestId.ToString());
			// Create request
			var request = WebRequest.Create(ub.Uri);
			request.Method = "GET";
			// Get file
			using (WebResponse response = request.GetResponse())
			{
				var status = ((HttpWebResponse)response).StatusCode;
				if (status == HttpStatusCode.BadRequest)
				{
					// If 200 or 400 we have JSON!
					using (var stream = response.GetResponseStream())
					{
						var eresult = (new StreamReader(stream)).ReadToEnd();
						JObject jerror = JObject.Parse(eresult);
						throw new Exception("Oups: " + jerror.ToString());
					}
				}
				else
				{
					string temppath = null;
					try
					{
						using (var stream = response.GetResponseStream())
						{
							using (DeflateStream dfstream = new DeflateStream(stream, CompressionMode.Decompress, true))
							{
								temppath = Path.GetTempFileName();
								using (Stream targetstream = File.OpenWrite(temppath))
								{
									dfstream.CopyTo(targetstream);
								}
							}
						}
						return temppath;
					}
					catch
					{
						if (temppath != null) File.Delete(temppath);
						throw;
					}
				}
			}
		}
 
 

		/// <summary>
		/// Gets JSON result **synchronously**.
		/// If HTTP result status is neither 200 nor 400, an exception is raised.
		/// </summary>
		/// <param name="request">The web request</param>
		/// <param name="error">
		/// False: Json is the success result. 
		/// True: Json is the API error result which contains the error message etc.
		/// </param>
		/// <returns>JSON</returns>
		private JObject GetJsonResult(WebRequest request, out bool error)
		{
			using (WebResponse response = request.GetResponse())
			{
				var status = ((HttpWebResponse)response).StatusCode;
				if (status == HttpStatusCode.BadRequest || status == HttpStatusCode.OK)
				{
					// If 200 or 400 we have JSON!
					using (var stream = response.GetResponseStream())
					{
						var eresult = (new StreamReader(stream)).ReadToEnd();
						JObject jerror = JObject.Parse(eresult);
						error = status == HttpStatusCode.BadRequest;
						return jerror;
					}
				}
				else
				{
					// A different error, we do not get JSON here
					// Might want to read the contents too for logging etc.
					throw new Exception(status.ToString());
				}
			}
		}

	}
 
 

	/// <summary>
	/// Helper class to add query parameters to an URI
	/// </summary>
	public class UriBuilderExt
	{
		private NameValueCollection collection;
		private UriBuilder builder;
		public UriBuilderExt(string uri) { builder = new UriBuilder(uri); collection = System.Web.HttpUtility.ParseQueryString(string.Empty); }
		public void AddParameter(string key, string value) { collection.Add(key, value); }
		public Uri Uri { get { builder.Query = collection.ToString(); return builder.Uri; } }
	}

}


 

 

 

 

  • No labels