ASP.NET MVC 5 - DocuSign - Get And Store Envelop Information Into Database Using EF

Introduction
 
In this article, I will demonstrate how to maintain the DocuSign envelope information in our database using Entity Framework and how to get the envelope information by envelope Id. Please take a look at my previous articles for basic account creation, integration, validation, and creation of a signature request on a document with our application.
Let's move forward to do a storing operation of Envelope Information into our database.
 
Prerequisites 
  • Visual Studio
  • Basic Knowledge of ASP.NET MVC
  • Basic Knowledge of C#
  • Should have an account in DocuSign
Article Flow 
  • Create a table in a database
  • Configure Entity Framework with database and application
  • Get Envelope Information
  • Store Envelope Informations
  • Get Envelope By Envelope Id
Create a table in a database
 
First, we will create a table in SQL Server to store the details of Envelope. I have created a table called "Recipient" with the following design 
 
 
Execute the below query to create a table with the above design.
  1. CREATE TABLE [dbo].[Recipient](  
  2. [Id] [bigint] IDENTITY(1,1) NOT NULL,  
  3. [Name] [nvarchar](250) NULL,  
  4. [Email] [nvarchar](300) NULL,  
  5. [EnvelopeID] [nvarchar](maxNULL,  
  6. [Documents] [varbinary](maxNULL,  
  7. [Description] [nvarchar](maxNULL,  
  8. [Status] [varchar](100) NULL,  
  9. [SentOn] [datetime] NULL,  
  10. [UpdatedOn] [datetime] NULL,  
  11. CONSTRAINT [PK_Recipient] PRIMARY KEY CLUSTERED  
  12. (  
  13.    [Id] ASC  
  14. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  15. ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]  
  16. GO  
Configure Entity Framework with database and application 
 
Here, I have already discussed how to configure and implement a database-first approach. In the meantime, choose your created table with Entity Framework. Once we do our configuration with SQL table "Recipient" from CSharpCorner database and with our application, we will get the below screen as the succeeding configuration 
 
 
 
Get Envelope Information
 
In our previous article discussion, we discussed how to create a signature request on a respective document for the respective recipient, we successfully sent the signature request and got the envelope Id and much more information but we didn't store it anywhere for future reference. So we need to store envelope information, with the help of the envelope information only we can track or get more information from docuSign. For every signature request, we will get a unique envelope id, so we need to store it into our database. We can't get any information without envelope id. Let's create a new signing request and get envelope information and store it in our database.
 
As per the previous article, we will get enough information in the below envelopeSummary object. It contains Status,StatusDateTime and EnvelopeId. So, let's store that information into our database.
  1. EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);  
  2. // print the JSON response  
  3. var result = JsonConvert.SerializeObject(envelopeSummary);  
  4. Recipient recipient = new Recipient();  
  5. recipient.Description = "envDef.EmailSubject";  
  6. recipient.Email = recipientEmail;  
  7. recipient.Name = recipientName;  
  8. recipient.Status = envelopeSummary.Status;  
  9. recipient.Documents = fileBytes;  
  10. recipient.SentOn = System.Convert.ToDateTime(envelopeSummary.StatusDateTime);  
  11. recipient.EnvelopeID = envelopeSummary.EnvelopeId;  
  12. CSharpCornerEntities cSharpCornerEntities = new CSharpCornerEntities();  
  13. cSharpCornerEntities.Recipients.Add(recipient);  
Now, run your application.
 
In the above image, you can see that we got all information and the below image represents our data has been stored in a database. Now, we can proceed with many things with the help of this envelope id and status.
 
 
Get Envelope By Envelope Id
 
Now, let's try to pull the envelope information by passing the evelopeID. 
  1. public ActionResult getEnvelopeInformation() {  
  2.     ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi");  
  3.     Configuration.Default.ApiClient = apiClient;  
  4.     // provide a valid envelope ID from your account.  
  5.     string envelopeId = "3e66307b-e9ba-42a0-9f9e-b3a7016fee2a"//Enter Stored Envelope Id  
  6.     MyCredential myCredential = new MyCredential();  
  7.     // call the Login() API which sets the user's baseUrl and returns their accountId  
  8.     string accountId = loginApi(myCredential.UserName, myCredential.Password);  
  9.     //===========================================================  
  10.     // Step 2: Get Envelope Information  
  11.     //===========================================================  
  12.     // |EnvelopesApi| contains methods related to creating and sending Envelopes including status calls  
  13.     EnvelopesApi envelopesApi = new EnvelopesApi();  
  14.     Envelope envInfo = envelopesApi.GetEnvelope(accountId, envelopeId);  
  15.     return View();  
  16. // end requestSignatu  
Now, run your application. In the below image, you can see that we got much information by passing envelope id, and we will use all properties in the future one by one.
 
 
 Complete controller
  1. using DocuSign.eSign.Api;  
  2. using DocuSign.eSign.Client;  
  3. using DocuSign.eSign.Model;  
  4. using DocusignDemo.Models;  
  5. using Newtonsoft.Json;  
  6. using System.Collections.Generic;  
  7. using System.IO;  
  8. using System.Web;  
  9. using System.Web.Mvc;  
  10. using Document = DocuSign.eSign.Model.Document;  
  11. namespace DocusignDemo.Controllers {  
  12.     public class DocusignController: Controller {  
  13.         MyCredential credential = new MyCredential();  
  14.         private string INTEGRATOR_KEY = "Enter Integrator Key";  
  15.         public ActionResult SendDocumentforSign() {  
  16.                 return View();  
  17.             }  
  18.             [HttpPost]  
  19.         public ActionResult SendDocumentforSign(DocusignDemo.Models.Recipient recipient, HttpPostedFileBase UploadDocument) {  
  20.             Models.Recipient recipientModel = new Models.Recipient();  
  21.             string directorypath = Server.MapPath("~/App_Data/" + "Files/");  
  22.             if (!Directory.Exists(directorypath)) {  
  23.                 Directory.CreateDirectory(directorypath);  
  24.             }  
  25.             byte[] data;  
  26.             using(Stream inputStream = UploadDocument.InputStream) {  
  27.                 MemoryStream memoryStream = inputStream as MemoryStream;  
  28.                 if (memoryStream == null) {  
  29.                     memoryStream = new MemoryStream();  
  30.                     inputStream.CopyTo(memoryStream);  
  31.                 }  
  32.                 data = memoryStream.ToArray();  
  33.             }  
  34.             var serverpath = directorypath + recipient.Name.Trim() + ".pdf";  
  35.             System.IO.File.WriteAllBytes(serverpath, data);  
  36.             docusign(serverpath, recipient.Name, recipient.Email);  
  37.             return View();  
  38.         }  
  39.         public string loginApi(string usr, string pwd) {  
  40.             // we set the api client in global config when we configured the client  
  41.             ApiClient apiClient = Configuration.Default.ApiClient;  
  42.             string authHeader = "{\"Username\":\"" + usr + "\", \"Password\":\"" + pwd + "\", \"IntegratorKey\":\"" + INTEGRATOR_KEY + "\"}";  
  43.             Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);  
  44.             // we will retrieve this from the login() results  
  45.             string accountId = null;  
  46.             // the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object  
  47.             AuthenticationApi authApi = new AuthenticationApi();  
  48.             LoginInformation loginInfo = authApi.Login();  
  49.             // find the default account for this user  
  50.             foreach(DocuSign.eSign.Model.LoginAccount loginAcct in loginInfo.LoginAccounts) {  
  51.                 if (loginAcct.IsDefault == "true") {  
  52.                     accountId = loginAcct.AccountId;  
  53.                     break;  
  54.                 }  
  55.             }  
  56.             if (accountId == null) { // if no default found set to first account  
  57.                 accountId = loginInfo.LoginAccounts[0].AccountId;  
  58.             }  
  59.             return accountId;  
  60.         }  
  61.         public void docusign(string path, string recipientName, string recipientEmail) {  
  62.             ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi");  
  63.             Configuration.Default.ApiClient = apiClient;  
  64.             //Verify Account Details  
  65.             string accountId = loginApi(credential.UserName, credential.Password);  
  66.             // Read a file from disk to use as a document.  
  67.             byte[] fileBytes = System.IO.File.ReadAllBytes(path);  
  68.             EnvelopeDefinition envDef = new EnvelopeDefinition();  
  69.             envDef.EmailSubject = "Please sign this doc";  
  70.             // Add a document to the envelope  
  71.             Document doc = new Document();  
  72.             doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);  
  73.             doc.Name = Path.GetFileName(path);  
  74.             doc.DocumentId = "1";  
  75.             envDef.Documents = new List < Document > ();  
  76.             envDef.Documents.Add(doc);  
  77.             // Add a recipient to sign the documeent  
  78.             DocuSign.eSign.Model.Signer signer = new DocuSign.eSign.Model.Signer();  
  79.             signer.Email = recipientEmail;  
  80.             signer.Name = recipientName;  
  81.             signer.RecipientId = "1";  
  82.             envDef.Recipients = new DocuSign.eSign.Model.Recipients();  
  83.             envDef.Recipients.Signers = new List < DocuSign.eSign.Model.Signer > ();  
  84.             envDef.Recipients.Signers.Add(signer);  
  85.             //set envelope status to "sent" to immediately send the signature request  
  86.             envDef.Status = "sent";  
  87.             // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests)  
  88.             EnvelopesApi envelopesApi = new EnvelopesApi();  
  89.             EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);  
  90.             // print the JSON response  
  91.             var result = JsonConvert.SerializeObject(envelopeSummary);  
  92.             Recipient recipient = new Recipient();  
  93.             recipient.Description = "envDef.EmailSubject";  
  94.             recipient.Email = recipientEmail;  
  95.             recipient.Name = recipientName;  
  96.             recipient.Status = envelopeSummary.Status;  
  97.             recipient.Documents = fileBytes;  
  98.             recipient.SentOn = System.Convert.ToDateTime(envelopeSummary.StatusDateTime);  
  99.             recipient.EnvelopeID = envelopeSummary.EnvelopeId;  
  100.             CSharpCornerEntities cSharpCornerEntities = new CSharpCornerEntities();  
  101.             cSharpCornerEntities.Recipients.Add(recipient);  
  102.             cSharpCornerEntities.SaveChanges();  
  103.         }  
  104.         public ActionResult getEnvelopeInformation() {  
  105.             ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi");  
  106.             Configuration.Default.ApiClient = apiClient;  
  107.             // provide a valid envelope ID from your account.  
  108.             string envelopeId = "Enter Stored Envelope Id"//Enter Stored Envelope Id  
  109.             MyCredential myCredential = new MyCredential();  
  110.             // call the Login() API which sets the user's baseUrl and returns their accountId  
  111.             string accountId = loginApi(myCredential.UserName, myCredential.Password);  
  112.             //===========================================================  
  113.             // Step 2: Get Envelope Information  
  114.             //===========================================================  
  115.             // |EnvelopesApi| contains methods related to creating and sending Envelopes including status calls  
  116.             EnvelopesApi envelopesApi = new EnvelopesApi();  
  117.             Envelope envInfo = envelopesApi.GetEnvelope(accountId, envelopeId);  
  118.             return View();  
  119.         } // end requestSignatu  
  120.     }  
  121.     public class MyCredential {  
  122.         public string UserName {  
  123.             get;  
  124.             set;  
  125.         } = "Enter your username";  
  126.         public string Password {  
  127.             get;  
  128.             set;  
  129.         } = "Enter your Password";  
  130.     }  
  131. }  
Refer to the attached project. I did attach the demonstrated project without a package due to the size limit. Wait for my next docuSign article to get more knowledge on this.
 
Summary
 
In this article, we discussed how to maintain the DocuSign envelope information in our database using Entity Framework and how to get envelope information by envelope Id. I hope it will help you out. Your valuable feedback and comments about this article are always welcome. 


Similar Articles