// The next two functions simply create the html for the status tables. You can safely ignore these.
        protected void CreateStatusTable(DocuSignAPI.FilteredEnvelopeStatuses statuses)
        {
            foreach (DocuSignAPI.EnvelopeStatus status in statuses.EnvelopeStatuses)
            {
                var containerDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                var info = new System.Web.UI.HtmlControls.HtmlGenericControl("p")
                    {
                        InnerHtml =
                            "<a href=\"javascript:toggle('" + status.EnvelopeID + "_Detail" +
                            "');\"><img src=\"images/plus.png\"></a> " + status.Subject + " (" + status.Status.ToString() +
                            ") - " + status.EnvelopeID
                    };
                containerDiv.Controls.Add(info);
                System.Web.UI.HtmlControls.HtmlGenericControl envelopeDetail = CreateEnvelopeTable(status);
                envelopeDetail.Attributes[Keys.Class] = "detail";
                envelopeDetail.Attributes[Keys.Id] = status.EnvelopeID + "_Detail";

                containerDiv.Controls.Add(envelopeDetail);
                var tr = new System.Web.UI.HtmlControls.HtmlTableRow();
                var tc = new System.Web.UI.HtmlControls.HtmlTableCell();
                tc.Controls.Add(containerDiv);
                tr.Cells.Add(tc);
                statusTable.Rows.Add(tr);
            }
        }
        protected System.Web.UI.HtmlControls.HtmlGenericControl CreateEnvelopeTable(DocuSignAPI.EnvelopeStatus status)
        {
            System.Web.UI.HtmlControls.HtmlTable envelopeTable = new System.Web.UI.HtmlControls.HtmlTable();
            System.Web.UI.HtmlControls.HtmlGenericControl envelopeDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");

            int recipIndex = 0;

            foreach (DocuSignAPI.RecipientStatus recipient in status.RecipientStatuses)
            {
                System.Web.UI.HtmlControls.HtmlGenericControl info = new System.Web.UI.HtmlControls.HtmlGenericControl("p");

                String recipId = "Recipient_Detail_" + status.EnvelopeID + "_" + recipient.RoutingOrder + "_" + recipient.UserName + "_" + recipient.Email + "_" + recipIndex++;

                info.InnerHtml = "<a href=\"javascript:toggle('" + recipId + "');\"><img src=\"images/plus.png\"></a> Recipient - " +
                    recipient.UserName + ": " + recipient.Status.ToString();
                if (recipient.Status != DocuSignAPI.RecipientStatusCode.Completed && recipient.ClientUserId != null)
                {
                    info.InnerHtml += " <input type=\"submit\" id=\"" + status.EnvelopeID + "\" value=\"Start Signing\" name=\"DocEnvelope+" + status.EnvelopeID + "&Email+" + recipient.Email + "&UserName+" +
                        recipient.UserName + "&CID+" + recipient.ClientUserId + "\">";
                }

                if (recipient.TabStatuses != null)
                {
                    System.Web.UI.HtmlControls.HtmlGenericControl tabs = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                    foreach (DocuSignAPI.TabStatus tab in recipient.TabStatuses)
                    {
                        System.Web.UI.HtmlControls.HtmlGenericControl t = new System.Web.UI.HtmlControls.HtmlGenericControl("p");
                        t.InnerHtml = tab.TabName + ": " + tab.TabValue;
                        tabs.Controls.Add(t);
                    }
                    tabs.Attributes["id"] = recipId;
                    tabs.Attributes["class"] = "detail";
                    info.Controls.Add(tabs);
                }
                envelopeDiv.Controls.Add(info);
            }

            System.Web.UI.HtmlControls.HtmlGenericControl documents = new System.Web.UI.HtmlControls.HtmlGenericControl("p");
            documents.InnerHtml = "<a href=\"javascript:toggle('" + status.EnvelopeID + "_Detail_Documents" + "');\"><img src=\"images/plus.png\"></a> Documents";
            if (status.Status == DocuSignAPI.EnvelopeStatusCode.Completed)
            {
                documents.InnerHtml += " <input type=\"submit\" id=\"" + status.EnvelopeID + "\" value=\"Download\" name=\"" + status.EnvelopeID + "\";>";
            }
            envelopeDiv.Controls.Add(documents);
            if (status.DocumentStatuses != null)
            {
                System.Web.UI.HtmlControls.HtmlGenericControl documentDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
                foreach (DocuSignAPI.DocumentStatus document in status.DocumentStatuses)
                {
                    System.Web.UI.HtmlControls.HtmlGenericControl info = new System.Web.UI.HtmlControls.HtmlGenericControl("p");
                    info.InnerHtml = document.Name;
                    documentDiv.Controls.Add(info);
                }
                documentDiv.Attributes["id"] = status.EnvelopeID + "_Detail_Documents";
                documentDiv.Attributes["class"] = "detail";
                envelopeDiv.Controls.Add(documentDiv);
            }
            return envelopeDiv;
        }
        // Add the recipients to the UI
        protected void AddRecipients(DocuSignAPI.Recipient[] recipients)
        {
            int i = 1;
            foreach (DocuSignAPI.Recipient recipient in recipients)
            {
                System.Web.UI.HtmlControls.HtmlTableRow row = new System.Web.UI.HtmlControls.HtmlTableRow();
                System.Web.UI.HtmlControls.HtmlTableCell roleCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                System.Web.UI.HtmlControls.HtmlTableCell nameCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                System.Web.UI.HtmlControls.HtmlTableCell emailCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                System.Web.UI.HtmlControls.HtmlTableCell securityCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                System.Web.UI.HtmlControls.HtmlTableCell inviteCell = new System.Web.UI.HtmlControls.HtmlTableCell();

                roleCell.InnerHtml = "<input id=\"RecipientRole\" type=\"text\" readonly=\"true\" name=\"RecipientRole" + i.ToString() + "\" value=\"" + recipient.RoleName + "\"/>";

                nameCell.InnerHtml = "<input id=\"RecipientName\" type=\"text\" name=\"RecipientName" + i.ToString() + "\" value=\"" + recipient.UserName + "\"/>";

                emailCell.InnerHtml = "<input id=\"RecipientEmail\" type=\"text\" name=\"RecipientEmail" + i.ToString() + "\" value=\"" + recipient.Email + "\"/>";

                string security = "";
                if (!String.IsNullOrEmpty(recipient.AccessCode))
                {
                    security = "Access code: " + recipient.AccessCode;
                }
                else if (recipient.PhoneAuthentication != null)
                {
                    security = "Phone Authentication";
                }
                else if (recipient.RequireIDLookup)
                {
                    security = "ID Check";
                }
                else
                {
                    security = "None";
                }

                securityCell.InnerHtml = "<input id=\"RecipientSecurity\" type=\"text\" readonly=\"true\" name=\"RecipientSecurity" + i.ToString() + "\" value=\"" + security + "\"/>";

                inviteCell.InnerHtml = "<ul class=\"switcher\" name=\"RecipientInvite" + i.ToString() + "\" ><li class=\"active\"><a href=\"#\" title=\"On\">ON</a></li><li><a href=\"#\" title=\"OFF\">OFF</a></li><input id=\"RecipientInviteToggle" + i.ToString() + "\" name=\"RecipientInviteToggle" + i.ToString() + "\" value=\"RecipientInviteToggle" + i.ToString() + "\" type=\"checkbox\" checked=\"\" style=\"display: none\"></ul>";
                //<ul class="switcher" id="RecipientInvite1">
                //    <li id="RecipientInviteon1" class="active"><a href="#" title="On">ON</a></li>
                //    <li id="RecipientInviteoff1"><a href="#" title="OFF">OFF</a></li>
                //    <input id="RecipientInviteToggle1" name="RecipientInviteToggle1" value="RecipientInviteToggle1" type="checkbox" checked="" style="display: none">
                //</ul>
                inviteCell.Attributes["ID"] = String.Format("RecipientInvite{0}", recipient.ID);
                inviteCell.Attributes["name"] = String.Format("RecipientInvite{0}", recipient.ID);

                row.Cells.Add(roleCell);
                row.Cells.Add(nameCell);
                row.Cells.Add(emailCell);
                row.Cells.Add(securityCell);
                row.Cells.Add(inviteCell);
                RecipientTable.Rows.Add(row);
                i++;
            }
        }
        protected void SendNow(DocuSignAPI.Envelope envelope)
        {
            DocuSignAPI.APIServiceSoapClient client = CreateAPIProxy();
            try
            {
                // Create and send the envelope in one step
                DocuSignAPI.EnvelopeStatus status = client.CreateAndSendEnvelope(envelope);

                // If we succeeded, go to the status
                if (status.SentSpecified)
                {
                    base.AddEnvelopeID(status.EnvelopeID);
                    Response.Redirect("GetStatusAndDocs.aspx", false);
                }

            }
            catch (Exception ex)
            {
                base.GoToErrorPage(ex.Message);
            }
        }
        protected void EmbedSending(DocuSignAPI.Envelope envelope)
        {
            DocuSignAPI.APIServiceSoapClient client = CreateAPIProxy();
            try
            {
                // Create the envelope (but don't send it!)
                DocuSignAPI.EnvelopeStatus status = client.CreateEnvelope(envelope);
                base.AddEnvelopeID(status.EnvelopeID);

                // If it created successfully, redirect to the embedded host
                if (status.Status == DocuSignAPI.EnvelopeStatusCode.Created)
                {
                    string navURL = String.Format("{0}?envelopeID={1}&accountID={2}&source=Document", "EmbeddedHost.aspx", status.EnvelopeID,
                        envelope.AccountId);
                    Response.Redirect(navURL, false);
                }
            }
            catch (Exception ex)
            {
                base.GoToErrorPage(ex.Message);
            }
        }
        private DocuSignAPI.Envelope ProcessOptions(DocuSignAPI.Envelope envelope)
        {
            if (Request.Form["markup"] != null)
            {
                // Allow recipients to mark up the envelope
                envelope.AllowMarkup = true;
                envelope.AllowMarkupSpecified = true;
            }

            if (Request.Form["enablepaper"] != null)
            {
                // Allow recipients to sign on paper (called wet signing)
                envelope.EnableWetSign = true;
                envelope.EnableWetSignSpecified = true;
            }

            if (!String.IsNullOrEmpty(Request.Form["reminders"]))
            {
                // Set any reminders
                DateTime remind = Convert.ToDateTime(Request.Form["reminders"]);
                int difference = (remind - DateTime.Today).Days;

                if (envelope.Notification == null)
                {
                    envelope.Notification = new DocuSignAPI.Notification();
                }
                envelope.Notification.Reminders = new DocuSignAPI.Reminders();
                envelope.Notification.Reminders.ReminderEnabled = true;
                envelope.Notification.Reminders.ReminderDelay = difference.ToString();
                envelope.Notification.Reminders.ReminderFrequency = "2";
            }

            if (!String.IsNullOrEmpty(Request.Form["expiration"]))
            {
                // Set any expirations
                DateTime expire = Convert.ToDateTime(Request.Form["expiration"]);
                int difference = (expire - DateTime.Today).Days;

                if (envelope.Notification == null)
                {
                    envelope.Notification = new DocuSignAPI.Notification();
                }

                envelope.Notification.Expirations = new DocuSignAPI.Expirations();
                envelope.Notification.Expirations.ExpireEnabled = true;
                envelope.Notification.Expirations.ExpireAfter = difference.ToString();
                envelope.Notification.Expirations.ExpireWarn = (difference - 2).ToString();
            }

            return envelope;
        }
        protected void SendNow(DocuSignAPI.TemplateReference templateReference, DocuSignAPI.EnvelopeInformation envelopeInfo,
            DocuSignAPI.Recipient[] recipients)
        {
            DocuSignAPI.APIServiceSoapClient client = CreateAPIProxy();
            try
            {
                // Create the envelope using the specified template, and send it (note the last parameter)
                DocuSignAPI.EnvelopeStatus status = client.CreateEnvelopeFromTemplates(new DocuSignAPI.TemplateReference[] { templateReference },
                recipients, envelopeInfo, true);

                base.AddEnvelopeID(status.EnvelopeID);
                if (status.SentSpecified)
                {
                    Response.Redirect("GetStatusAndDocs.aspx", false);
                }

            }
            catch (Exception ex)
            {
                base.GoToErrorPage(ex.Message);
            }
        }
        protected void EmbedSending(DocuSignAPI.TemplateReference templateReference, DocuSignAPI.EnvelopeInformation envelopeInfo,
            DocuSignAPI.Recipient[] recipients)
        {
            DocuSignAPI.APIServiceSoapClient client = CreateAPIProxy();
            try
            {
                // Create the envelope using the specified template, but don't send it (note the last parameter)
                DocuSignAPI.EnvelopeStatus status = client.CreateEnvelopeFromTemplates(new DocuSignAPI.TemplateReference[] { templateReference },
                recipients, envelopeInfo, false);
                base.AddEnvelopeID(status.EnvelopeID);

                // If it created successfully, redirect to the embedded host
                if (status.Status == DocuSignAPI.EnvelopeStatusCode.Created)
                {
                    string navURL = String.Format("{0}?envelopeID={1}&accountID={2}&source=Template", "EmbeddedHost.aspx", status.EnvelopeID,
                        envelopeInfo.AccountId);

                    Response.Redirect(navURL, false);
                }
            }
            catch (Exception ex)
            {
                base.GoToErrorPage(ex.Message);
            }
        }
        protected DocuSignAPI.TemplateReferenceRoleAssignment[] CreateFinalRoleAssignments(DocuSignAPI.Recipient[] recipients)
        {
            List<DocuSignAPI.TemplateReferenceRoleAssignment> runningList = new List<DocuSignAPI.TemplateReferenceRoleAssignment>();

            // Match up all the recipients to the roles on the template
            foreach (DocuSignAPI.Recipient recipient in recipients)
            {
                DocuSignAPI.TemplateReferenceRoleAssignment assign = new DocuSignAPI.TemplateReferenceRoleAssignment();
                assign.RecipientID = recipient.ID;
                assign.RoleName = recipient.RoleName;

                runningList.Add(assign);
            }
            return runningList.ToArray();
        }
        protected void SignSecond(DocuSignAPI.EnvelopeStatus status)
        {
            // Create the assertion using the current time, password and demo information
            DocuSignAPI.RequestRecipientTokenAuthenticationAssertion assertion = new DocuSignAPI.RequestRecipientTokenAuthenticationAssertion();
            assertion.AssertionID = new Guid().ToString();
            assertion.AuthenticationInstant = DateTime.Now;
            assertion.AuthenticationMethod = DocuSignAPI.RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.Password;
            assertion.SecurityDomain = "DocuSignSample";

            DocuSignAPI.RecipientStatus recipient = status.RecipientStatuses[1];

            // Construct the URLs to which the iframe will redirect upon every event
            DocuSignAPI.RequestRecipientTokenClientURLs urls = new DocuSignAPI.RequestRecipientTokenClientURLs();

            // TODO: replace urlBase with your own test url
            String urlBase = Request.Url.AbsoluteUri.Replace("EmbedDocuSign.aspx", "pop.html") + "?source=embed";
            urls.OnSigningComplete = urlBase + "&event=SignComplete2";
            urls.OnViewingComplete = urlBase + "&event=ViewComplete2";
            urls.OnCancel = urlBase + "&event=Cancel2";
            urls.OnDecline = urlBase + "&event=Decline2";
            urls.OnSessionTimeout = urlBase + "&event=Timeout2";
            urls.OnTTLExpired = urlBase + "&event=TTLExpired2";
            urls.OnIdCheckFailed = urlBase + "&event=IDCheck2";
            urls.OnAccessCodeFailed = urlBase + "&event=AccessCode2";
            urls.OnException = urlBase + "&event=Exception2";

            DocuSignAPI.APIServiceSoapClient client = CreateAPIProxy();
            String token = null;
            try
            {
                // Request the token for a specific recipient
                token = client.RequestRecipientToken(status.EnvelopeID, recipient.ClientUserId,
                                                                recipient.UserName, recipient.Email, assertion, urls);
            }
            catch (Exception ex)
            {
                base.GoToErrorPage(ex.Message);
            }

            // Set the signer message
            signerMessage = "The first signer has completed the Envelope. Now the second signer will be asked to fill out details in the Envelope.";
            messagediv.Visible = true;

            // Set the source of the iframe to the token
            hostiframe.Visible = true;
            hostiframe.Attributes["src"] = token;
        }
        // Add the recipients to the UI
        protected void AddRecipients(DocuSignAPI.Recipient[] recipients)
        {
            int i = 1;
            foreach (DocuSignAPI.Recipient recipient in recipients)
            {
                var row = new System.Web.UI.HtmlControls.HtmlTableRow();
                var roleCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                var nameCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                var emailCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                var securityCell = new System.Web.UI.HtmlControls.HtmlTableCell();
                var inviteCell = new System.Web.UI.HtmlControls.HtmlTableCell();

                roleCell.InnerHtml = String.Format(
                    "<input id=\"{0}\" type=\"text\" readonly=\"true\" name=\"{0}{1}\" value=\"{2}\"/>", 
                    Keys.RecipientRole, i.ToString(), recipient.RoleName);

                nameCell.InnerHtml = String.Format(
                    "<input id=\"{0}\" type=\"text\" name=\"{0}{1}\" value=\"{2}\"/>", 
                    Keys.RecipientName, i.ToString(), recipient.UserName);

                emailCell.InnerHtml = String.Format(
                    "<input id=\"{0}\" type=\"text\" name=\"{0}{1}\" value=\"{2}\"/>",
                    Keys.RecipientEmail, i.ToString(), recipient.Email);

                string security = String.Empty;
                if (!String.IsNullOrEmpty(recipient.AccessCode))
                {
                    security = "Access code: " + recipient.AccessCode;
                }
                else if (null != recipient.PhoneAuthentication)
                {
                    security = "Phone Authentication";
                }
                else if (recipient.RequireIDLookup)
                {
                    security = "ID Check";
                }
                else
                {
                    security = "None";
                }

                securityCell.InnerHtml = String.Format(
                    "<input id=\"{0}\" type=\"text\" readonly=\"true\" name=\"{0}{1}\" value=\"{2}\"/>",
                    Keys.RecipientSecurity, i.ToString(), security);

                inviteCell.InnerHtml = String.Format(
                    "<ul class=\"switcher\" name=\"{0}{1}\" ><li class=\"active\"><a href=\"#\" title=\"On\">ON</a></li><li><a href=\"#\" title=\"OFF\">OFF</a></li><input id=\"RecipientInviteToggle{1}\" name=\"RecipientInviteToggle{1}\" value=\"RecipientInviteToggle{1}\" type=\"checkbox\" checked=\"\" style=\"display: none\"></ul>",
                    Keys.RecipientInvite, i.ToString());
                //<ul class="switcher" id="RecipientInvite1">
                //    <li id="RecipientInviteon1" class="active"><a href="#" title="On">ON</a></li>
                //    <li id="RecipientInviteoff1"><a href="#" title="OFF">OFF</a></li>
                //    <input id="RecipientInviteToggle1" name="RecipientInviteToggle1" value="RecipientInviteToggle1" type="checkbox" checked="" style="display: none">
                //</ul>
                inviteCell.Attributes[Keys.Id] = String.Format("{0}{1}", Keys.RecipientInvite,recipient.ID);
                inviteCell.Attributes[Keys.Name] = String.Format("{0}{1}", Keys.RecipientInvite,recipient.ID);

                row.Cells.Add(roleCell);
                row.Cells.Add(nameCell);
                row.Cells.Add(emailCell);
                row.Cells.Add(securityCell);
                row.Cells.Add(inviteCell);
                RecipientTable.Rows.Add(row);
                i++;
            }
        }
 protected DocuSignAPI.TemplateReferenceRoleAssignment[] CreateFinalRoleAssignments(DocuSignAPI.Recipient[] recipients)
 {
     // Match up all the recipients to the roles on the template
     return recipients.Select(recipient => new DocuSignAPI.TemplateReferenceRoleAssignment
         {
             RecipientID = recipient.ID, RoleName = recipient.RoleName
         }).ToArray();
 }