forked from docusign/code-examples-csharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEg010SendBinaryDocsController.cs
351 lines (316 loc) · 14.9 KB
/
Eg010SendBinaryDocsController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using DocuSign.CodeExamples.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace DocuSign.CodeExamples.Controllers
{
[Area("eSignature")]
[Route("eg010")]
public class Eg010SendBinaryDocsController : EgController
{
public Eg010SendBinaryDocsController(DSConfiguration config, IRequestItemsService requestItemsService)
: base(config, requestItemsService)
{
ViewBag.title = "Send envelope with multipart mime";
}
public override string EgName => "eg010";
// Returns a tuple. See https://stackoverflow.com/a/36436255/64904
// ***DS.snippet.0.start
(bool statusOk, string envelopeId, string errorCode, string errorMessage) DoWork(
string signerEmail, string signerName, string ccEmail,
string ccName, string accessToken, string basePath,
string accountId)
{
// Data for this method
// signerEmail
// signerName
// ccEmail
// ccName
// accessToken
// basePath
// accountId
// Config.docDocx
// Config.docPdf
// Step 1. Make the envelope JSON request body
dynamic envelope = MakeEnvelope(signerEmail, signerName, ccEmail, ccName);
// Step 2. Gather documents and their headeres
// Read files from a local directory
// The reads could raise an exception if the file is not available!
dynamic doc1 = envelope["documents"][0];
dynamic doc2 = envelope["documents"][1];
dynamic doc3 = envelope["documents"][2];
dynamic documents = new[] {
new {
mime = "text/html",
filename = (string) doc1["name"],
documentId = (string) doc1["documentId"],
bytes = Encoding.ASCII.GetBytes(document1(signerEmail, signerName, ccEmail, ccName))
},
new {
mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
filename = (string) doc2["name"],
documentId = (string) doc2["documentId"],
bytes = System.IO.File.ReadAllBytes(Config.docDocx)
},
new {
mime = "application/pdf",
filename = (string) doc3["name"],
documentId = (string) doc3["documentId"],
bytes = System.IO.File.ReadAllBytes(Config.docPdf)
}
};
// Step 3. Create the multipart body
byte[] CRLF = Encoding.ASCII.GetBytes("\r\n");
byte[] boundary = Encoding.ASCII.GetBytes("multipartboundary_multipartboundary");
byte[] hyphens = Encoding.ASCII.GetBytes("--");
string uri = basePath
+ "/v2/accounts/" + accountId + "/envelopes";
HttpWebRequest request = WebRequest.CreateHttp(uri);
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "multipart/form-data; boundary=" + Encoding.ASCII.GetString(boundary);
request.Headers.Add("Authorization", "Bearer " + accessToken);
using (var buffer = new BinaryWriter(request.GetRequestStream(), Encoding.ASCII))
{
buffer.Write(hyphens);
buffer.Write(boundary);
buffer.Write(CRLF);
buffer.Write(Encoding.ASCII.GetBytes("Content-Type: application/json"));
buffer.Write(CRLF);
buffer.Write(Encoding.ASCII.GetBytes("Content-Disposition: form-data"));
buffer.Write(CRLF);
buffer.Write(CRLF);
var json = JsonConvert.SerializeObject(envelope, Formatting.Indented);
buffer.Write(Encoding.ASCII.GetBytes(json));
// Loop to add the documents.
// See section Multipart Form Requests on page https://developers.docusign.com/esign-rest-api/guides/requests-and-responses
foreach (var d in documents)
{
buffer.Write(CRLF);
buffer.Write(hyphens);
buffer.Write(boundary);
buffer.Write(CRLF);
buffer.Write(Encoding.ASCII.GetBytes("Content-Type:" + d.mime));
buffer.Write(CRLF);
buffer.Write(Encoding.ASCII.GetBytes("Content-Disposition: file; filename=\"" + d.filename + ";documentid=" + d.documentId));
buffer.Write(CRLF);
buffer.Write(CRLF);
buffer.Write(d.bytes);
}
// Add closing boundary
buffer.Write(CRLF);
buffer.Write(hyphens);
buffer.Write(boundary);
buffer.Write(hyphens);
buffer.Write(CRLF);
buffer.Flush();
}
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response;
ViewBag.errorMessage = ex.Message;
ViewBag.err = ex;
}
var res = "";
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
res = reader.ReadToEnd();
}
}
HttpStatusCode code = ((HttpWebResponse)response).StatusCode;
dynamic obj = JsonConvert.DeserializeObject(res);
bool statusOk = code >= HttpStatusCode.OK && code < HttpStatusCode.MultipleChoices;
string envelopeId = null;
string errorCode = null;
string errorMessage = null;
if (statusOk)
{
envelopeId = obj.envelopeId;
}
else
{
errorCode = obj.errorCode;
errorMessage = obj.message;
}
return (statusOk, envelopeId, errorCode, errorMessage);
}
private string document1(string signerEmail, string signerName, string ccEmail, string ccName)
{
// Data for this method
// signerEmail
// signerName
// ccEmail
// ccName
return " <!DOCTYPE html>\n" +
" <html>\n" +
" <head>\n" +
" <meta charset=\"UTF-8\">\n" +
" </head>\n" +
" <body style=\"font-family:sans-serif;margin-left:2em;\">\n" +
" <h1 style=\"font-family: 'Trebuchet MS', Helvetica, sans-serif;\n" +
" color: darkblue;margin-bottom: 0;\">World Wide Corp</h1>\n" +
" <h2 style=\"font-family: 'Trebuchet MS', Helvetica, sans-serif;\n" +
" margin-top: 0px;margin-bottom: 3.5em;font-size: 1em;\n" +
" color: darkblue;\">Order Processing Division</h2>\n" +
" <h4>Ordered by " + signerName + "</h4>\n" +
" <p style=\"margin-top:0em; margin-bottom:0em;\">Email: " + signerEmail + "</p>\n" +
" <p style=\"margin-top:0em; margin-bottom:0em;\">Copy to: " + ccName + ", " + ccEmail + "</p>\n" +
" <p style=\"margin-top:3em;\">\n" +
" Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie. Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée. Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice. Donut jujubes oat cake jelly-o. Dessert bear claw chocolate cake gummies lollipop sugar plum ice cream gummies cheesecake.\n" +
" </p>\n" +
" <!-- Note the anchor tag for the signature field is in white. -->\n" +
" <h3 style=\"margin-top:3em;\">Agreed: <span style=\"color:white;\">**signature_1**/</span></h3>\n" +
" </body>\n" +
" </html>";
}
private Dictionary<string, dynamic> MakeEnvelope(string signerEmail, string signerName, string ccEmail, string ccName)
{
// Data for this method
// signerEmail
// signerName
// ccEmail
// ccName
// document 1 (html) has tag **signature_1**
// document 2 (docx) has tag /sn1/
// document 3 (pdf) has tag /sn1/
//
// The envelope has two recipients.
// recipient 1 - signer
// recipient 2 - cc
// The envelope will be sent first to the signer.
// After it is signed, a copy is sent to the cc person.
// create the envelope definition
// add the documents
Dictionary<string, dynamic> doc1 = new Dictionary<string, dynamic>()
{
{ "name", "Order acknowledgement"}, // can be different from actual file name
{ "fileExtension", "html"}, // Source data format. Signed docs are always pdf.
{ "documentId", "1"} // a label used to reference the doc
};
Dictionary<string, dynamic> doc2 = new Dictionary<string, dynamic>()
{
{ "name", "Battle Plan"}, // can be different from actual file name
{ "fileExtension", "docx" },
{ "documentId", "2" }
};
Dictionary<string, dynamic> doc3 = new Dictionary<string, dynamic>()
{
{ "name", "Lorem Ipsum" }, // can be different from actual file name
{ "fileExtension", "pdf" },
{ "documentId", "3" }
};
// create a signer recipient to sign the document, identified by name and email
// We're setting the parameters via the object creation
Dictionary<string, dynamic> signer1 = new Dictionary<string, dynamic>()
{
{ "email", signerEmail },
{ "name", signerName },
{ "recipientId", "1" },
{ "routingOrder", "1" }
};
// routingOrder (lower means earlier) determines the order of deliveries
// to the recipients. Parallel routing order is supported by using the
// same integer as the order for two or more recipients.
// create a cc recipient to receive a copy of the documents, identified by name and email
// We're setting the parameters via setters
Dictionary<string, dynamic> cc1 = new Dictionary<string, dynamic>()
{
{ "email", ccEmail },
{ "name", ccName },
{ "routingOrder", "2" },
{ "recipientId", "2" }
};
// Create signHere fields (also known as tabs) on the documents,
// We're using anchor (autoPlace) positioning
//
// The DocuSign platform searches throughout your envelope's
// documents for matching anchor strings. So the
// signHere2 tab will be used in both document 2 and 3 since they
// use the same anchor string for their "signer 1" tabs.
Dictionary<string, dynamic> signHere1 = new Dictionary<string, dynamic>()
{
{ "anchorString", "**signature_1**" },
{ "anchorYOffset", "10" },
{ "anchorUnits", "pixels" },
{ "anchorXOffset", "20" }
};
Dictionary<string, dynamic> signHere2 = new Dictionary<string, dynamic>()
{
{ "anchorString", "/sn1/" },
{ "anchorYOffset", "10" },
{ "anchorUnits", "pixels" },
{ "anchorXOffset", "20" }
};
// Tabs are set per recipient / signer
Dictionary<string, dynamic> signer1Tabs = new Dictionary<string, dynamic>()
{
{ "signHereTabs", new dynamic[] { signHere1, signHere2 } }
};
signer1.Add("tabs", signer1Tabs);
// Recipients holds the different recipient objects as sets of arrays
Dictionary<string, dynamic> recipients = new Dictionary<string, dynamic>()
{
{ "signers", new dynamic[] { signer1 } },
{ "carbonCopies", new dynamic[] { cc1 } }
};
// create the envelope definition
Dictionary<string, dynamic> envelopeDefinition = new Dictionary<string, dynamic>()
{
{ "emailSubject", "Please sign this document set"},
{ "documents", new dynamic[] { doc1, doc2, doc3}},
{ "recipients", recipients },
{ "status", "sent" }
};
return envelopeDefinition;
}
// ***DS.snippet.0.end
[HttpPost]
public IActionResult Create(string signerEmail, string signerName, string ccEmail, string ccName)
{
// Data for this method
// signerEmail
// signerName
// ccEmail
// ccName
var accessToken = RequestItemsService.User.AccessToken;
var basePath = RequestItemsService.Session.BasePath + "/restapi";
var accountId = RequestItemsService.Session.AccountId;
bool tokenOk = CheckToken(3);
if (!tokenOk)
{
// We could store the parameters of the requested operation
// so it could be restarted automatically.
// But since it should be rare to have a token issue here,
// we'll make the user re-enter the form data after
// authentication.
RequestItemsService.EgName = EgName;
return Redirect("/ds/mustAuthenticate");
}
(bool statusOk, string envelopeId, string errorCode, string errorMessage) =
DoWork(signerEmail, signerName, ccEmail, ccName, accessToken, basePath, accountId);
if (statusOk)
{
RequestItemsService.EnvelopeId = envelopeId;
ViewBag.h1 = "Envelope sent";
ViewBag.message = "The envelope has been created and sent!<br/>Envelope ID " + envelopeId + ".";
return View("example_done");
}
else
{
ViewBag.errorCode = errorCode;
ViewBag.errorMessage = errorMessage;
return View("error");
}
}
}
}