protected void Page_Load(object sender, EventArgs e)
        {
            DocusignAuth docusignObj = new DocusignAuth();

            docusignObj.UserName      = ConfigurationManager.AppSettings["Username"].ToString();
            docusignObj.Password      = ConfigurationManager.AppSettings["Password"].ToString();
            docusignObj.IntegratorKey = ConfigurationManager.AppSettings["IntegratorKey"].ToString();
            docusignObj.TemplateId    = ConfigurationManager.AppSettings["TemplateId"].ToString();
            docusignObj.Url           = ConfigurationManager.AppSettings["Url"].ToString();

            DocusignMethods docusignMethods = new DocusignMethods(docusignObj);



            #region Document
            Document document = new Document();
            document.documentId = "1";
            document.name       = "test_document.pdf";

            DocDetail docDetail = new DocDetail();
            docDetail.document = document;
            #endregion

            #region RecipientCreation
            SignHere objSignHere = new SignHere();
            objSignHere.xPosition  = "100";
            objSignHere.yPosition  = "100";
            objSignHere.documentId = "1";
            objSignHere.pageNumber = "1";

            SignHereTab objSignHereTab = new SignHereTab();
            objSignHereTab.signHere = objSignHere;

            Tab objTab = new Tab();
            objTab.signHereTabs = objSignHereTab;

            signer objSigner = new signer();
            objSigner.recipientId = "1";
            objSigner.name        = "jay";
            objSigner.email       = "*****@*****.**";
            objSigner.tabs        = objTab;

            List <signer> signerList = new List <signer>();
            signerList.Add(objSigner);

            Recipients recip = new Recipients();
            recip.signers = signerList;

            #endregion

            envelopeDefinition data = new envelopeDefinition();
            data.emailSubject = "Hello";
            data.emailBlurb   = "Hello";
            data.status       = signatureStatus.sent;
            data.documents    = docDetail;
            data.recipients   = recip;

            string response = docusignMethods.RequestSignatureFromDocument(@"C:\Users\jay\Desktop\test_document.pdf", data);
        }
        protected override void Execute(CodeActivityContext context)
        {
            Initialize(context);
            SignHereTab signHereTab;

            scaleValue = ScaleValue.Get(context);

            if (anchorText != null)
            {
                signHereTab = new SignHereTab(anchorText, offsetX, offsetY - 21, doc.documentId, pageNumber, toolTip, tabLabel, scaleValue, !Required);
            }
            else
            {
                signHereTab = new SignHereTab(sigX, sigY - 21, doc.documentId, pageNumber, toolTip, tabLabel, scaleValue, !Required);
            }

            AddTabToRecipient(signHereTab);
        }
        void SendEnvelope()
        {
            int docId        = 1;
            int recptId      = 1;
            int routingOrder = 1;

            Document        document  = new Document(Path.GetFileName(documentFilePath), documentFilePath, docId);
            List <Document> documents = new List <Document>()
            {
                document
            };

            SignHereTab signHereTab;

            if (anchorText != null)
            {
                signHereTab = new SignHereTab(anchorText, offsetX, offsetY, docId, 1, null, null, 1, false);
            }
            else
            {
                signHereTab = new SignHereTab(sigX, sigY, docId, 1, null, null, 1, false);
            }

            List <Tab> tabs = new List <Tab>()
            {
                signHereTab
            };
            Signer r1signer = new Signer(recipientName, recipientEmail, routingOrder, tabs, recptId);

            List <Recipient> recipients = new List <Recipient>()
            {
                r1signer
            };

            Envelope env = new Envelope(subject, documents, recipients);

            DocusignResponse response = new DocusignResponse();

            SendRestRequest(response, HttpMethod.Post, "envelopes", env).Wait();
            if (response.IsError)
            {
                response.Throw();
            }
        }
Example #4
0
    protected void createEnvelope()
    {
        // Set up the envelope
        CreateEnvelopeRequest createEnvelopeRequest = new CreateEnvelopeRequest();

        createEnvelopeRequest.emailSubject = "Template Example";
        createEnvelopeRequest.status       = "sent";
        createEnvelopeRequest.emailBlurb   = "Example of how template functionality works";

        // Define first signer
        Signer signer = new Signer();

        signer.email        = email.Value;
        signer.name         = firstname.Value + " " + lastname.Value;
        signer.recipientId  = 1;
        signer.routingOrder = "1";
        signer.roleName     = "Signer1";
        signer.clientUserId = RandomizeClientUserID();  // First signer is embedded

        // Add tabs for the signer
        signer.tabs = new Tabs();
        signer.tabs.signHereTabs = new List <SignHereTab>();
        SignHereTab signHereTab = new SignHereTab();

        signHereTab.documentId   = "1";
        signHereTab.tabId        = "1";
        signHereTab.anchorString = tab1AnchorText.Value;
        signHereTab.name         = tabName.Value;
        signer.tabs.signHereTabs.Add(signHereTab);

        signer.tabs.dateSignedTabs = new List <DateSignedTab>();
        DateSignedTab dateSignedTab = new DateSignedTab();

        dateSignedTab.documentId   = "1";
        dateSignedTab.tabId        = "2";
        dateSignedTab.anchorString = tab2AnchorText.Value;
        dateSignedTab.name         = tab2Name.Value;
        signer.tabs.dateSignedTabs.Add(dateSignedTab);

        // Define a document
        Document document = new Document();

        document.documentId         = "1";
        document.name               = "Sample Form";
        document.transformPdfFields = "true";

        // Define an inline template
        InlineTemplate inline1 = new InlineTemplate();

        inline1.sequence           = "2";
        inline1.recipients         = new Recipients();
        inline1.recipients.signers = new List <Signer>();
        inline1.recipients.signers.Add(signer);


        // Add the inline template to a CompositeTemplate
        CompositeTemplate compositeTemplate1 = new CompositeTemplate();

        compositeTemplate1.inlineTemplates = new List <InlineTemplate>();
        compositeTemplate1.inlineTemplates.Add(inline1);
        compositeTemplate1.document = document;

        // Add compositeTemplate to the envelope
        createEnvelopeRequest.compositeTemplates = new List <CompositeTemplate>();
        createEnvelopeRequest.compositeTemplates.Add(compositeTemplate1);


        string output = JsonConvert.SerializeObject(createEnvelopeRequest);

        // Specify a unique boundary string that doesn't appear in the json or document bytes.
        string Boundary = "MY_BOUNDARY";

        // Set the URI
        HttpWebRequest request = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/v2/accounts/" + ConfigurationManager.AppSettings["API.TemplatesAccountID"] + "/envelopes") as HttpWebRequest;

        // Set the method
        request.Method = "POST";

        // Set the authentication header
        request.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

        // Set the overall request content type aand boundary string
        request.ContentType = "multipart/form-data; boundary=" + Boundary;
        request.Accept      = "application/json";

        // Start forming the body of the request
        Stream reqStream = request.GetRequestStream();

        // write boundary marker between parts
        WriteStream(reqStream, "\n--" + Boundary + "\n");

        // write out the json envelope definition part
        WriteStream(reqStream, "Content-Type: application/json\n");
        WriteStream(reqStream, "Content-Disposition: form-data\n");
        WriteStream(reqStream, "\n"); // requires an empty line between the header and the json body
        WriteStream(reqStream, output);

        // write out the form bytes for the first form
        WriteStream(reqStream, "\n--" + Boundary + "\n");
        WriteStream(reqStream, "Content-Type: application/pdf\n");
        WriteStream(reqStream, "Content-Disposition: file; filename=\"Sample_Form\"; documentId=1\n");
        WriteStream(reqStream, "\n");
        String filename = uploadFile.Value;

        if (File.Exists(Server.MapPath("~/App_Data/" + filename)))
        {
            // Read the file contents and write them to the request stream
            byte[] buf = new byte[4096];
            int    len;
            // read contents of document into the request stream
            FileStream fileStream = File.OpenRead(Server.MapPath("~/App_Data/" + filename));
            while ((len = fileStream.Read(buf, 0, 4096)) > 0)
            {
                reqStream.Write(buf, 0, len);
            }
            fileStream.Close();
        }


        // wrte the end boundary marker - ensure that it is on its own line
        WriteStream(reqStream, "\n--" + Boundary + "--");
        WriteStream(reqStream, "\n");

        try
        {
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.Created)
            {
                byte[] responseBytes = new byte[response.ContentLength];
                using (var reader = new System.IO.BinaryReader(response.GetResponseStream()))
                {
                    reader.Read(responseBytes, 0, responseBytes.Length);
                }
                string responseText = Encoding.UTF8.GetString(responseBytes);
                CreateEnvelopeResponse createEnvelopeResponse = new CreateEnvelopeResponse();

                createEnvelopeResponse = JsonConvert.DeserializeObject <CreateEnvelopeResponse>(responseText);
                if (createEnvelopeResponse.status.Equals("sent"))
                {
                    // Now that we have created the envelope, get the recipient token for the first signer
                    String url = Request.Url.AbsoluteUri;
                    RecipientViewRequest recipientViewRequest = new RecipientViewRequest();
                    recipientViewRequest.authenticationMethod = "email";
                    recipientViewRequest.clientUserId         = signer.clientUserId;
                    recipientViewRequest.email = email.Value;
                    if (!Request.Browser.IsMobileDevice)
                    {
                        recipientViewRequest.returnUrl = url.Substring(0, url.LastIndexOf("/")) + "/EmbeddedSigningComplete0.aspx?envelopeID=" + createEnvelopeResponse.envelopeId;
                    }
                    else
                    {
                        recipientViewRequest.returnUrl = url.Substring(0, url.LastIndexOf("/")) + "/ConfirmationPage.aspx?envelopeID=" + createEnvelopeResponse.envelopeId;
                    }
                    recipientViewRequest.userName = firstname.Value + " " + lastname.Value;

                    HttpWebRequest request2 = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/v2/accounts/" + ConfigurationManager.AppSettings["API.TemplatesAccountID"] + "/envelopes/" + createEnvelopeResponse.envelopeId + "/views/recipient") as HttpWebRequest;
                    request2.Method = "POST";

                    // Set the authenticationheader
                    request2.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

                    request2.Accept      = "application/json";
                    request2.ContentType = "application/json";

                    Stream reqStream2 = request2.GetRequestStream();

                    WriteStream(reqStream2, JsonConvert.SerializeObject(recipientViewRequest));
                    HttpWebResponse response2 = request2.GetResponse() as HttpWebResponse;

                    responseBytes = new byte[response2.ContentLength];
                    using (var reader = new System.IO.BinaryReader(response2.GetResponseStream()))
                    {
                        reader.Read(responseBytes, 0, responseBytes.Length);
                    }
                    string response2Text = Encoding.UTF8.GetString(responseBytes);

                    RecipientViewResponse recipientViewResponse = new RecipientViewResponse();
                    recipientViewResponse = JsonConvert.DeserializeObject <RecipientViewResponse>(response2Text);
                    Session.Add("envelopeID", createEnvelopeResponse.envelopeId);

                    // If it's a non-touch aware device, show the signing session in an iFrame
                    if (!Request.Browser.IsMobileDevice)
                    {
                        if (!Request.Browser.Browser.Equals("InternetExplorer") && (!Request.Browser.Browser.Equals("Safari")))
                        {
                            docusignFrame.Visible = true;
                            docusignFrame.Src     = recipientViewResponse.url;
                        }
                        else // Handle IE differently since it does not allow dynamic setting of the iFrame width and height
                        {
                            docusignFrameIE.Visible = true;
                            docusignFrameIE.Src     = recipientViewResponse.url;
                        }
                    }
                    // For touch aware devices, show the signing session in main browser window
                    else
                    {
                        Response.Redirect(recipientViewResponse.url);
                    }
                }
            }
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                using (var reader = new System.IO.StreamReader(ex.Response.GetResponseStream(), UTF8Encoding.UTF8))
                {
                    string       errorMess = reader.ReadToEnd();
                    log4net.ILog logger    = log4net.LogManager.GetLogger(typeof(demos_AnchorTextREST));
                    logger.Info("\n----------------------------------------\n");
                    logger.Error("DocuSign Error: " + errorMess);
                    logger.Error(ex.StackTrace);
                    Response.Write(ex.Message);
                }
            }
            else
            {
                log4net.ILog logger = log4net.LogManager.GetLogger(typeof(demos_AnchorTextREST));
                logger.Info("\n----------------------------------------\n");
                logger.Error("WebRequest Error: " + ex.Message);
                logger.Error(ex.StackTrace);
                Response.Write(ex.Message);
            }
        }
    }
Example #5
0
    protected void createEnvelopeResponsive()
    {
        // Set up the envelope
        CreateEnvelopeRequest createEnvelopeRequest = new CreateEnvelopeRequest();

        createEnvelopeRequest.emailSubject = "Business Credit Card Approval";
        createEnvelopeRequest.status       = "sent";
        createEnvelopeRequest.emailBlurb   = "Please review & DocuSign your business credit cards approval";

        // Define first signer
        Signer signer = new Signer();

        signer.email        = Email.Value;
        signer.name         = firstName.Value + ' ' + lastName.Value;
        signer.recipientId  = 1;
        signer.routingOrder = "1";
        signer.roleName     = "signer";
        signer.clientUserId = RandomizeClientUserID();


        //// Add tabs for the signer
        signer.tabs = new Tabs();
        signer.tabs.dateSignedTabs = new List <DateSignedTab>();
        DateSignedTab dateSignedTab = new DateSignedTab();

        dateSignedTab.documentId  = "1";
        dateSignedTab.pageNumber  = "1";
        dateSignedTab.font        = "arial";
        dateSignedTab.fontSize    = "size12";
        dateSignedTab.fontColor   = "black";
        dateSignedTab.recipientId = "1";
        dateSignedTab.tabLabel    = "clientDateSigned";
        signer.tabs.dateSignedTabs.Add(dateSignedTab);


        signer.tabs.signHereTabs = new List <SignHereTab>();
        SignHereTab signHereTab = new SignHereTab();

        signHereTab.stampType   = "signature";
        signHereTab.name        = "SignHere";
        signHereTab.tabLabel    = "clientSignature";
        signHereTab.scaleValue  = "1";
        signHereTab.optional    = "false";
        signHereTab.recipientId = "1";
        signer.tabs.signHereTabs.Add(signHereTab);

        signer.tabs.textTabs = new List <TextTab>();
        TextTab texttab2 = new TextTab();

        texttab2.isPaymentAmount              = "false";
        texttab2.validationMessage            = "";
        texttab2.validationPattern            = "";
        texttab2.shared                       = "false";
        texttab2.requireInitialOnSharedChange = "false";
        texttab2.requireAll                   = "false";
        texttab2.value    = firstName.Value + " " + lastName.Value + "/" + title.Value;
        texttab2.required = "true";
        texttab2.locked   = "true";
        texttab2.concealValueOnDocument = "false";
        texttab2.disableAutoSize        = "false";
        texttab2.maxLength   = "4000";
        texttab2.tabLabel    = "Approver";
        texttab2.font        = "arial";
        texttab2.bold        = "false";
        texttab2.italic      = "false";
        texttab2.underline   = "false";
        texttab2.fontColor   = "black";
        texttab2.fontSize    = "size12";
        texttab2.documentId  = "1";
        texttab2.recipientId = "1";
        texttab2.width       = "100";
        texttab2.height      = "11";
        signer.tabs.textTabs.Add(texttab2);

        TextTab texttab3 = new TextTab();

        texttab3.isPaymentAmount              = "false";
        texttab3.validationMessage            = "";
        texttab3.validationPattern            = "";
        texttab3.shared                       = "false";
        texttab3.requireInitialOnSharedChange = "false";
        texttab3.requireAll                   = "false";
        texttab3.value    = businessName.Value;
        texttab3.required = "true";
        texttab3.locked   = "true";
        texttab3.concealValueOnDocument = "false";
        texttab3.disableAutoSize        = "false";
        texttab3.maxLength   = "4000";
        texttab3.tabLabel    = "BusinessName";
        texttab3.font        = "arial";
        texttab3.bold        = "false";
        texttab3.italic      = "false";
        texttab3.underline   = "false";
        texttab3.fontColor   = "black";
        texttab3.fontSize    = "size12";
        texttab3.documentId  = "1";
        texttab3.recipientId = "1";
        texttab3.width       = "60";
        texttab3.height      = "11";
        signer.tabs.textTabs.Add(texttab3);



        createEnvelopeRequest.recipients = new Recipients();

        createEnvelopeRequest.recipients.signers = new List <Signer>();
        createEnvelopeRequest.recipients.signers.Add(signer);

        // Define a document
        Document document = new Document();

        document.documentId     = "1";
        document.name           = "Business Credit Card Approval";
        document.htmlDefinition = new HtmlDefinition();
        // Read in the HTML file
        document.htmlDefinition.source = File.ReadAllText(Server.MapPath("~/App_Data/") + "digbankingdemo.html");

        // Define display anchors
        document.htmlDefinition.displayAnchors = new List <DisplayAnchor>();
        DisplayAnchor displayAnchor = new DisplayAnchor();

        displayAnchor.startAnchor                = "responsive_table_start";
        displayAnchor.endAnchor                  = "responsive_table_end";
        displayAnchor.removeEndAnchor            = true;
        displayAnchor.removeStartAnchor          = true;
        displayAnchor.caseSensitive              = true;
        displayAnchor.displaySettings            = new DisplaySettings();
        displayAnchor.displaySettings.display    = "responsive_table_single_column";
        displayAnchor.displaySettings.tableStyle = "margin-bottom: 20px;width:100%;max-width:816px;margin-left:auto;margin-right:auto;";
        displayAnchor.displaySettings.cellStyle  = "text-align:left;border:solid 0px #000;margin:0px;padding:0px;";
        document.htmlDefinition.displayAnchors.Add(displayAnchor);

        createEnvelopeRequest.documents = new List <Document>();
        createEnvelopeRequest.documents.Add(document);
        createEnvelopeRequest.brandId = ConfigurationManager.AppSettings["MomentumBrandID"];



        // Set up Connect
        createEnvelopeRequest.eventNotification = getConnectSetup();


        string output = JsonConvert.SerializeObject(createEnvelopeRequest);

        // Set the URI
        HttpWebRequest request = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/vdev/accounts/" + ConfigurationManager.AppSettings["API.AccountId"] + "/envelopes") as HttpWebRequest;

        // Set the method
        request.Method = "POST";

        // Set the authentication header
        request.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

        // Set the overall request content type aand boundary string
        request.ContentType = "application/json";
        request.Accept      = "application/json";

        // Start forming the body of the request
        Stream reqStream = request.GetRequestStream();


        WriteStream(reqStream, "\n"); // requires an empty line between the header and the json body
        WriteStream(reqStream, output);



        try
        {
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.Created)
            {
                byte[] responseBytes = new byte[response.ContentLength];
                using (var reader = new System.IO.BinaryReader(response.GetResponseStream()))
                {
                    reader.Read(responseBytes, 0, responseBytes.Length);
                }
                string responseText = Encoding.UTF8.GetString(responseBytes);
                CreateEnvelopeResponse createEnvelopeResponse = new CreateEnvelopeResponse();

                createEnvelopeResponse = JsonConvert.DeserializeObject <CreateEnvelopeResponse>(responseText);
                if (createEnvelopeResponse.status.Equals("sent"))
                {
                    // Now that we have created the envelope, get the recipient token for the first signer
                    String url = Request.Url.AbsoluteUri;
                    RecipientViewRequest recipientViewRequest = new RecipientViewRequest();
                    recipientViewRequest.authenticationMethod = "email";
                    recipientViewRequest.clientUserId         = signer.clientUserId;
                    recipientViewRequest.email     = Email.Value;
                    recipientViewRequest.returnUrl = url.Substring(0, url.LastIndexOf("/")) + "/ConfirmationScreen.aspx";
                    recipientViewRequest.userName  = firstName.Value + " " + lastName.Value;

                    HttpWebRequest request2 = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/v2/accounts/" + ConfigurationManager.AppSettings["API.TemplatesAccountID"] + "/envelopes/" + createEnvelopeResponse.envelopeId + "/views/recipient") as HttpWebRequest;
                    request2.Method = "POST";

                    // Set the authenticationheader
                    request2.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

                    request2.Accept      = "application/json";
                    request2.ContentType = "application/json";

                    Stream reqStream2 = request2.GetRequestStream();

                    WriteStream(reqStream2, JsonConvert.SerializeObject(recipientViewRequest));
                    HttpWebResponse response2 = request2.GetResponse() as HttpWebResponse;

                    responseBytes = new byte[response2.ContentLength];
                    using (var reader = new System.IO.BinaryReader(response2.GetResponseStream()))
                    {
                        reader.Read(responseBytes, 0, responseBytes.Length);
                    }
                    string response2Text = Encoding.UTF8.GetString(responseBytes);

                    RecipientViewResponse recipientViewResponse = new RecipientViewResponse();
                    recipientViewResponse = JsonConvert.DeserializeObject <RecipientViewResponse>(response2Text);
                    Session.Add("envelopeID", createEnvelopeResponse.envelopeId);

                    Response.Redirect(recipientViewResponse.url);
                }
            }
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                using (var reader = new System.IO.StreamReader(ex.Response.GetResponseStream(), UTF8Encoding.UTF8))
                {
                    string       errorMess = reader.ReadToEnd();
                    log4net.ILog logger    = log4net.LogManager.GetLogger(typeof(BusinessCCApproval));
                    logger.Info("\n----------------------------------------\n");
                    logger.Error("DocuSign Error: " + errorMess);
                    logger.Error(ex.StackTrace);
                    Response.Write(ex.Message);
                }
            }
            else
            {
                log4net.ILog logger = log4net.LogManager.GetLogger(typeof(BusinessCCApproval));
                logger.Info("\n----------------------------------------\n");
                logger.Error("WebRequest Error: " + ex.Message);
                logger.Error(ex.StackTrace);
                Response.Write(ex.Message);
            }
        }
    }
Example #6
0
        public static void Main()
        {
            DocuSignCredentials credentials = new DocuSignCredentials();

            credentials.username      = "";                     // your account email
            credentials.password      = "";                     // your account password
            credentials.integratorKey = "";                     // your account Integrator Key (found on Preferences -> API page)
            credentials.accountId     = "";
            credentials.baseUrl       = "https://demo.docusign.net/";

            DocuSignClient client = new DocuSignClient(credentials);

            Envelope envelope = new Envelope();

            envelope.status       = "sent";
            envelope.emailSubject = "Test API Call Create Envelope";

            Signer signer = new Signer();

            signer.email       = "";
            signer.name        = "";
            signer.recipientId = 1;

            SignHereTab signHereTab = new SignHereTab();

            signHereTab.anchorString  = "/S1Sign/";
            signHereTab.anchorXOffset = "-20";
            signHereTab.anchorYOffset = "120";

            InitialHereTab initialHereTab = new InitialHereTab();

            initialHereTab.anchorString  = "/S1Initial/";
            initialHereTab.anchorXOffset = "10";
            initialHereTab.anchorYOffset = "120";

            FullNameTab fullNameTab = new FullNameTab();

            fullNameTab.anchorString  = "/S1FullName/";
            fullNameTab.anchorXOffset = "-20";
            fullNameTab.anchorYOffset = "120";

            DateSignedTab dateSignedTab = new DateSignedTab();

            dateSignedTab.anchorString  = "/S1Date/";
            dateSignedTab.anchorXOffset = "-20";
            dateSignedTab.anchorYOffset = "120";

            signer.tabs = new Tabs();
            signer.tabs.signHereTabs = new List <SignHereTab>();
            signer.tabs.signHereTabs.Add(signHereTab);

            signer.tabs.initialHereTabs = new List <InitialHereTab>();
            signer.tabs.initialHereTabs.Add(initialHereTab);

            signer.tabs.fullNameTabs = new List <FullNameTab>();
            signer.tabs.fullNameTabs.Add(fullNameTab);

            signer.tabs.dateSignedTabs = new List <DateSignedTab>();
            signer.tabs.dateSignedTabs.Add(dateSignedTab);

            envelope.recipients         = new Recipients();
            envelope.recipients.signers = new List <Signer>();
            envelope.recipients.signers.Add(signer);

            Document document = new Document();

            document.name       = "Try DocuSigning.docx"; // copy document with same name and extension into project directory (i.e. "test.pdf")
            document.documentId = 1;

            envelope.documents = new List <Document>();
            envelope.documents.Add(document);

            CreateEnvelopeResponse response = client.CreateAndSendEnvelope(envelope);

            Trace.WriteLine(response);
        }
    protected void createEnvelope()
    {
        // Set up the envelope
        CreateEnvelopeRequest createEnvelopeRequest = new CreateEnvelopeRequest();

        createEnvelopeRequest.emailSubject = "DOL Example";
        createEnvelopeRequest.status       = "sent";
        createEnvelopeRequest.emailBlurb   = "Example of how DOL functionality could work";

        // Add documents (one main document and one supplemental document to show as terms and conditions)
        createEnvelopeRequest.documents = new List <Document>();
        Document mainDocument = new Document();

        mainDocument.name              = "Main Document";
        mainDocument.documentId        = "1";
        mainDocument.fileExtension     = "doc";
        mainDocument.includeInDownload = null;
        createEnvelopeRequest.documents.Add(mainDocument);

        Document supplementalDocument = new Document();

        supplementalDocument.name          = "Terms & Conditions";
        supplementalDocument.documentId    = "2";
        supplementalDocument.fileExtension = "doc";

        if (IncludeInDownloadTrue.Checked)
        {
            supplementalDocument.includeInDownload = true;
        }
        else if (IncludeInDownloadFalse.Checked)
        {
            supplementalDocument.includeInDownload = false;
        }

        // Registration type
        //if (Modal.Checked)
        //{
        supplementalDocument.display = "modal";
        //}
        //else if (Download.Checked)
        //{
        //    supplementalDocument.display = "download";
        //}
        //else if (Inline.Checked)
        //{
        //    supplementalDocument.display = "inline";
        //}

        if (View_.Checked)
        {
            supplementalDocument.signerMustAcknowledge = "view";
        }
        else if (Accept.Checked)
        {
            supplementalDocument.signerMustAcknowledge = "accept";
        }
        else if (View_Accept.Checked)
        {
            supplementalDocument.signerMustAcknowledge = "view_accept";
        }
        else if (No_Interaction.Checked)
        {
            supplementalDocument.signerMustAcknowledge = "no_interaction";
        }

        createEnvelopeRequest.documents.Add(supplementalDocument);

        // Add recipients
        createEnvelopeRequest.recipients         = new Recipients();
        createEnvelopeRequest.recipients.signers = new List <Signer>();
        Signer signerOne = new Signer();

        signerOne.name         = firstname.Value + " " + lastname.Value;
        signerOne.email        = email.Value;
        signerOne.recipientId  = "1";
        signerOne.roleName     = "signer1";
        signerOne.routingOrder = "1";
        if (embedded.Checked)
        {
            signerOne.clientUserId = RandomizeClientUserID();
        }

        // Add tab for the recipient
        signerOne.tabs = new Tabs();
        signerOne.tabs.signHereTabs = new List <SignHereTab>();
        SignHereTab signHereTab = new SignHereTab();

        signHereTab.documentId = "1";
        signHereTab.pageNumber = tabPage.Value;
        signHereTab.tabId      = "1";
        signHereTab.xPosition  = xPosition.Value;
        signHereTab.yPosition  = yPosition.Value;
        signHereTab.name       = "sigTab";
        signerOne.tabs.signHereTabs.Add(signHereTab);

        createEnvelopeRequest.recipients.signers.Add(signerOne);

        string output = JsonConvert.SerializeObject(createEnvelopeRequest);

        if (accountId.Value.Length == 0)
        {
            accountId.Value = ConfigurationManager.AppSettings["API.AccountID"];
        }

        // Specify a unique boundary string that doesn't appear in the json or document bytes.
        string Boundary = "MY_BOUNDARY";

        // Set the URI
        HttpWebRequest request = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/v2/accounts/" + accountId.Value + "/envelopes") as HttpWebRequest;

        // Set the method
        request.Method = "POST";

        // Set the authentication header
        request.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

        // Set the overall request content type aand boundary string
        request.ContentType = "multipart/form-data; boundary=" + Boundary;
        request.Accept      = "application/json";

        // Start forming the body of the request
        Stream reqStream = request.GetRequestStream();

        // write boundary marker between parts
        WriteStream(reqStream, "\n--" + Boundary + "\n");

        // write out the json envelope definition part
        WriteStream(reqStream, "Content-Type: application/json\n");
        WriteStream(reqStream, "Content-Disposition: form-data\n");
        WriteStream(reqStream, "\n"); // requires an empty line between the header and the json body
        WriteStream(reqStream, output);

        // write out the form bytes for the first form
        WriteStream(reqStream, "\n--" + Boundary + "\n");

        WriteStream(reqStream, "Content-Type: application/pdf\n");
        WriteStream(reqStream, "Content-Disposition: file; filename=\"Main Document\"; documentId=1\n");
        WriteStream(reqStream, "\n");
        String filename = uploadFile.Value;

        if (File.Exists(Server.MapPath("~/App_Data/" + filename)))
        {
            // Read the file contents and write them to the request stream
            byte[] buf = new byte[4096];
            int    len;
            // read contents of document into the request stream
            FileStream fileStream = File.OpenRead(Server.MapPath("~/App_Data/" + filename));
            while ((len = fileStream.Read(buf, 0, 4096)) > 0)
            {
                reqStream.Write(buf, 0, len);
            }
            fileStream.Close();
        }

        // write out the form bytes for the second form
        WriteStream(reqStream, "\n--" + Boundary + "\n");

        WriteStream(reqStream, "Content-Type: application/pdf\n");
        WriteStream(reqStream, "Content-Disposition: file; filename=\"Supplemental Document\"; documentId=2\n");
        WriteStream(reqStream, "\n");
        String filename2 = uploadFile2.Value;

        if (File.Exists(Server.MapPath("~/App_Data/" + filename2)))
        {
            // Read the file contents and write them to the request stream
            byte[] buf = new byte[4096];
            int    len;
            // read contents of document into the request stream
            FileStream fileStream = File.OpenRead(Server.MapPath("~/App_Data/" + filename2));
            while ((len = fileStream.Read(buf, 0, 4096)) > 0)
            {
                reqStream.Write(buf, 0, len);
            }
            fileStream.Close();
        }
        // wrte the end boundary marker - ensure that it is on its own line
        WriteStream(reqStream, "\n--" + Boundary + "--");
        WriteStream(reqStream, "\n");

        try
        {
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.Created)
            {
                byte[] responseBytes = new byte[response.ContentLength];
                using (var reader = new System.IO.BinaryReader(response.GetResponseStream()))
                {
                    reader.Read(responseBytes, 0, responseBytes.Length);
                }
                string responseText = Encoding.UTF8.GetString(responseBytes);
                CreateEnvelopeResponse createEnvelopeResponse = new CreateEnvelopeResponse();

                createEnvelopeResponse = JsonConvert.DeserializeObject <CreateEnvelopeResponse>(responseText);
                if (createEnvelopeResponse.status.Equals("sent"))
                {
                    if (remote.Checked)
                    {
                        Response.Redirect("ConfirmationPage.aspx");
                    }
                    else
                    {
                        // Now that we have created the envelope, get the recipient token for the first signer
                        String url = Request.Url.AbsoluteUri;
                        RecipientViewRequest recipientViewRequest = new RecipientViewRequest();
                        recipientViewRequest.authenticationMethod = "email";
                        recipientViewRequest.clientUserId         = signerOne.clientUserId;
                        recipientViewRequest.email = email.Value;
                        if (!Request.Browser.IsMobileDevice)
                        {
                            recipientViewRequest.returnUrl = url.Substring(0, url.LastIndexOf("/")) + "/EmbeddedSigningComplete0.aspx?envelopeID=" + createEnvelopeResponse.envelopeId;
                        }
                        else
                        {
                            recipientViewRequest.returnUrl = url.Substring(0, url.LastIndexOf("/")) + "/ConfirmationPage.aspx?envelopeID=" + createEnvelopeResponse.envelopeId;
                        }
                        recipientViewRequest.userName = signerOne.name;

                        HttpWebRequest request2 = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/v2/accounts/" + accountId.Value + "/envelopes/" + createEnvelopeResponse.envelopeId + "/views/recipient") as HttpWebRequest;
                        request2.Method = "POST";

                        // Set the authenticationheader
                        request2.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

                        request2.Accept      = "application/json";
                        request2.ContentType = "application/json";

                        Stream reqStream2 = request2.GetRequestStream();

                        WriteStream(reqStream2, JsonConvert.SerializeObject(recipientViewRequest));
                        HttpWebResponse response2 = request2.GetResponse() as HttpWebResponse;

                        responseBytes = new byte[response2.ContentLength];
                        using (var reader = new System.IO.BinaryReader(response2.GetResponseStream()))
                        {
                            reader.Read(responseBytes, 0, responseBytes.Length);
                        }
                        string response2Text = Encoding.UTF8.GetString(responseBytes);

                        RecipientViewResponse recipientViewResponse = new RecipientViewResponse();
                        recipientViewResponse = JsonConvert.DeserializeObject <RecipientViewResponse>(response2Text);
                        Session.Add("envelopeID", createEnvelopeResponse.envelopeId);

                        // If it's a non-touch aware device, show the signing session in an iFrame
                        if (!Request.Browser.IsMobileDevice)
                        {
                            // If it's a non-touch aware device, show the signing session in an iFrame
                            if (!Request.Browser.Browser.Equals("InternetExplorer") && (!Request.Browser.Browser.Equals("Safari")))
                            {
                                docusignFrame.Visible = true;
                                docusignFrame.Src     = recipientViewResponse.url;
                            }
                            else // Handle IE differently since it does not allow dynamic setting of the iFrame width and height
                            {
                                docusignFrameIE.Visible = true;
                                docusignFrameIE.Src     = recipientViewResponse.url;
                            }
                        }
                        // For touch aware devices, show the signing session in main browser window
                        else
                        {
                            Response.Redirect(recipientViewResponse.url);
                        }
                    }
                }
            }
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                using (var reader = new System.IO.StreamReader(ex.Response.GetResponseStream(), UTF8Encoding.UTF8))
                {
                    string       errorMess = reader.ReadToEnd();
                    log4net.ILog logger    = log4net.LogManager.GetLogger(typeof(demos_DOL));
                    logger.Info("\n----------------------------------------\n");
                    logger.Error("DocuSign Error: " + errorMess);
                    logger.Error(ex.StackTrace);
                    Response.Write(ex.Message);
                }
            }
            else
            {
                log4net.ILog logger = log4net.LogManager.GetLogger(typeof(demos_DOL));
                logger.Info("\n----------------------------------------\n");
                logger.Error("WebRequest Error: " + ex.Message);
                logger.Error(ex.StackTrace);
                Response.Write(ex.Message);
            }
        }
    }
    protected void createEnvelope()
    {
        // Set up the envelope
        CreateEnvelopeRequest createEnvelopeRequest = new CreateEnvelopeRequest();

        createEnvelopeRequest.emailSubject = "Kitchen Sink Example";
        createEnvelopeRequest.status       = "sent";
        createEnvelopeRequest.emailBlurb   = "Example of how different smart anchors work";

        // Define first signer
        Signer signer = new Signer();

        signer.email        = email.Value;
        signer.name         = firstname.Value + " " + lastname.Value;
        signer.recipientId  = 1;
        signer.routingOrder = "1";
        signer.roleName     = "Signer1";
        signer.clientUserId = RandomizeClientUserID();  // First signer is embedded

        // Add tabs for the signer
        signer.tabs = new Tabs();
        signer.tabs.signHereTabs = new List <SignHereTab>();
        SignHereTab signHereTab = new SignHereTab();

        signHereTab.documentId               = "1";
        signHereTab.tabId                    = "1";
        signHereTab.anchorString             = "~?";
        signHereTab.anchorIgnoreIfNotPresent = "true";
        signHereTab.name = "PrimarySignerSignature";
        signer.tabs.signHereTabs.Add(signHereTab);


        signer.tabs.dateSignedTabs = new List <DateSignedTab>();
        DateSignedTab dateSignedTab = new DateSignedTab();

        dateSignedTab.documentId               = "1";
        dateSignedTab.tabId                    = "2";
        dateSignedTab.anchorString             = "~!";
        dateSignedTab.anchorIgnoreIfNotPresent = "true";
        dateSignedTab.name = "PrimarySignerDateSigned";
        signer.tabs.dateSignedTabs.Add(dateSignedTab);

        // Define a document
        Document document = new Document();

        document.documentId            = "1";
        document.name                  = "Sample Form";
        document.transformPdfFields    = "true";
        document.fileExtension         = "doc";
        document.htmlDefinition        = new HtmlDefinition();
        document.htmlDefinition.source = "document";
        document.htmlDefinition.displayAnchorPrefix = "";
        document.htmlDefinition.maxScreenWidth      = 0;
        document.htmlDefinition.removeEmptyTags     = "table,tr,p";
        document.htmlDefinition.headerLabel         = "<h1 style='color:#E20074;text-align:center;font-family:Tele-Grotesk, Arial, Helvetica;'>Examples of Smart Sections</h1><h2 style = 'text-align:center;font-family:Tele-Grotesk, Arial, Helvetica;'> Simply scroll down to review.</ h2><div style = 'margin-top:20px;margin-bottom:20px;border-bottom:solid 2px #dedede;'></ div >";

        // Define the display anchors
        document.htmlDefinition.displayAnchors = new List <DisplayAnchor>();
        DisplayAnchor displayAnchor = new DisplayAnchor();

        displayAnchor.startAnchor                           = "$Docu$printonlyS$";
        displayAnchor.endAnchor                             = "$Docu$printonlyE$";
        displayAnchor.removeEndAnchor                       = true;
        displayAnchor.removeStartAnchor                     = true;
        displayAnchor.caseSensitive                         = true;
        displayAnchor.displaySettings                       = new DisplaySettings();
        displayAnchor.displaySettings.display               = "print_only";
        displayAnchor.displaySettings.tableStyle            = "";
        displayAnchor.displaySettings.cellStyle             = "";
        displayAnchor.displaySettings.labelWhenOpened       = "";
        displayAnchor.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor.displaySettings.hideLabelWhenOpened   = true;
        displayAnchor.displaySettings.displayLabel          = "";
        document.htmlDefinition.displayAnchors.Add(displayAnchor);

        DisplayAnchor displayAnchor2 = new DisplayAnchor();

        displayAnchor2.startAnchor                           = "$tmo$tila$";
        displayAnchor2.endAnchor                             = "$tmo$tila$";
        displayAnchor2.removeEndAnchor                       = true;
        displayAnchor2.removeStartAnchor                     = true;
        displayAnchor2.caseSensitive                         = true;
        displayAnchor2.displaySettings                       = new DisplaySettings();
        displayAnchor2.displaySettings.display               = "responsive_table_single_column";
        displayAnchor2.displaySettings.tableStyle            = "margin-bottom:20px;";
        displayAnchor2.displaySettings.cellStyle             = "text-align:center;border:solid 3px #333;margin:5px;padding:5px;background-color:#eaeaea;~text-align:center;border:solid 3px #333;margin:5px;padding:5px;background-color:#eaeaea;~text-align:center;border:solid 1px #999;margin:5px;padding:5px;background-color:#eaeaea;";
        displayAnchor2.displaySettings.labelWhenOpened       = "";
        displayAnchor2.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor2.displaySettings.hideLabelWhenOpened   = true;
        displayAnchor2.displaySettings.displayLabel          = "";
        document.htmlDefinition.displayAnchors.Add(displayAnchor2);

        DisplayAnchor displayAnchor5 = new DisplayAnchor();

        displayAnchor5.startAnchor                           = "$Docu$collapsedS$";
        displayAnchor5.endAnchor                             = "$Docu$collapsedE$";
        displayAnchor5.removeEndAnchor                       = true;
        displayAnchor5.removeStartAnchor                     = true;
        displayAnchor5.caseSensitive                         = true;
        displayAnchor5.displaySettings                       = new DisplaySettings();
        displayAnchor5.displaySettings.display               = "collapsed";
        displayAnchor5.displaySettings.tableStyle            = "";
        displayAnchor5.displaySettings.cellStyle             = "";
        displayAnchor5.displaySettings.labelWhenOpened       = "";
        displayAnchor5.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor5.displaySettings.hideLabelWhenOpened   = false;
        displayAnchor5.displaySettings.displayLabel          = @"<div style='display:flex;flex-flow:row wrap;align-items:center;min-height:40px;border-top:solid 1px #dedede;font-size:24px;color:#9d2624'><div style = 'flex:none;width:90%;padding:5px;'>Declaration Of Independence</div><div style='width:10%;text-align:right;padding:5px;'><a><i class='icon icon-caret-large-down' style='color:#000;'></i></a></div></div>";
        document.htmlDefinition.displayAnchors.Add(displayAnchor5);

        DisplayAnchor displayAnchor3 = new DisplayAnchor();

        displayAnchor3.startAnchor                           = "$Docu$collapsibleS$";
        displayAnchor3.endAnchor                             = "$Docu$collapsibleE$";
        displayAnchor3.removeEndAnchor                       = true;
        displayAnchor3.removeStartAnchor                     = true;
        displayAnchor3.caseSensitive                         = true;
        displayAnchor3.displaySettings                       = new DisplaySettings();
        displayAnchor3.displaySettings.display               = "collapsible";
        displayAnchor3.displaySettings.tableStyle            = "";
        displayAnchor3.displaySettings.cellStyle             = "";
        displayAnchor3.displaySettings.labelWhenOpened       = "";
        displayAnchor3.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor3.displaySettings.hideLabelWhenOpened   = false;
        displayAnchor3.displaySettings.displayLabel          = @"<div style='display:flex;flex-flow:row wrap;align-items:center;min-height:40px;border-top:solid 1px #dedede;font-size:24px;color:#9d2624'><div style = 'flex:none;width:90%;padding:5px;'>Declaration Of Independence</div><div style='width:10%;text-align:right;padding:5px;'><a><i class='icon icon-caret-large-down' style='color:#000;'></i></a></div></div>";
        document.htmlDefinition.displayAnchors.Add(displayAnchor3);

        DisplayAnchor displayAnchor4 = new DisplayAnchor();

        displayAnchor4.startAnchor                           = "$Docu$inlineS$";
        displayAnchor4.endAnchor                             = "$Docu$inlineE$";
        displayAnchor4.removeEndAnchor                       = true;
        displayAnchor4.removeStartAnchor                     = true;
        displayAnchor4.caseSensitive                         = true;
        displayAnchor4.displaySettings                       = new DisplaySettings();
        displayAnchor4.displaySettings.display               = "inline";
        displayAnchor4.displaySettings.labelWhenOpened       = "";
        displayAnchor4.displaySettings.scrollToTopWhenOpened = true;
        displayAnchor4.displaySettings.hideLabelWhenOpened   = true;
        displayAnchor4.displaySettings.displayLabel          = "Highlight the following section";
        displayAnchor4.displaySettings.inlineOuterStyle      = "background-color:#ff0; padding:10px;";
        document.htmlDefinition.displayAnchors.Add(displayAnchor4);

        // Define an inline template
        InlineTemplate inline1 = new InlineTemplate();

        inline1.sequence           = "2";
        inline1.recipients         = new Recipients();
        inline1.recipients.signers = new List <Signer>();
        inline1.recipients.signers.Add(signer);


        // Add the inline template to a CompositeTemplate
        CompositeTemplate compositeTemplate1 = new CompositeTemplate();

        compositeTemplate1.inlineTemplates = new List <InlineTemplate>();
        compositeTemplate1.inlineTemplates.Add(inline1);
        compositeTemplate1.document = document;

        // Add compositeTemplate to the envelope
        createEnvelopeRequest.compositeTemplates = new List <CompositeTemplate>();
        createEnvelopeRequest.compositeTemplates.Add(compositeTemplate1);
        createEnvelopeRequest.brandId = ConfigurationManager.AppSettings["MomentumBrandID"];


        string output = JsonConvert.SerializeObject(createEnvelopeRequest);

        // Specify a unique boundary string that doesn't appear in the json or document bytes.
        string Boundary = "MY_BOUNDARY";

        // Set the URI
        HttpWebRequest request = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/vdev/accounts/" + ConfigurationManager.AppSettings["API.AccountId"] + "/envelopes") as HttpWebRequest;

        // Set the method
        request.Method = "POST";

        // Set the authentication header
        request.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

        // Set the overall request content type aand boundary string
        request.ContentType = "multipart/form-data; boundary=" + Boundary;
        request.Accept      = "application/json";

        // Start forming the body of the request
        Stream reqStream = request.GetRequestStream();

        // write boundary marker between parts
        WriteStream(reqStream, "\n--" + Boundary + "\n");

        // write out the json envelope definition part
        WriteStream(reqStream, "Content-Type: application/json\n");
        WriteStream(reqStream, "Content-Disposition: form-data\n");
        WriteStream(reqStream, "\n"); // requires an empty line between the header and the json body
        WriteStream(reqStream, output);

        // write out the form bytes for the first form
        WriteStream(reqStream, "\n--" + Boundary + "\n");
        WriteStream(reqStream, "Content-Type: application/pdf\n");
        WriteStream(reqStream, "Content-Disposition: file; filename=\"Sample_Form\"; documentId=1\n");
        WriteStream(reqStream, "\n");
        if (File.Exists(Server.MapPath("~/App_Data/kitchensink.pdf")))
        {
            // Read the file contents and write them to the request stream
            byte[] buf = new byte[4096];
            int    len;
            // read contents of document into the request stream
            FileStream fileStream = File.OpenRead(Server.MapPath("~/App_Data/kitchensink.pdf"));
            while ((len = fileStream.Read(buf, 0, 4096)) > 0)
            {
                reqStream.Write(buf, 0, len);
            }
            fileStream.Close();
        }


        // wrte the end boundary marker - ensure that it is on its own line
        WriteStream(reqStream, "\n--" + Boundary + "--");
        WriteStream(reqStream, "\n");
        try
        {
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.Created)
            {
                byte[] responseBytes = new byte[response.ContentLength];
                using (var reader = new System.IO.BinaryReader(response.GetResponseStream()))
                {
                    reader.Read(responseBytes, 0, responseBytes.Length);
                }
                string responseText = Encoding.UTF8.GetString(responseBytes);
                CreateEnvelopeResponse createEnvelopeResponse = new CreateEnvelopeResponse();

                createEnvelopeResponse = JsonConvert.DeserializeObject <CreateEnvelopeResponse>(responseText);
                if (createEnvelopeResponse.status.Equals("sent"))
                {
                    // Now that we have created the envelope, get the recipient token for the first signer
                    String url = Request.Url.AbsoluteUri;
                    RecipientViewRequest recipientViewRequest = new RecipientViewRequest();
                    recipientViewRequest.authenticationMethod = "email";
                    recipientViewRequest.clientUserId         = signer.clientUserId;
                    recipientViewRequest.email     = email.Value;
                    recipientViewRequest.returnUrl = url.Substring(0, url.LastIndexOf("/")) + "/ConfirmationScreen.aspx";
                    recipientViewRequest.userName  = firstname.Value + " " + lastname.Value;

                    HttpWebRequest request2 = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/v2/accounts/" + ConfigurationManager.AppSettings["API.TemplatesAccountID"] + "/envelopes/" + createEnvelopeResponse.envelopeId + "/views/recipient") as HttpWebRequest;
                    request2.Method = "POST";

                    // Set the authenticationheader
                    request2.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

                    request2.Accept      = "application/json";
                    request2.ContentType = "application/json";

                    Stream reqStream2 = request2.GetRequestStream();

                    WriteStream(reqStream2, JsonConvert.SerializeObject(recipientViewRequest));
                    HttpWebResponse response2 = request2.GetResponse() as HttpWebResponse;

                    responseBytes = new byte[response2.ContentLength];
                    using (var reader = new System.IO.BinaryReader(response2.GetResponseStream()))
                    {
                        reader.Read(responseBytes, 0, responseBytes.Length);
                    }
                    string response2Text = Encoding.UTF8.GetString(responseBytes);

                    RecipientViewResponse recipientViewResponse = new RecipientViewResponse();
                    recipientViewResponse = JsonConvert.DeserializeObject <RecipientViewResponse>(response2Text);
                    Response.Redirect(recipientViewResponse.url);
                }
            }
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                using (var reader = new System.IO.StreamReader(ex.Response.GetResponseStream(), UTF8Encoding.UTF8))
                {
                    string       errorMess = reader.ReadToEnd();
                    log4net.ILog logger    = log4net.LogManager.GetLogger(typeof(KitchenSink));
                    logger.Info("\n----------------------------------------\n");
                    logger.Error("DocuSign Error: " + errorMess);
                    logger.Error(ex.StackTrace);
                    Response.Write(ex.Message);
                }
            }
            else
            {
                log4net.ILog logger = log4net.LogManager.GetLogger(typeof(KitchenSink));
                logger.Info("\n----------------------------------------\n");
                logger.Error("WebRequest Error: " + ex.Message);
                logger.Error(ex.StackTrace);
                Response.Write(ex.Message);
            }
        }
    }
    protected void createEnvelope()
    {
        // Set up the envelope
        CreateEnvelopeRequest createEnvelopeRequest = new CreateEnvelopeRequest();

        createEnvelopeRequest.emailSubject = "eNotary Example";
        createEnvelopeRequest.status       = "sent";

        //Define inperson signers
        InPersonSigner inPersonSigner = new InPersonSigner();

        //       inPersonSigner.hostEmail = "*****@*****.**";
        inPersonSigner.hostEmail           = email.Value;
        inPersonSigner.hostName            = firstname.Value + " " + lastname.Value;
        inPersonSigner.recipientId         = "3";
        inPersonSigner.routingOrder        = "3";
        inPersonSigner.inPersonSigningType = "notary";

        NotaryHost notaryHost = new NotaryHost();

        notaryHost.recipientId = 4;
        notaryHost.email       = notaryEmail.Value;
        notaryHost.name        = notaryFirstname.Value + " " + notaryLastname.Value;

        // Add tab for the recipient
        inPersonSigner.tabs = new Tabs();
        inPersonSigner.tabs.signHereTabs = new List <SignHereTab>();
        SignHereTab signHereTab = new SignHereTab();

        signHereTab.documentId = "1";
        signHereTab.pageNumber = "1";
        signHereTab.tabId      = "1";
        signHereTab.xPosition  = "110";
        signHereTab.yPosition  = "210";
        signHereTab.name       = "sigTab";
        inPersonSigner.tabs.signHereTabs.Add(signHereTab);

        inPersonSigner.tabs.dateSignedTabs = new List <DateSignedTab>();
        DateSignedTab dateSignedTab = new DateSignedTab();

        dateSignedTab.documentId = "1";
        dateSignedTab.pageNumber = "1";
        dateSignedTab.tabId      = "2";
        dateSignedTab.xPosition  = "425";
        dateSignedTab.yPosition  = "260";
        dateSignedTab.name       = "dateSignedTab";
        inPersonSigner.tabs.dateSignedTabs.Add(dateSignedTab);

        inPersonSigner.tabs.fullNameTabs = new List <FullNameTab>();
        FullNameTab fullNameTab = new FullNameTab();

        fullNameTab.documentId = "1";
        fullNameTab.pageNumber = "1";
        fullNameTab.tabId      = "3";
        fullNameTab.xPosition  = "90";
        fullNameTab.yPosition  = "150";
        fullNameTab.name       = "fullNameTab";
        inPersonSigner.tabs.fullNameTabs.Add(fullNameTab);

        inPersonSigner.notaryHost = notaryHost;


        // Define a document
        Document document = new Document();

        document.documentId         = "1";
        document.name               = "Sample Form";
        document.transformPdfFields = "true";
        //document.display = "modal";

        // Define an inline template
        InlineTemplate inline1 = new InlineTemplate();

        inline1.sequence   = "2";
        inline1.recipients = new Recipients();
        //        inline1.recipients.signers = new List<Signer>();
        //        inline1.recipients.signers.Add(signer);
        inline1.recipients.inPersonSigners = new List <InPersonSigner>();
        inline1.recipients.inPersonSigners.Add(inPersonSigner);

        //       inline1.documents = new List<Document>();
        //       inline1.documents.Add(document);

        ServerTemplate serverTemplate1 = new ServerTemplate();

        serverTemplate1.sequence   = "1";
        serverTemplate1.templateId = "d7a2c6d9-3b20-4086-a408-ada85efc00fd";

        CompositeTemplate compositeTemplate1 = new CompositeTemplate();

        compositeTemplate1.inlineTemplates = new List <InlineTemplate>();
        compositeTemplate1.inlineTemplates.Add(inline1);
        //        compositeTemplate1.serverTemplates = new List<ServerTemplate>();
        //        compositeTemplate1.serverTemplates.Add(serverTemplate1);
        compositeTemplate1.document                    = document;
        compositeTemplate1.document                    = new Document();
        compositeTemplate1.document.documentId         = "1";
        compositeTemplate1.document.name               = "Affidavit";
        compositeTemplate1.document.transformPdfFields = "true";
        //compositeTemplate1.document.display = "modal";

        createEnvelopeRequest.compositeTemplates = new List <CompositeTemplate>();
        createEnvelopeRequest.compositeTemplates.Add(compositeTemplate1);


        string output = JsonConvert.SerializeObject(createEnvelopeRequest);

        accountId.Value = ConfigurationManager.AppSettings["API.NotaryAccountID"];

        // Specify a unique boundary string that doesn't appear in the json or document bytes.
        string Boundary = "MY_BOUNDARY";

        // Set the URI
        HttpWebRequest request = HttpWebRequest.Create(ConfigurationManager.AppSettings["DocuSignServer"] + "/restapi/v2/accounts/" + accountId.Value + "/envelopes") as HttpWebRequest;

        // Set the method
        request.Method = "POST";

        // Set the authentication header
        request.Headers["X-DocuSign-Authentication"] = GetSecurityHeader();

        // Set the overall request content type aand boundary string
        request.ContentType = "multipart/form-data; boundary=" + Boundary;
        request.Accept      = "application/json";

        // Start forming the body of the request
        Stream reqStream = request.GetRequestStream();

        // write boundary marker between parts
        WriteStream(reqStream, "\n--" + Boundary + "\n");

        // write out the json envelope definition part
        WriteStream(reqStream, "Content-Type: application/json\n");
        WriteStream(reqStream, "Content-Disposition: form-data\n");
        WriteStream(reqStream, "\n"); // requires an empty line between the header and the json body
        WriteStream(reqStream, output);

        // write out the form bytes for the first form
        WriteStream(reqStream, "\n--" + Boundary + "\n");
        WriteStream(reqStream, "Content-Type: application/pdf\n");
        WriteStream(reqStream, "Content-Disposition: file; filename=\"Sample_Form\"; documentId=1\n");
        WriteStream(reqStream, "\n");
        String filename = "Docusign_Affidavit.pdf";

        if (File.Exists(Server.MapPath("~/App_Data/" + filename)))
        {
            // Read the file contents and write them to the request stream
            byte[] buf = new byte[4096];
            int    len;
            // read contents of document into the request stream
            FileStream fileStream = File.OpenRead(Server.MapPath("~/App_Data/" + filename));
            while ((len = fileStream.Read(buf, 0, 4096)) > 0)
            {
                reqStream.Write(buf, 0, len);
            }
            fileStream.Close();
        }


        // wrte the end boundary marker - ensure that it is on its own line
        WriteStream(reqStream, "\n--" + Boundary + "--");
        WriteStream(reqStream, "\n");

        try
        {
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.Created)
            {
                byte[] responseBytes = new byte[response.ContentLength];
                using (var reader = new System.IO.BinaryReader(response.GetResponseStream()))
                {
                    reader.Read(responseBytes, 0, responseBytes.Length);
                }
                string responseText = Encoding.UTF8.GetString(responseBytes);
                CreateEnvelopeResponse createEnvelopeResponse = new CreateEnvelopeResponse();

                createEnvelopeResponse = JsonConvert.DeserializeObject <CreateEnvelopeResponse>(responseText);
                if (createEnvelopeResponse.status.Equals("sent"))
                {
                    Response.Redirect("ConfirmationPage.aspx");
                }
            }
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                using (var reader = new System.IO.StreamReader(ex.Response.GetResponseStream(), UTF8Encoding.UTF8))
                {
                    string       errorMess = reader.ReadToEnd();
                    log4net.ILog logger    = log4net.LogManager.GetLogger(typeof(demos_eNotary));
                    logger.Info("\n----------------------------------------\n");
                    logger.Error("DocuSign Error: " + errorMess);
                    logger.Error(ex.StackTrace);
                    Response.Write(ex.Message);
                }
            }
            else
            {
                log4net.ILog logger = log4net.LogManager.GetLogger(typeof(demos_eNotary));
                logger.Info("\n----------------------------------------\n");
                logger.Error("WebRequest Error: " + ex.Message);
                logger.Error(ex.StackTrace);
                Response.Write(ex.Message);
            }
        }
    }