Skip to content

Instantly share code, notes, and snippets.

@Ergin008
Last active July 9, 2016 02:19
Show Gist options
  • Select an option

  • Save Ergin008/4165799 to your computer and use it in GitHub Desktop.

Select an option

Save Ergin008/4165799 to your computer and use it in GitHub Desktop.
Get Document List and Download Envelope Documents
// DocuSign API Walkthrough 06 in C# - Download Envelope Document(s)
//
// To run this sample:
// 1) Create a new .NET project.
// 2) Add 4 assembly references to the project: System, System.Net, System.XML, and System.XML.Linq
// 3) Update the email, password, integrator key, and envelopeId in the code
// 4) Compile and Run
//
// NOTE 1: The DocuSign REST API accepts both JSON and XML formatted http requests. These C# API walkthroughs
// demonstrate the use of XML format, whereas the other walkthroughs show examples in JSON format.
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Collections.Generic;
namespace DocuSignAPIWalkthrough06
{
public class DownloadEnvelopeDocs
{
public static void Main ()
{
//---------------------------------------------------------------------------------------------------
// ENTER VALUES FOR THE FOLLOWING 4 VARIABLES:
//---------------------------------------------------------------------------------------------------
string username = "***"; // your account email
string password = "***"; // your account password
string integratorKey = "***"; // your account Integrator Key (found on Preferences -> API page)
string envelopeId = "***"; // valid envelopeId from an envelope in your account
//---------------------------------------------------------------------------------------------------
// additional variable declarations
string baseURL = ""; // - we will retrieve this through the Login API call
try {
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest( url, "GET", null, username, password, integratorKey);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//--- display results
Console.WriteLine("\nAPI Call Result: \n\n" + prettyPrintXml(response));
//============================================================================
// STEP 2 - Get Envelope Document(s) List and Info
//============================================================================
// append "/envelopes/{envelopeId}/documents" to to baseUrl and use for next endpoint
url = baseURL + "/envelopes/" + envelopeId + "/documents";
// set request url, method, body, and headers
request = initializeRequest( url, "GET", null, username, password, integratorKey);
// read the http response
response = getResponseBody(request);
// store each document name and uri locally, so that we can subsequently download each one
Dictionary<string, string> docsList = new Dictionary<string, string>();
string uri, name;
using (XmlReader reader = XmlReader.Create(new StringReader(response))) {
while (reader.Read()) {
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "envelopeDocument"))
{
XmlReader reader2 = reader.ReadSubtree();
uri = ""; name = "";
while (reader2.Read()) {
if((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "name"))
{
name = reader2.ReadString();
}
if((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "uri"))
{
uri = reader2.ReadString();
}
}// end while
docsList.Add(name, uri);
}
}
}
//--- display results
Console.WriteLine("\nAPI Call Result: \n\n" + prettyPrintXml(response));
//============================================================================
// STEP 3 - Download the Document(s)
//============================================================================
foreach( KeyValuePair<string, string> kvp in docsList )
{
// append document uri to baseUrl and use to download each document(s)
url = baseURL + kvp.Value;
// set request url, method, body, and headers
request = initializeRequest( url, "GET", null, username, password, integratorKey);
request.Accept = "application/pdf"; // documents are converted to PDF in the DocuSign cloud
// read the response and store into a local file:
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
using (MemoryStream ms = new MemoryStream())
using (FileStream outfile = new FileStream(kvp.Key, FileMode.Create)) {
webResponse.GetResponseStream().CopyTo(ms);
if (ms.Length > int.MaxValue) {
throw new NotSupportedException("Cannot write a file larger than 2GB.");
}
outfile.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
}
Console.WriteLine("\nDone downloading document(s), check local directory.");
}
catch (WebException e) {
using (WebResponse response = e.Response) {
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
Console.WriteLine(prettyPrintXml(text));
}
}
}
} // end main()
//***********************************************************************************************
// --- HELPER FUNCTIONS ---
//***********************************************************************************************
public static HttpWebRequest initializeRequest(string url, string method, string body, string email, string password, string intKey)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
request.Method = method;
addRequestHeaders( request, email, password, intKey );
if( body != null )
addRequestBody(request, body);
return request;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void addRequestHeaders(HttpWebRequest request, string email, string password, string intKey)
{
// authentication header can be in JSON or XML format. XML used for this walkthrough:
string authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + email + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + intKey + "</IntegratorKey>" +
"</DocuSignCredentials>";
request.Headers.Add ("X-DocuSign-Authentication", authenticateStr);
request.Accept = "application/xml";
request.ContentType = "application/xml";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void addRequestBody(HttpWebRequest request, string requestBody)
{
// create byte array out of request body and add to the request object
byte[] body = System.Text.Encoding.UTF8.GetBytes (requestBody);
Stream dataStream = request.GetRequestStream ();
dataStream.Write (body, 0, requestBody.Length);
dataStream.Close ();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public static string getResponseBody(HttpWebRequest request)
{
// read the response stream into a local string
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse ();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public static string parseDataFromResponse(string response, string searchToken)
{
// look for "searchToken" in the response body and parse its value
using (XmlReader reader = XmlReader.Create(new StringReader(response))) {
while (reader.Read()) {
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == searchToken))
return reader.ReadString();
}
}
return null;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public static string prettyPrintXml(string xml)
{
// print nicely formatted xml
try {
XDocument doc = XDocument.Parse(xml);
return doc.ToString();
}
catch (Exception) {
return xml;
}
}
} // end class
} // end namespace
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment