This example shows how to get the structure of a template in JSON format using C#. It calls the Docmosis REST API to return a response describing the fields, images and sections of the template.
The sample code includes the instructions to get started. You will need a Free Trial to install and run Tornado.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace Docmosis
{
///
/// This sample code shows how to get the structure of the "WelcomeTemplate.docx" template in JSON format
/// via the local Tornado server (localhost:8080).
///
/// If you wish to test via a web proxy server, see the PROXY_* settings below to enable it.
///
///
/// Copyright Docmosis 2019
///
class CSGetTemplateStructureExample
{
private static string DWS_GETSTRUCTURE_URL = "http://localhost:8080/api/getTemplateStructure";
// Set your access key here. The access key is only required if configured in Tornado.
private const string ACCESS_KEY = "";
// the name of the template (stored in Tornado) to use
private const string TEMPLATE = "WelcomeTemplate.docx";
// Proxy settings if needed to reach the internet
private const string PROXY_HOST = "";
private const string PROXY_PORT = "";
private const string PROXY_USER = "";
private const string PROXY_PASSWD = "";
static void Main(string[] args)
{
HttpWebResponse response;
try
{
response = sendRequest();
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
String responseString = getJsonResponse(response.GetResponseStream());
Console.Out.WriteLine(JsonHelper.FormatJson(responseString));
}
else
{
processError(response);
}
}
finally
{
response.Close();
}
}
catch (WebException e)
{
Console.WriteLine("ERROR:" + e.Message);
using (WebResponse webResponse = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)webResponse;
processError(httpResponse);
}
}
catch (Exception e)
{
Console.Error.WriteLine("Unable to connect to Docmosis: " + e.Message);
Console.Error.WriteLine(e.StackTrace);
Console.Error.WriteLine("If you have a proxy, configure proxy settings at the top of this example.");
Console.ReadKey();
System.Environment.Exit(2);
}
Console.Out.WriteLine("Press any key");
Console.ReadKey();
}
///
/// Sends the request to the server and returns the response.
///
///
/// the response returned by the server
///
static HttpWebResponse sendRequest()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(DWS_GETSTRUCTURE_URL);
if (PROXY_HOST.Length != 0)
{
WebProxy proxy = new WebProxy(PROXY_HOST + ":" + PROXY_PORT, true);
if (PROXY_USER.Length != 0)
{
proxy.Credentials = new NetworkCredential(PROXY_USER, PROXY_PASSWD);
}
Console.WriteLine(proxy.Address);
request.Proxy = proxy;
}
string getStructureRequest = buildRequest();
Console.WriteLine("Sending request:" + getStructureRequest);
byte[] data = new UTF8Encoding().GetBytes(getStructureRequest);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
return (HttpWebResponse)request.GetResponse();
}
///
/// Build the request in urlencoded format.
///
private static string buildRequest()
{
StringBuilder sb = new StringBuilder();
// Build the request
sb.Append("accessKey=").Append(ACCESS_KEY).Append("&");
sb.Append("templateName=").Append(TEMPLATE);
return sb.ToString();
}
///
/// Extract the returned json from the response
///
///the Stream containing the content
private static String getJsonResponse(Stream content)
{
StreamReader reader = new StreamReader(content, Encoding.UTF8);
String responseString = reader.ReadToEnd();
//Remove succeeded parameter and templateStructure key from response
responseString = responseString.Substring(1, responseString.Length - 3);
int idx = responseString.IndexOf('{')+1;
responseString = responseString.Substring(idx, responseString.Length-idx);
return "{" + responseString + "}";
}
///
/// Something went wrong in the call to the service, tell the user about it
///
///The response causing errors
private static void processError(HttpWebResponse response)
{
Console.Error.WriteLine("Our call failed: status = {0}", response.StatusCode);
Console.Error.WriteLine("message:" + response.StatusDescription);
StreamReader errorReader = new StreamReader(response.GetResponseStream());
String msg;
while ((msg = errorReader.ReadLine()) != null)
{
Console.Error.WriteLine(msg);
}
}
}
///
/// Helper Class to format the json response for output to user.
///
class JsonHelper
{
private const string INDENT_STRING = " ";
public static string FormatJson(string str)
{
var indent = 0;
var quoted = false;
var sb = new StringBuilder();
for (var i = 0; i < str.Length; i++)
{
var ch = str[i];
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING));
}
break;
case '}':
case ']':
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, --indent).ForEach(item => sb.Append(INDENT_STRING));
}
sb.Append(ch);
break;
case '"':
sb.Append(ch);
bool escaped = false;
var index = i;
while (index > 0 && str[--index] == '\\')
escaped = !escaped;
if (!escaped)
quoted = !quoted;
break;
case ',':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, indent).ForEach(item => sb.Append(INDENT_STRING));
}
break;
case ':':
sb.Append(ch);
if (!quoted)
sb.Append(" ");
break;
default:
sb.Append(ch);
break;
}
}
return sb.ToString();
}
}
static class Extensions
{
public static void ForEach<T>(this IEnumerable<T> ie, Action<T> action)
{
foreach (var i in ie)
{
action(i);
}
}
}
}
