Пример #1
0
        public void CreateReport(string input, string outputDirectory)
        {
            var attributes = File.GetAttributes(input);
            IEnumerable <FileInfo> filePathList;

            if ((FileAttributes.Directory & attributes) == FileAttributes.Directory)
            {
                filePathList = new DirectoryInfo(input).GetFiles("*.xml", SearchOption.AllDirectories)
                               .OrderByDescending(f => f.CreationTime);
            }
            else
            {
                if (File.Exists(input))
                {
                    filePathList = new[] { new FileInfo(input) };
                }
                else
                {
                    filePathList = new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles(input);
                }
            }

            InitializeRazor();

            var compositeTemplate = new CompositeTemplate();

            foreach (var filePath in filePathList)
            {
                var testRunner = GetTestRunner(filePath.FullName);

                if (!(testRunner.Equals(TestRunner.Unknown)))
                {
                    var parser = (IParser)Assembly.GetExecutingAssembly().CreateInstance(Ns + "." + Enum.GetName(typeof(TestRunner), testRunner));
                    var report = parser.Parse(filePath.FullName);

                    compositeTemplate.AddReport(report);
                }
            }
            if (compositeTemplate.ReportList == null)
            {
                Logger.GetLogger().Fatal("No reports added - invalid files?");
                return;
            }
            if (compositeTemplate.ReportList.Count > 1)
            {
                compositeTemplate.SideNavLinks = compositeTemplate.SideNavLinks.Insert(0, Templates.SideNav.IndexLink);

                var summary = Engine.Razor.RunCompile(Templates.TemplateManager.GetSummaryTemplate(), "summary", typeof(Model.CompositeTemplate), compositeTemplate, null);
                File.WriteAllText(Path.Combine(outputDirectory, "Index.html"), summary);
            }

            foreach (var report in compositeTemplate.ReportList)
            {
                report.SideNavLinks = compositeTemplate.SideNavLinks;

                var html = Engine.Razor.RunCompile(Templates.TemplateManager.GetFileTemplate(), "report", typeof(Model.Report), report, null);
                File.WriteAllText(Path.Combine(outputDirectory, report.FileName + ".html"), html);
            }
        }
Пример #2
0
        public void CreateReport(string input, string outputDirectory)
        {
            var attributes = File.GetAttributes(input);
            IEnumerable <FileInfo> filePathList;

            if ((FileAttributes.Directory & attributes) == FileAttributes.Directory)
            {
                filePathList = new DirectoryInfo(input).GetFiles("*.xml", SearchOption.AllDirectories)
                               .OrderBy(f => f.CreationTime);
            }
            else
            {
                filePathList = new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles(input);
            }

            InitializeRazor();

            var compositeTemplate = new CompositeTemplate();

            foreach (var filePath in filePathList)
            {
                var testRunner = GetTestRunner(filePath.FullName);

                if (!(testRunner.Equals(TestRunner.Unknown)))
                {
                    IParser parser = (IParser)Assembly.GetExecutingAssembly().CreateInstance(_ns + "." + Enum.GetName(typeof(TestRunner), testRunner));
                    var     report = parser.Parse(filePath.FullName);

                    compositeTemplate.AddReport(report);
                }
            }


            compositeTemplate.SideNavLinks = compositeTemplate.SideNavLinks.Insert(0, Templates.SideNav.TimeAnalytics);
            compositeTemplate.SideNavLinks = compositeTemplate.SideNavLinks.Insert(0, Templates.SideNav.IndexLink);
            compositeTemplate.SideNavLinks = compositeTemplate.SideNavLinks.Insert(0, Templates.SideNav.SummaryLink);

            string index = Engine.Razor.RunCompile(Templates.Summary.GetSource(), "index", typeof(Model.CompositeTemplate), compositeTemplate, null);

            File.WriteAllText(Path.Combine(outputDirectory, "Index.ejs"), index);
            string summary = Engine.Razor.RunCompile(Templates.TemplateManager.GetReportsTemplate(), "summary", typeof(CompositeTemplate), compositeTemplate);

            File.WriteAllText(Path.Combine(outputDirectory, "Summary.ejs"), summary);

            string timeAnalytics = Engine.Razor.RunCompile(Templates.TemplateManager.GetTimeAnalyticsTemplate(), "timeAnalytics", typeof(CompositeTemplate), compositeTemplate);

            File.WriteAllText(Path.Combine(outputDirectory, "timeAnalytics.ejs"), timeAnalytics);

            foreach (var report in compositeTemplate.ReportList)
            {
                report.SideNavLinks = compositeTemplate.SideNavLinks;

                var html = Engine.Razor.RunCompile(Templates.File.GetSource(), "report", typeof(Model.Report), report, null);
                File.WriteAllText(Path.Combine(outputDirectory, report.FileName + ".ejs"), html);
            }
        }
Пример #3
0
        public void CreateReport(string input, string outputDirectory)
        {
            var           attributes = File.GetAttributes(input);
            List <string> filePathList;

            if ((FileAttributes.Directory & attributes) == FileAttributes.Directory)
            {
                filePathList = Directory.GetFiles(input, "*.*", SearchOption.TopDirectoryOnly).ToList();
            }
            else
            {
                filePathList = new List <string>();
                filePathList.Add(input);
            }

            InitializeRazor();

            var compositeTemplate = new CompositeTemplate();

            foreach (var filePath in filePathList)
            {
                var testRunner = GetTestRunner(filePath);

                if (!(testRunner.Equals(TestRunner.Unknown)))
                {
                    IParser parser = (IParser)Assembly.GetExecutingAssembly().CreateInstance(_ns + "." + Enum.GetName(typeof(TestRunner), testRunner));
                    var     report = parser.Parse(filePath);

                    compositeTemplate.AddReport(report);
                }
            }

            if (compositeTemplate.ReportList.Count > 1)
            {
                compositeTemplate.SideNavLinks = compositeTemplate.SideNavLinks.Insert(0, Templates.SideNav.IndexLink);

                string summary = Engine.Razor.RunCompile(Templates.Summary.GetSource(), "summary", typeof(Model.CompositeTemplate), compositeTemplate, null);
                File.WriteAllText(Path.Combine(outputDirectory, "Index.html"), summary);
            }

            foreach (var report in compositeTemplate.ReportList)
            {
                report.SideNavLinks = compositeTemplate.SideNavLinks;

                var html = Engine.Razor.RunCompile(Templates.File.GetSource(), "report", typeof(Model.Report), report, null);
                File.WriteAllText(Path.Combine(outputDirectory, report.FileName + ".html"), html);
            }
        }
    protected void createEnvelope()
    {
        FileStream fs = null;

        try
        {
            String userName = ConfigurationManager.AppSettings["API.Email"];
            String password = ConfigurationManager.AppSettings["API.Password"];
            String integratorKey = ConfigurationManager.AppSettings["API.IntegratorKey"];


            String auth = "<DocuSignCredentials><Username>" + userName
                + "</Username><Password>" + password
                + "</Password><IntegratorKey>" + integratorKey
                + "</IntegratorKey></DocuSignCredentials>";
            ServiceReference1.DSAPIServiceSoapClient client = new ServiceReference1.DSAPIServiceSoapClient();

            using (OperationContextScope scope = new System.ServiceModel.OperationContextScope(client.InnerChannel))
            {
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                CompositeTemplate template = new CompositeTemplate();

                // Set up the envelope
                EnvelopeInformation envInfo = new EnvelopeInformation();
                envInfo.AutoNavigation = true;
                envInfo.AccountId = ConfigurationManager.AppSettings["API.AccountId"];
                envInfo.Subject = "Dynamic Fields Example";

                // Set up recipients 
                Recipient[] recipients;
                if (jointEmail.Value.Trim().Equals(""))
                {
                    recipients = new Recipient[1];
                }
                else
                {
                    recipients = new Recipient[2];
                }

                recipients[0] = new Recipient();
                recipients[0].ID = "1";
                recipients[0].Email = email.Value;
                recipients[0].Type = RecipientTypeCode.Signer;
                recipients[0].UserName = firstname.Value + " " + lastname.Value;
                recipients[0].CaptiveInfo = new RecipientCaptiveInfo();

                recipients[0].CaptiveInfo.ClientUserId = RandomizeClientUserID();
                recipients[0].RoutingOrder = 1;
                recipients[0].RoleName = "Signer1";

                // If there is a 2nd recipient, configure 
                if (!jointEmail.Value.Equals(""))
                {
                    recipients[1] = new Recipient();
                    recipients[1].ID = "2";
                    recipients[1].Email = jointEmail.Value;
                    recipients[1].Type = RecipientTypeCode.Signer;
                    recipients[1].UserName = jointFirstname.Value + " " + jointLastname.Value;
                    recipients[1].RoleName = "Signer2";
                    recipients[1].RoutingOrder = 1;
                }

                //Configure the inline templates 
                InlineTemplate inlineTemplate = new InlineTemplate();
                inlineTemplate.Sequence = "1";
                inlineTemplate.Envelope = new Envelope();
                inlineTemplate.Envelope.Recipients = recipients;
                inlineTemplate.Envelope.AccountId = ConfigurationManager.AppSettings["API.AccountId"];

                // Initialize tab properties 
                Tab tab = new Tab();
                tab.Type = TabTypeCode.SignHere;
                tab.XPosition = xPosition.Value;
                tab.YPosition = yPosition.Value;
                tab.TabLabel = tabName.Value;
                tab.RecipientID = "1";
                tab.DocumentID = "1";
                tab.Name = tabName.Value;
                tab.PageNumber = tabPage.Value;

                Tab tab2 = new Tab();
                tab2.Type = TabTypeCode.DateSigned;

                tab2.XPosition = xPosition2.Value;
                tab2.YPosition = yPosition2.Value;
                tab2.TabLabel = tabName2.Value;
                tab2.RecipientID = "1";
                tab2.DocumentID = "1";
                tab2.Name = tabName2.Value;
                tab2.PageNumber = tabPage2.Value;

                inlineTemplate.Envelope.Tabs = new Tab[] { tab, tab2 };

                template.InlineTemplates = new InlineTemplate[] { inlineTemplate };


                // Configure the document
                template.Document = new Document();
                template.Document.ID = "1";
                template.Document.Name = "Sample Document";
                BinaryReader binReader = null;
                String filename = uploadFile.Value;
                if (File.Exists(Server.MapPath("~/App_Data/" + filename)))
                {
                    fs = new FileStream(Server.MapPath("~/App_Data/" + filename), FileMode.Open);
                    binReader = new BinaryReader(fs);
                }
                byte[] PDF = binReader.ReadBytes(System.Convert.ToInt32(fs.Length));
                template.Document.PDFBytes = PDF;

                template.Document.TransformPdfFields = true;
                template.Document.FileExtension = "pdf";

                //Create envelope with all the composite template information 
                EnvelopeStatus status = client.CreateEnvelopeFromTemplatesAndForms(envInfo, new CompositeTemplate[] { template }, true);
                RequestRecipientTokenAuthenticationAssertion assert = new RequestRecipientTokenAuthenticationAssertion();
                assert.AssertionID = "12345";
                assert.AuthenticationInstant = DateTime.Now;
                assert.AuthenticationMethod = RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.Password;
                assert.SecurityDomain = "www.magicparadigm.com";

                RequestRecipientTokenClientURLs clientURLs = new RequestRecipientTokenClientURLs();

                clientURLs.OnAccessCodeFailed = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnAccessCodeFailed";
                clientURLs.OnCancel = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnCancel";
                clientURLs.OnDecline = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnDecline";
                clientURLs.OnException = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnException";
                clientURLs.OnFaxPending = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnFaxPending";
                clientURLs.OnIdCheckFailed = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnIdCheckFailed";
                clientURLs.OnSessionTimeout = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnSessionTimeout";
                clientURLs.OnTTLExpired = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnTTLExpired";
                clientURLs.OnViewingComplete = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnViewingComplete";


                String url = Request.Url.AbsoluteUri;

                String recipientToken;

                clientURLs.OnSigningComplete = url.Substring(0, url.LastIndexOf("/")) + "/EmbeddedSigningComplete0.aspx?envelopeID=" + status.EnvelopeID;
                recipientToken = client.RequestRecipientToken(status.EnvelopeID, recipients[0].CaptiveInfo.ClientUserId, recipients[0].UserName, recipients[0].Email, assert, clientURLs);
                Session["envelopeID"] = status.EnvelopeID;
                if (!Request.Browser.Browser.Equals("InternetExplorer") && (!Request.Browser.Browser.Equals("Safari")))
                {
                    docusignFrame.Visible = true;
                    docusignFrame.Src = recipientToken;
                }
                else // Handle IE differently since it does not allow dynamic setting of the iFrame width and height
                {
                    docusignFrameIE.Visible = true;
                    docusignFrameIE.Src = recipientToken;
                }


            }
        }
        catch (Exception ex)
        {
            // Log4Net Piece
            log4net.ILog logger = log4net.LogManager.GetLogger(typeof(DynamicFields));
            logger.Info("\n----------------------------------------\n");
            logger.Error(ex.Message);
            logger.Error(ex.StackTrace);
            Response.Write(ex.Message);

        }
        finally
        {
            if (fs != null)
                fs.Close();
        }
    }
Пример #5
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);
            }
        }
    }
Пример #6
0
        private EnvelopeDefinition MakeEnvelope(string signerEmail, string signerName, string ccEmail,
                                                string ccName, string item, string quantity)
        {
            // Data for this method
            // signerEmail
            // signerName
            // ccEmail
            // ccName
            // item
            // quantity
            // signerClientId -- class global


            // The envelope request object uses Composite Template to
            // include in the envelope:
            // 1. A template stored on the DocuSign service
            // 2. An additional document which is a custom HTML source document

            // Create Recipients for server template. Note that Recipients object
            // is used, not TemplateRole
            //
            // Create a signer recipient for the signer role of the server template
            Signer signer1 = new Signer
            {
                Email       = signerEmail,
                Name        = signerName,
                RoleName    = "signer",
                RecipientId = "1",
                // Adding clientUserId transforms the template recipient
                // into an embedded recipient:
                ClientUserId = signerClientId
            };
            // Create the cc recipient
            CarbonCopy cc1 = new CarbonCopy
            {
                Email       = ccEmail,
                Name        = ccName,
                RoleName    = "cc",
                RecipientId = "2"
            };
            // Recipients object:
            Recipients recipientsServerTemplate = new Recipients
            {
                CarbonCopies = new List <CarbonCopy> {
                    cc1
                },
                Signers = new List <Signer> {
                    signer1
                }
            };

            // create a composite template for the Server Template
            CompositeTemplate compTemplate1 = new CompositeTemplate
            {
                CompositeTemplateId = "1"
            };
            ServerTemplate serverTemplates = new ServerTemplate
            {
                Sequence   = "1",
                TemplateId = RequestItemsService.TemplateId
            };

            compTemplate1.ServerTemplates = new List <ServerTemplate> {
                serverTemplates
            };
            // Add the roles via an inlineTemplate
            InlineTemplate inlineTemplate = new InlineTemplate
            {
                Sequence   = "1",
                Recipients = recipientsServerTemplate
            };

            compTemplate1.InlineTemplates = new List <InlineTemplate> {
                inlineTemplate
            };
            // The signer recipient for the added document with
            // a tab definition:
            SignHere signHere1 = new SignHere
            {
                AnchorString  = "**signature_1**",
                AnchorYOffset = "10",
                AnchorUnits   = "pixels",
                AnchorXOffset = "20"
            };

            Tabs signer1Tabs = new Tabs
            {
                SignHereTabs = new List <SignHere> {
                    signHere1
                }
            };
            // Signer definition for the added document
            Signer signer1AddedDoc = new Signer
            {
                Email        = signerEmail,
                Name         = signerName,
                ClientUserId = signerClientId,
                RoleName     = "signer",
                RecipientId  = "1",
                Tabs         = signer1Tabs
            };
            // Recipients object for the added document:
            Recipients recipientsAddedDoc = new Recipients
            {
                CarbonCopies = new List <CarbonCopy> {
                    cc1
                },
                Signers = new List <Signer> {
                    signer1AddedDoc
                }
            };

            // create the HTML document
            Document doc1 = new Document();

            String doc1b64 = Convert.ToBase64String(document1(signerEmail, signerName, ccEmail, ccName, item, quantity));

            doc1.DocumentBase64 = doc1b64;
            doc1.Name           = "Appendix 1--Sales order"; // can be different from actual file name
            doc1.FileExtension  = "html";
            doc1.DocumentId     = "1";
            // create a composite template for the added document
            CompositeTemplate compTemplate2 = new CompositeTemplate
            {
                CompositeTemplateId = "2"
            };
            // Add the recipients via an inlineTemplate
            InlineTemplate inlineTemplate2 = new InlineTemplate
            {
                Sequence   = "2",
                Recipients = recipientsAddedDoc
            };

            compTemplate2.InlineTemplates = new List <InlineTemplate> {
                inlineTemplate2
            };
            compTemplate2.Document = doc1;

            EnvelopeDefinition env = new EnvelopeDefinition
            {
                Status             = "sent",
                CompositeTemplates = new List <CompositeTemplate> {
                    compTemplate1, compTemplate2
                }
            };

            return(env);
        }
Пример #7
0
        public void CreateReport(PathTypeEnum pathType, string inputPath, string outputPath = null)
        {
            IEnumerable <FileInfo> filePathList;

            if (pathType.Equals(PathTypeEnum.Directory))
            {
                filePathList = new DirectoryInfo(inputPath).GetFiles("*.xml", SearchOption.AllDirectories)
                               .OrderByDescending(f => f.CreationTime);
            }
            else
            {
                String directory = Path.GetDirectoryName(inputPath);
                filePathList = new DirectoryInfo(directory).GetFiles(Path.GetFileName(inputPath));
            }

            InitializeRazor();

            var compositeTemplate = new CompositeTemplate();

            foreach (var filePath in filePathList)
            {
                var testRunner = GetTestRunner(filePath.FullName);

                try
                {
                    IParser parser = ParserFactory.GetParser(testRunner);
                    var     report = parser.Parse(filePath.FullName);

                    compositeTemplate.AddReport(report);
                }
                catch (NotSupportedException ex)
                {
                    _logger.Log(Level.Error, ex.Message);
                }
            }

            if (!compositeTemplate.ReportList.Any())
            {
                Logger.GetLogger().Fatal("No reports added - invalid files?");
                return;
            }

            if (pathType == PathTypeEnum.Directory)
            {
                if (String.IsNullOrEmpty(outputPath))
                {
                    outputPath = inputPath;
                }

                compositeTemplate.SideNavLinks = compositeTemplate.SideNavLinks.Insert(0, Templates.SideNav.IndexLink);

                string summary = Engine.Razor.RunCompile(Templates.TemplateManager.GetSummaryTemplate(), "summary", typeof(Model.CompositeTemplate), compositeTemplate, null);

                File.WriteAllText(Path.Combine(outputPath, "Index.html"), summary);

                foreach (var report in compositeTemplate.ReportList)
                {
                    report.SideNavLinks = compositeTemplate.SideNavLinks;
                    var html = Engine.Razor.RunCompile(Templates.TemplateManager.GetFileTemplate(), "report", typeof(Model.Report), report, null);

                    File.WriteAllText(Path.Combine(outputPath, report.FileName + ".html"), html);
                }
            }
            else
            {
                var report = compositeTemplate.ReportList.FirstOrDefault();
                var html   = Engine.Razor.RunCompile(Templates.TemplateManager.GetFileTemplate(), "report", typeof(Model.Report), report, null);

                if (String.IsNullOrEmpty(outputPath))
                {
                    outputPath = Path.Combine(Path.GetDirectoryName(inputPath), Path.GetFileNameWithoutExtension(inputPath) + ".html");
                }
                File.WriteAllText(outputPath, html);
            }
        }
Пример #8
0
    protected void createEnvelope()
    {
        FileStream fs = null;

        try
        {
            String userName      = ConfigurationManager.AppSettings["API.Email"];
            String password      = ConfigurationManager.AppSettings["API.Password"];
            String integratorKey = ConfigurationManager.AppSettings["API.IntegratorKey"];


            String auth = "<DocuSignCredentials><Username>" + userName
                          + "</Username><Password>" + password
                          + "</Password><IntegratorKey>" + integratorKey
                          + "</IntegratorKey></DocuSignCredentials>";
            ServiceReference1.DSAPIServiceSoapClient client = new ServiceReference1.DSAPIServiceSoapClient();

            using (OperationContextScope scope = new System.ServiceModel.OperationContextScope(client.InnerChannel))
            {
                HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
                httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;

                CompositeTemplate template = new CompositeTemplate();

                // Set up recipients
                Recipient[] recipients;
                if (jointEmail.Value.Trim().Equals(""))
                {
                    recipients = new Recipient[1];
                }
                else
                {
                    recipients = new Recipient[2];
                }

                recipients[0]             = new Recipient();
                recipients[0].ID          = "1";
                recipients[0].Email       = email.Value;
                recipients[0].Type        = RecipientTypeCode.Signer;
                recipients[0].UserName    = firstname.Value + " " + lastname.Value;
                recipients[0].CaptiveInfo = new RecipientCaptiveInfo();

                recipients[0].CaptiveInfo.ClientUserId = RandomizeClientUserID();
                recipients[0].RoutingOrder             = 1;
                recipients[0].RoleName = "Signer1";

                // If there is a 2nd recipient, configure
                if (!jointEmail.Value.Equals(""))
                {
                    recipients[1]              = new Recipient();
                    recipients[1].ID           = "2";
                    recipients[1].Email        = jointEmail.Value;
                    recipients[1].Type         = RecipientTypeCode.Signer;
                    recipients[1].UserName     = jointFirstname.Value + " " + jointLastname.Value;
                    recipients[1].RoleName     = "Signer2";
                    recipients[1].RoutingOrder = 1;
                }

                //Configure the inline templates
                InlineTemplate inlineTemplate = new InlineTemplate();
                inlineTemplate.Sequence            = "2";
                inlineTemplate.Envelope            = new Envelope();
                inlineTemplate.Envelope.Recipients = recipients;
                inlineTemplate.Envelope.AccountId  = ConfigurationManager.AppSettings["API.TemplatesAccountId"];

                template.InlineTemplates = new InlineTemplate[] { inlineTemplate };
                // Configure the document
                template.Document      = new Document();
                template.Document.ID   = "1";
                template.Document.Name = "Sample Document";

                BinaryReader binReader = null;
                String       filename  = uploadFile.Value;
                if (File.Exists(Server.MapPath("~/App_Data/" + filename)))
                {
                    fs        = new FileStream(Server.MapPath("~/App_Data/" + filename), FileMode.Open);
                    binReader = new BinaryReader(fs);
                }
                byte[] PDF = binReader.ReadBytes(System.Convert.ToInt32(fs.Length));
                template.Document.PDFBytes = PDF;

                template.Document.TransformPdfFields = true;
                template.Document.FileExtension      = "pdf";

                ServerTemplate serverTemplate = new ServerTemplate();

                serverTemplate.Sequence   = "1";
                serverTemplate.TemplateID = templatesList.SelectedValue;
                template.ServerTemplates  = new ServerTemplate[] { serverTemplate };

                // Set up the envelope
                EnvelopeInformation envInfo = new EnvelopeInformation();
                envInfo.AutoNavigation = true;
                envInfo.AccountId      = ConfigurationManager.AppSettings["API.AccountId"];
                envInfo.Subject        = "Templates Example";

                //Create envelope with all the composite template information
                EnvelopeStatus status = client.CreateEnvelopeFromTemplatesAndForms(envInfo, new CompositeTemplate[] { template }, true);
                RequestRecipientTokenAuthenticationAssertion assert = new RequestRecipientTokenAuthenticationAssertion();
                assert.AssertionID           = "12345";
                assert.AuthenticationInstant = DateTime.Now;
                assert.AuthenticationMethod  = RequestRecipientTokenAuthenticationAssertionAuthenticationMethod.Password;
                assert.SecurityDomain        = "www.magicparadigm.com";

                RequestRecipientTokenClientURLs clientURLs = new RequestRecipientTokenClientURLs();

                clientURLs.OnAccessCodeFailed = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnAccessCodeFailed";
                clientURLs.OnCancel           = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnCancel";
                clientURLs.OnDecline          = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnDecline";
                clientURLs.OnException        = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnException";
                clientURLs.OnFaxPending       = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnFaxPending";
                clientURLs.OnIdCheckFailed    = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnIdCheckFailed";
                clientURLs.OnSessionTimeout   = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnSessionTimeout";
                clientURLs.OnTTLExpired       = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnTTLExpired";
                clientURLs.OnViewingComplete  = ConfigurationManager.AppSettings["RecipientTokenClientURLsPrefix"] + "?envelopeId=" + status.EnvelopeID + "&event=OnViewingComplete";


                String url = Request.Url.AbsoluteUri;

                String recipientToken;

                clientURLs.OnSigningComplete = url.Substring(0, url.LastIndexOf("/")) + "/EmbeddedSigningComplete0.aspx?envelopeID=" + status.EnvelopeID;
                recipientToken        = client.RequestRecipientToken(status.EnvelopeID, recipients[0].CaptiveInfo.ClientUserId, recipients[0].UserName, recipients[0].Email, assert, clientURLs);
                Session["envelopeID"] = status.EnvelopeID;
                if (!Request.Browser.Browser.Equals("InternetExplorer") && (!Request.Browser.Browser.Equals("Safari")))
                {
                    docusignFrame.Visible = true;
                    docusignFrame.Src     = recipientToken;
                }
                else // Handle IE differently since it does not allow dynamic setting of the iFrame width and height
                {
                    docusignFrameIE.Visible = true;
                    docusignFrameIE.Src     = recipientToken;
                }
            }
        }
        catch (Exception ex)
        {
            // Log4Net Piece
            log4net.ILog logger = log4net.LogManager.GetLogger(typeof(_Default));
            logger.Info("\n----------------------------------------\n");
            logger.Error(ex.Message);
            logger.Error(ex.StackTrace);
            Response.Write(ex.Message);
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
            }
        }
    }
Пример #9
0
        public static EnvelopeSummary RequestStudentSignatureFromTemplate(Student student)
        {
            // instantiate api client with appropriate environment (for production change to www.docusign.net/restapi)
            //configureApiClient("https://na2.docusign.net/restapi");
            configureApiClient("https://demo.docusign.net/restapi");


            // var envID = envDef.EnvelopeId;
            //AUA --> DME --> ?PRECEPTOR?

            var envDef = new EnvelopeDefinition {
                CompositeTemplates = new List <CompositeTemplate>()
            };

            // studentSigner = CreateSigner(student.StudentEmailSchool, student.StudentName, templateRoleName, routingOrder, recipientId);

            Signer studentSigner   = new Signer();
            Signer preceptorSigner = new Signer();
            Signer DMESigner       = new Signer();
            Signer signer          = new Signer();

            Agent      agent  = new Agent();
            CarbonCopy DME_CC = new CarbonCopy();


            SetEnvelopeReminders(student, envDef);


            string formName = "";

            //Assign the correct template
            //Adds all controls to List<Recipients>

            //Make a list of forms to
            var formsList = new List <string>();

            // if Student
            formsList.Add("1");
            //formsList.Add("2");
            //formsList.Add("4");

            // if DME/Preceptor
            //formsList.Add("3");
            //formsList.Add("5");

            int i = 1;

            foreach (string form in formsList)
            {
                CompositeTemplate ct = new CompositeTemplate
                {
                    ServerTemplates = new List <ServerTemplate>(),
                    InlineTemplates = new List <InlineTemplate>()
                };


                ServerTemplate st = new ServerTemplate();  //??

                InlineTemplate it = new InlineTemplate
                {
                    Recipients = new Recipients(),
                    Documents  = new List <Document>()
                };

                st.Sequence = i.ToString();

                ct.ServerTemplates.Add(st);

                Recipients r = new Recipients();
                r.Signers = new List <Signer>();

                string documentId = string.Empty;

                switch (form)
                {
                case "1":
                    formName            = "Student Clerkship Evaluation Form";
                    st.TemplateId       = StudentClerkshipEvaluationForm;
                    documentId          = StudentClerkshipEvaluationDocumentId;
                    envDef.EmailBlurb   = "Please complete your Clerkship Evaluation on the last Friday of this rotation.";
                    envDef.EmailSubject = "AUA - Student Clerkship Evaluation Form";
                    studentSigner       = CreateSigner(student.StudentEmailSchool, student.StudentName, "Student", "1", "1");
                    r.Signers.Add(studentSigner);
                    signer = studentSigner;
                    break;

                case "2":
                    formName            = "Student Faculty Evaluation Form";
                    st.TemplateId       = StudentFacultyEvaluationForm;
                    documentId          = "";
                    envDef.EmailBlurb   = "Please complete your Faculty Evaluation on the last Friday of this rotation.";
                    envDef.EmailSubject = "AUA - Student Faculty Evaluation Form";
                    studentSigner       = CreateSigner(student.StudentEmailSchool, student.StudentName, "Student", "1", "1");
                    r.Signers.Add(studentSigner);
                    signer = studentSigner;
                    break;

                case "3":
                    formName            = "Mid Clerkship Assessment Form";
                    st.TemplateId       = MidClerkshipAssessmentForm;
                    documentId          = "";
                    envDef.EmailBlurb   = "Please complete this Mid-Clerkship Assessment Form at the middle of the rotation.";
                    envDef.EmailSubject = "AUA - Mid Clerkship Assessment Form";


                    //DME FIRST (1)
                    //  DMESigner = CreateSigner("*****@*****.**", "Chris Grenard", "DME", "2", "3");
                    //   r.Signers.Add(DMESigner);
                    //  CarbonCopy carbonCopy = new CarbonCopy();
                    DME_CC = CreateCarbonCopy("*****@*****.**", "Chris Grenard", "DME", "2", "3");
                    if (r.CarbonCopies == null)
                    {
                        r.CarbonCopies = new List <CarbonCopy>();
                    }
                    r.CarbonCopies.Add(DME_CC);


                    //BEGIN PRECEPTOR CHECK
                    //If we don't know the preceptor then create agent.

                    //AGENT SECOND (2)
                    agent = CreateAgent("*****@*****.**", "Chris G", "DMEAgent", "1", "4");

                    if (r.Agents == null)
                    {
                        r.Agents = new List <Agent>();
                    }
                    r.Agents.Add(agent);



                    //else Create a precpetor using their ACTUAL INFO***
                    //PRECEP (3)
                    preceptorSigner = CreateSigner("", "", "Preceptor", "3", "1");
                    r.Signers.Add(preceptorSigner);

                    //end if


                    //Student (4)
                    studentSigner = CreateSigner(student.StudentEmailSchool, student.StudentName, "Student", "4", "2");
                    r.Signers.Add(studentSigner);

                    // Commented out b/c I don't need to prepopulate
                    signer = preceptorSigner;
                    break;

                case "4":
                    formName            = "Student Portfolio Form";
                    st.TemplateId       = StudentPortfolioForm;
                    documentId          = "";
                    envDef.EmailBlurb   = "Please complete your Student Portfolio prior to the end of this rotation.";
                    envDef.EmailSubject = "AUA - Student Portfolio";
                    studentSigner       = CreateSigner(student.StudentEmailSchool, student.StudentName, "Student", "1", "1");
                    r.Signers.Add(studentSigner);

                    signer = studentSigner;

                    break;

                case "5":
                    formName            = "Comprehensive Student Clerkship Assessment Form";
                    st.TemplateId       = ComprehensiveStudentClerkshipAssessmentForm;
                    documentId          = "";
                    envDef.EmailBlurb   = "Please complete this Comprehensive Clerkship Assessment Form for each respective student.";
                    envDef.EmailSubject = "AUA - Comprehensive Student Clerkship Assessment Form";
                    preceptorSigner     = CreateSigner("*****@*****.**", "Dr. Gometi", "Preceptor", "1", "2");
                    DMESigner           = CreateSigner("*****@*****.**", "Janes Rice, PHd.", "DME", "2", "3");
                    r.Signers.Add(preceptorSigner);
                    r.Signers.Add(DMESigner);
                    signer = preceptorSigner;
                    break;

                default:
                    break;
                }

                it.Recipients = r;  //might need to change

                it.Sequence = i.ToString();


                Document doc = new Document
                {
                    Name           = formName,
                    DocumentBase64 = CreatePersonalizedForm(student, Convert.ToInt32(form)),
                    DocumentId     = documentId
                };
                //why #2?

                it.Documents.Add(doc);

                ct.InlineTemplates.Add(it);
                envDef.CompositeTemplates.Add(ct);

                #region FormTabs

                /*
                 * The font type used for the information in the tab. Possible values are:
                 * Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, and Verdana.
                 *
                 * The font size used for the information in the tab.
                 * Possible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72.
                 *
                 * The font color used for the information in the tab. Possible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White.
                 */

                //Create a List<> for Checkboxes and add them to the collection

                //REFACTOR SOMEDAY INTO NEW METHOD SO WE CAN DYNAMICALLY ASSIGN TABS PER ROLE TYPE...
                signer.Tabs.CheckboxTabs = new List <Checkbox>();

                string core         = "false";
                string elective     = "false";
                string rotationType = "";

                rotationType = student.ClinicalRotation;
                // rotationType = rotationType.ToUpper();

                if (rotationType.ToUpper().Contains("CORE"))
                {
                    core = "true";
                }
                else
                {
                    elective = "true";
                }

                Checkbox chkCore = new Checkbox
                {
                    TabLabel = "chkCore",
                    Selected = core
                };
                signer.Tabs.CheckboxTabs.Add(chkCore);

                Checkbox chkElective = new Checkbox
                {
                    TabLabel = "chkElective",
                    Selected = elective
                };
                signer.Tabs.CheckboxTabs.Add(chkElective);

                Text StudentName = new Text
                {
                    TabLabel = "StudentName",
                    Value    = student.StudentFirstName + " " + student.StudentLastName
                };
                signer.Tabs.TextTabs.Add(StudentName);


                Text CourseId = new Text
                {
                    TabLabel  = "CourseId",
                    Value     = student.CourseId,
                    FontColor = "White"
                };
                signer.Tabs.TextTabs.Add(CourseId);

                Text ClinicalRotationName = new Text
                {
                    TabLabel = "ClinicalRotationName",
                    Value    = student.ClinicalRotation
                };

                signer.Tabs.TextTabs.Add(ClinicalRotationName);

                Text ClinicalRotationSite = new Text
                {
                    TabLabel = "ClinicalRotationSite",
                    Value    = student.ClinicalSite
                };
                signer.Tabs.TextTabs.Add(ClinicalRotationSite);

                Text StartDate = new Text
                {
                    TabLabel = "StartDate",
                    Value    = student.StartDate
                };
                signer.Tabs.TextTabs.Add(StartDate);

                Text EndDate = new Text
                {
                    TabLabel = "EndDate",
                    Value    = student.EndDate
                };
                signer.Tabs.TextTabs.Add(EndDate);

                Text txtStudentID = new Text
                {
                    TabLabel = "txtStudentID",
                    Value    = student.StudentId
                };
                signer.Tabs.TextTabs.Add(txtStudentID);


                #endregion FormTabs


                i++;
            }



            //Setting Status to sent sends the email
            envDef.Status = "sent";

            // |EnvelopesApi| contains methods related to creating and sending Envelopes (aka signature requests)
            EnvelopesApi    envelopesApi    = new EnvelopesApi();
            EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(ConfigurationManager.AppSettings["accountId"], envDef);


            // print the JSON response
            Console.WriteLine("EnvelopeSummary:\n{0}", JsonConvert.SerializeObject(envelopeSummary));

            //write a log file method or store to DB to show file was sent

            return(envelopeSummary);
        }
Пример #10
0
//                @"{
//                ""status"" : ""Sent"",
//                ""emailBlurb"":""Test Sending template in an envelope"",
//                ""emailSubject"": ""Test Sending template in an envelope"",
//                ""compositeTemplates"":[
//                {
//                    ""serverTemplates"":[
//                      {
//                        ""sequence"":""1"",
//                        ""templateId"":""280D00CB-B0F7-479A-BBBD-A09DBB05EF6F""
//                      }
//                      ],
//                    ""inlineTemplates"": [
//                    {
//                        ""sequence"": ""1"",
//                        ""recipients"":
//                        {
//                            ""signers"": [
//                            {
//                                ""recipientID"": ""1"",
//                                ""routingOrder"": ""1"",
//                                ""email"": ""*****@*****.**"",
//                                ""name"": ""Vasudevan Sampath"",
//                                ""recipientId"": ""1"",
//                                ""roleName"": ""PrimarySigner"",
//                                ""requireIdLookup"": ""true"",
//                                ""idCheckConfigurationName"":""Phone Auth $"",
//                                ""phoneAuthentication"":{
//                                ""recipMayProvideNumber"":""false"",
//                                ""recordVoicePrint"":""false"",
//                                ""senderProvidedNumbers"":[""8175842746""],
//                                ""validateRecipProvidedNumber"":""false""
//                                 },
//                            }]
//                        }
//                    }]
//
//                }]
//            }";
    protected void createEnvelope()
    {
        // Set up the envelope
        CreateEnvelopeRequest createEnvelopeRequest = new CreateEnvelopeRequest();

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

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

        signer.email        = "*****@*****.**";
        signer.name         = "Dufus McTeague";
        signer.recipientId  = "1";
        signer.routingOrder = "1";
        signer.roleName     = "Signer1";
        //signer.accessCode = "1234";
        signer.requireIdLookup = "true";
//        signer.idCheckConfigurationName = "Phone Auth $";
        signer.idCheckConfigurationName = "SMS Auth $";
        //signer.phoneAuthentication = new PhoneAuthentication();
        //signer.phoneAuthentication.senderProvidedNumbers = new List<string>();
        //signer.phoneAuthentication.senderProvidedNumbers.Add("8175842746");
        //signer.phoneAuthentication.recordVoicePrint = "true";

        signer.smsAuthentication = new SMSAuthentication();
        signer.smsAuthentication.senderProvidedNumbers = new List <string>();
        signer.smsAuthentication.senderProvidedNumbers.Add("8175842746");

        // Define a documetn
        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.documents = new List<Document>();
        //       inline1.documents.Add(document);

        ServerTemplate serverTemplate1 = new ServerTemplate();

        serverTemplate1.sequence   = "1";
        serverTemplate1.templateId = "3abc4466-82a9-4c65-8c55-7cf4c44dea85";

        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 = "Sample Form";
        //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.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=\"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"))
                {
                }
            }
        }
        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_CompositeTemplate));
                    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_CompositeTemplate));
                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);
            }
        }
    }
Пример #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            EnvelopeDefinition envDef = new EnvelopeDefinition();

            envDef.CompositeTemplates = new List <CompositeTemplate>();
            CompositeTemplate ct = new CompositeTemplate();

            ct.CompositeTemplateId = "1";

            ct.ServerTemplates = new List <ServerTemplate>();
            ServerTemplate st = new ServerTemplate();

            st.Sequence = "1";

            ct.InlineTemplates = new List <InlineTemplate>();
            InlineTemplate it = new InlineTemplate();

            it.Sequence           = "1";
            it.Recipients         = new Recipients();
            it.Recipients.Signers = new List <Signer>();

            Signer Signer1 = new Signer();

            Signer1.RecipientId         = "1";
            Signer1.Tabs                = new Tabs();
            Signer1.Tabs.TextTabs       = new List <Text>();
            Signer1.Tabs.CheckboxTabs   = new List <Checkbox>();
            Signer1.Tabs.ListTabs       = new List <List>();
            Signer1.Tabs.RadioGroupTabs = new List <RadioGroup>();
            Signer Signer2 = new Signer();

            Signer2.RecipientId         = "2";
            Signer2.Tabs                = new Tabs();
            Signer2.Tabs.TextTabs       = new List <Text>();
            Signer2.Tabs.CheckboxTabs   = new List <Checkbox>();
            Signer2.Tabs.ListTabs       = new List <List>();
            Signer2.Tabs.RadioGroupTabs = new List <RadioGroup>();

            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

            foreach (string key in Request.Form)
            {
                if (key.Length > 9)
                {
                    switch (key.Substring(0, 10))
                    {
                    case "signer1_us":
                        Signer1.Name = Request[key];
                        break;

                    case "signer1_em":
                        Signer1.Email = Request[key];
                        break;

                    case "signer1_ro":
                        Signer1.RoleName       = Request[key];
                        envelope.dsSigner1Role = Request[key];
                        break;

                    case "signer1_ty":
                        if (Request[key] == "embedded")
                        {
                            Random random1 = new Random();
                            envelope.dsSigner1CID = new string(Enumerable.Repeat(chars, 10)
                                                               .Select(s => s[random1.Next(s.Length)]).ToArray());
                            Signer1.ClientUserId = envelope.dsSigner1CID;
                        }
                        break;

                    case "signer1_au":
                        envelope.dsSigner1AuthMethod = Request[key];
                        break;

                    case "signer1_nu":
                        envelope.dsSigner1AuthNumber = Request[key];
                        break;

                    case "signer1_si":
                        envelope.dsSigner1SP = Request[key];
                        break;

                    case "signer1_tx":
                        Text   tempText1    = new Text();
                        string tempTxtLabel = key;
                        tempTxtLabel       = tempTxtLabel.Substring(12);
                        tempText1.TabLabel = tempTxtLabel;
                        tempText1.Value    = Request[key];
                        Signer1.Tabs.TextTabs.Add(tempText1);
                        break;

                    case "signer1_rb":
                        RadioGroup tempRG1     = new RadioGroup();
                        string     tempRBLabel = key;
                        tempRBLabel       = tempRBLabel.Substring(11);
                        tempRG1.GroupName = tempRBLabel;
                        tempRG1.Radios    = new List <Radio>();
                        Radio tempRB1 = new Radio();
                        tempRB1.Selected = "true";
                        tempRB1.Value    = Request[key];
                        tempRG1.Radios.Add(tempRB1);
                        Signer1.Tabs.RadioGroupTabs.Add(tempRG1);
                        break;

                    case "signer1_li":
                        List   tempList1     = new List();
                        string tempListLabel = key;
                        tempListLabel      = tempListLabel.Substring(13);
                        tempList1.TabLabel = tempListLabel;
                        tempList1.Value    = Request[key];
                        Signer1.Tabs.ListTabs.Add(tempList1);
                        break;

                    case "signer1_cb":
                        Checkbox tempCB1     = new Checkbox();
                        string   tempCBLabel = key;
                        tempCBLabel      = tempCBLabel.Substring(11);
                        tempCB1.TabLabel = tempCBLabel;
                        tempCB1.Selected = "true";
                        Signer1.Tabs.CheckboxTabs.Add(tempCB1);
                        break;


                    case "signer2_us":
                        Signer2.Name           = Request[key];
                        envelope.dsSigner2Name = Signer2.Name;
                        break;

                    case "signer2_em":
                        Signer2.Email           = Request[key];
                        envelope.dsSigner2Email = Request[key];
                        break;

                    case "signer2_ro":
                        Signer2.RoleName       = Request[key];
                        envelope.dsSigner2Role = Request[key];
                        break;

                    case "signer2_ty":
                        if (Request[key] == "embedded")
                        {
                            Random random2 = new Random();
                            envelope.dsSigner2CID = new string(Enumerable.Repeat(chars, 10)
                                                               .Select(s => s[random2.Next(s.Length)]).ToArray());
                            Signer2.ClientUserId = envelope.dsSigner2CID;
                        }
                        break;

                    case "signer2_au":
                        envelope.dsSigner2AuthMethod = Request[key];
                        break;

                    case "signer2_nu":
                        envelope.dsSigner2AuthNumber = Request[key];
                        break;

                    case "signer2_si":
                        envelope.dsSigner2SP = Request[key];
                        break;

                    case "signer2_tx":
                        Text   tempText2     = new Text();
                        string tempTxtLabel2 = key;
                        tempTxtLabel2      = tempTxtLabel2.Substring(12);
                        tempText2.TabLabel = tempTxtLabel2;
                        tempText2.Value    = Request[key];
                        Signer2.Tabs.TextTabs.Add(tempText2);
                        break;

                    case "signer2_rb":
                        RadioGroup tempRG2      = new RadioGroup();
                        string     tempRBLabel2 = key;
                        tempRBLabel2      = tempRBLabel2.Substring(11);
                        tempRG2.GroupName = tempRBLabel2;
                        tempRG2.Radios    = new List <Radio>();
                        Radio tempRB2 = new Radio();
                        tempRB2.Selected = "true";
                        tempRB2.Value    = Request[key];
                        tempRG2.Radios.Add(tempRB2);
                        Signer2.Tabs.RadioGroupTabs.Add(tempRG2);
                        break;

                    case "signer2_li":
                        List   tempList2      = new List();
                        string tempListLabel2 = key;
                        tempListLabel2     = tempListLabel2.Substring(13);
                        tempList2.TabLabel = tempListLabel2;
                        tempList2.Value    = Request[key];
                        Signer2.Tabs.ListTabs.Add(tempList2);
                        break;

                    case "signer2_cb":
                        Checkbox tempCB2      = new Checkbox();
                        string   tempCBLabel2 = key;
                        tempCBLabel2     = tempCBLabel2.Substring(13);
                        tempCB2.TabLabel = tempCBLabel2;
                        tempCB2.Selected = "true";
                        Signer2.Tabs.CheckboxTabs.Add(tempCB2);
                        break;

                    case "accountnum":
                        envelope.dsAccountId = Request[key];
                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    switch (key)
                    {
                    case "usr":
                        envelope.dsUser = Request[key];
                        break;

                    case "pd":
                        envelope.dsPassword = Request[key];
                        break;

                    case "dst":
                        envelope.dsTemplateId = Request[key];
                        break;

                    case "logo":
                        envelope.dsLogo = Request[key];
                        break;

                    default:
                        break;
                    }
                }
            }
            switch (envelope.dsSigner1AuthMethod.ToLower())
            {
            case "access code":
                Signer1.AccessCode = envelope.dsSigner1AuthNumber;
                break;

            case "sms":
                Signer1.IdCheckConfigurationName = "SMS Auth $";
                Signer1.RequireIdLookup          = "true";
                Signer1.SmsAuthentication        = new RecipientSMSAuthentication();
                Signer1.SmsAuthentication.SenderProvidedNumbers = new List <string>();
                Signer1.SmsAuthentication.SenderProvidedNumbers.Add("+" + envelope.dsSigner1AuthNumber);
                break;

            case "phone":
                Signer1.IdCheckConfigurationName = "Phone Auth $";
                Signer1.RequireIdLookup          = "true";
                Signer1.PhoneAuthentication      = new RecipientPhoneAuthentication();
                Signer1.PhoneAuthentication.SenderProvidedNumbers = new List <string>();
                Signer1.PhoneAuthentication.SenderProvidedNumbers.Add("+" + envelope.dsSigner1AuthNumber);
                Signer1.PhoneAuthentication.RecipMayProvideNumber = "false";
                break;

            case "idcheck":
                Signer1.IdCheckConfigurationName = "ID Check $";
                Signer1.RequireIdLookup          = "true";
                break;

            default:
                break;
            }

            switch (envelope.dsSigner1SP.ToLower())
            {
            case "ds electronic":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspE = new RecipientSignatureProvider();
                rspE.SignatureProviderName = "UniversalSignaturePen_ImageOnly";
                Signer1.RecipientSignatureProviders.Add(rspE);
                break;

            case "ds express":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspD = new RecipientSignatureProvider();
                rspD.SignatureProviderName = "UniversalSignaturePen_Default";
                Signer1.RecipientSignatureProviders.Add(rspD);
                break;

            case "ds aes ac":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspAESAC = new RecipientSignatureProvider();
                rspAESAC.SignatureProviderName    = "UniversalSignaturePen_OpenTrust_Hash_TSP";
                rspAESAC.SignatureProviderOptions = new RecipientSignatureProviderOptions();
                rspAESAC.SignatureProviderOptions.OneTimePassword = envelope.dsSigner1AuthNumber;
                Signer1.RecipientSignatureProviders.Add(rspAESAC);
                break;

            case "ds aes sms":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspAESSMS = new RecipientSignatureProvider();
                rspAESSMS.SignatureProviderName        = "UniversalSignaturePen_OpenTrust_Hash_TSP";
                rspAESSMS.SignatureProviderOptions     = new RecipientSignatureProviderOptions();
                rspAESSMS.SignatureProviderOptions.Sms = "+" + envelope.dsSigner1AuthNumber;
                Signer1.RecipientSignatureProviders.Add(rspAESSMS);
                break;

            case "dsa":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspDSA = new RecipientSignatureProvider();
                rspDSA.SignatureProviderName = "universalsignaturepen_docusignsigningappliance_tsp";
                Signer1.RecipientSignatureProviders.Add(rspDSA);
                break;

            case "id now":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspIDNOW = new RecipientSignatureProvider();
                rspIDNOW.SignatureProviderName = "UniversalSignaturePen_IDNow_TSP";
                Signer1.RecipientSignatureProviders.Add(rspIDNOW);
                break;

            case "us piv":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspUSPIV = new RecipientSignatureProvider();
                rspUSPIV.SignatureProviderName = "UniversalSignaturePen_PIV_Test_TSP";
                Signer1.RecipientSignatureProviders.Add(rspUSPIV);
                break;

            case "it agile":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspAgile = new RecipientSignatureProvider();
                rspAgile.SignatureProviderName = "UniversalSignaturePen_ItAgile_TSP";
                Signer1.RecipientSignatureProviders.Add(rspAgile);
                break;

            case "icp":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspICP = new RecipientSignatureProvider();
                rspICP.SignatureProviderName = "UniversalSignaturePen_ICP_SmartCard_TSP";
                Signer1.RecipientSignatureProviders.Add(rspICP);
                break;

            case "ds smart card":
                Signer1.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspSMART = new RecipientSignatureProvider();
                rspSMART.SignatureProviderName = "universalsignaturepen_ds_smartcard_tsp";
                Signer1.RecipientSignatureProviders.Add(rspSMART);
                break;

            default:
                break;
            }

            switch (envelope.dsSigner2AuthMethod.ToLower())
            {
            case "access code":
                Signer2.AccessCode = envelope.dsSigner2AuthNumber;
                break;

            case "sms":
                Signer2.IdCheckConfigurationName = "SMS Auth $";
                Signer2.RequireIdLookup          = "true";
                Signer2.SmsAuthentication        = new RecipientSMSAuthentication();
                Signer2.SmsAuthentication.SenderProvidedNumbers = new List <string>();
                Signer2.SmsAuthentication.SenderProvidedNumbers.Add("+" + envelope.dsSigner2AuthNumber);
                break;

            case "phone":
                Signer2.IdCheckConfigurationName = "Phone Auth $";
                Signer2.RequireIdLookup          = "true";
                Signer2.PhoneAuthentication      = new RecipientPhoneAuthentication();
                Signer2.PhoneAuthentication.SenderProvidedNumbers = new List <string>();
                Signer2.PhoneAuthentication.SenderProvidedNumbers.Add("+" + envelope.dsSigner2AuthNumber);
                Signer2.PhoneAuthentication.RecipMayProvideNumber = "false";
                break;

            case "idcheck":
                Signer2.IdCheckConfigurationName = "ID Check $";
                Signer2.RequireIdLookup          = "true";
                break;

            default:
                break;
            }

            switch (envelope.dsSigner2SP.ToLower())
            {
            case "ds electronic":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspE = new RecipientSignatureProvider();
                rspE.SignatureProviderName = "UniversalSignaturePen_ImageOnly";
                Signer2.RecipientSignatureProviders.Add(rspE);
                break;

            case "ds express":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspD = new RecipientSignatureProvider();
                rspD.SignatureProviderName = "UniversalSignaturePen_Default";
                Signer2.RecipientSignatureProviders.Add(rspD);
                break;

            case "ds aes ac":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspAESAC = new RecipientSignatureProvider();
                rspAESAC.SignatureProviderName    = "UniversalSignaturePen_OpenTrust_Hash_TSP";
                rspAESAC.SignatureProviderOptions = new RecipientSignatureProviderOptions();
                rspAESAC.SignatureProviderOptions.OneTimePassword = envelope.dsSigner1AuthNumber;
                Signer2.RecipientSignatureProviders.Add(rspAESAC);
                break;

            case "ds aes sms":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspAESSMS = new RecipientSignatureProvider();
                rspAESSMS.SignatureProviderName        = "UniversalSignaturePen_OpenTrust_Hash_TSP";
                rspAESSMS.SignatureProviderOptions     = new RecipientSignatureProviderOptions();
                rspAESSMS.SignatureProviderOptions.Sms = "+" + envelope.dsSigner1AuthNumber;
                Signer2.RecipientSignatureProviders.Add(rspAESSMS);
                break;

            case "dsa":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspDSA = new RecipientSignatureProvider();
                rspDSA.SignatureProviderName = "universalsignaturepen_docusignsigningappliance_tsp";
                Signer2.RecipientSignatureProviders.Add(rspDSA);
                break;

            case "id now":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspIDNOW = new RecipientSignatureProvider();
                rspIDNOW.SignatureProviderName = "UniversalSignaturePen_IDNow_TSP";
                Signer2.RecipientSignatureProviders.Add(rspIDNOW);
                break;

            case "us piv":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspUSPIV = new RecipientSignatureProvider();
                rspUSPIV.SignatureProviderName = "UniversalSignaturePen_PIV_Test_TSP";
                Signer2.RecipientSignatureProviders.Add(rspUSPIV);
                break;

            case "it agile":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspAgile = new RecipientSignatureProvider();
                rspAgile.SignatureProviderName = "UniversalSignaturePen_ItAgile_TSP";
                Signer2.RecipientSignatureProviders.Add(rspAgile);
                break;

            case "icp":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspICP = new RecipientSignatureProvider();
                rspICP.SignatureProviderName = "UniversalSignaturePen_ICP_SmartCard_TSP";
                Signer2.RecipientSignatureProviders.Add(rspICP);
                break;

            case "ds smart card":
                Signer2.RecipientSignatureProviders = new List <RecipientSignatureProvider>();
                RecipientSignatureProvider rspSMART = new RecipientSignatureProvider();
                rspSMART.SignatureProviderName = "universalsignaturepen_ds_smartcard_tsp";
                Signer2.RecipientSignatureProviders.Add(rspSMART);
                break;

            default:
                break;
            }

            it.Recipients.Signers.Add(Signer1);
            if (Signer2.Email != "")
            {
                it.Recipients.Signers.Add(Signer2);
            }

            st.TemplateId = envelope.dsTemplateId;

            ct.ServerTemplates.Add(st);
            ct.InlineTemplates.Add(it);

            envDef.CompositeTemplates.Add(ct);

            envDef.Status = "sent";

            string json = JsonConvert.SerializeObject(envDef, Formatting.Indented);

            System.Diagnostics.Debug.Write(json);

            ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi");

            Configuration.Default.ApiClient = apiClient;
            envelope.dsAuthHeader           = "{\"Username\":\"" + envelope.dsUser + "\", \"Password\":\"" + envelope.dsPassword + "\", \"IntegratorKey\":\"49cfeb67-7406-4cef-bac9-7594a8802986\"}";
            Configuration.Default.DefaultHeader.Remove("X-DocuSign-Authentication");
            Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", envelope.dsAuthHeader);

            TemplatesApi     tempApi  = new TemplatesApi();
            EnvelopeTemplate tempInfo = tempApi.Get(envelope.dsAccountId, envelope.dsTemplateId);
            string           brandId  = tempInfo.BrandId;

            AccountsApi acctApi   = new AccountsApi();
            Brand       brandInfo = acctApi.GetBrand(envelope.dsAccountId, brandId);

            foreach (var key in brandInfo.Colors)
            {
                if (key.Name == "headerBackground")
                {
                    envelope.dsHeaderColor = key.Value;
                }
                if (key.Name == "headerText")
                {
                    envelope.dsFontColor = key.Value;
                }
            }
            if (envelope.dsHeaderColor == "")
            {
                envelope.dsHeaderColor = "#5376B7";
            }
            if (envelope.dsFontColor == "")
            {
                envelope.dsFontColor = "#FFFFFF";
            }

            EnvelopesApi envelopesApi = new EnvelopesApi();

            EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(envelope.dsAccountId, envDef);

            envelope.dsEnvelopeId = envelopeSummary.EnvelopeId;

            using (StreamWriter file = File.CreateText(Server.MapPath("~/json/" + envelope.dsEnvelopeId + ".json")))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(file, envDef);
            }

            if (Signer1.ClientUserId != null && Signer2.ClientUserId != null)
            {
                RecipientViewRequest viewOptions = new RecipientViewRequest()
                {
                    ReturnUrl            = "https://innov8ive.app/hmd/signer2start.aspx",
                    ClientUserId         = envelope.dsSigner1CID,
                    AuthenticationMethod = "email",
                    UserName             = Signer1.Name,
                    Email = Signer1.Email
                };

                ViewUrl recipientView = envelopesApi.CreateRecipientView(envelope.dsAccountId, envelope.dsEnvelopeId, viewOptions);

                Response.Redirect(recipientView.Url);
            }
            else if (Signer1.ClientUserId != null && Signer2.ClientUserId == null)
            {
                RecipientViewRequest viewOptions = new RecipientViewRequest()
                {
                    ReturnUrl            = "https://innov8ive.app/hmd/status.aspx",
                    ClientUserId         = envelope.dsSigner1CID,
                    AuthenticationMethod = "email",
                    UserName             = Signer1.Name,
                    Email = Signer1.Email
                };

                ViewUrl recipientView = envelopesApi.CreateRecipientView(envelope.dsAccountId, envelope.dsEnvelopeId, viewOptions);

                Response.Redirect(recipientView.Url);
            }
            else
            {
                Response.Redirect("~/status.aspx");
            }
        }
Пример #14
0
    protected void createEnvelope()
    {
        // Set up the envelope
        CreateEnvelopeRequest createEnvelopeRequest = new CreateEnvelopeRequest();

        createEnvelopeRequest.emailSubject = "Certified Delivery Example";
        createEnvelopeRequest.status       = "sent";
        createEnvelopeRequest.emailBlurb   = "Example of how certified delivery works";

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

        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

        // 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.certifiedDeliveries = new List <CertifiedDelivery>();
        inline1.recipients.certifiedDeliveries.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.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");
        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"))
                {
                    Response.Redirect("ConfirmationPage.aspx?envelopeID=" + createEnvelopeResponse.envelopeId);
                }
            }
        }
        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(CertifiedDelivery));
                    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(CertifiedDelivery));
                logger.Info("\n----------------------------------------\n");
                logger.Error("WebRequest Error: " + ex.Message);
                logger.Error(ex.StackTrace);
                Response.Write(ex.Message);
            }
        }
    }
 private static CompositeTemplate CreateTemplateFromImages(IDSolRequestType request)
 {
     CompositeTemplate compositeTemplate = new CompositeTemplate();
       compositeTemplate.DataType = EBiometricDataType.Raw;
       for (int index = 0; index < request.FingerPrint.Length; ++index)
       {
     FingerprintTemplate fingerprintTemplate = new FingerprintTemplate();
     fingerprintTemplate.DataType = EBiometricDataType.Raw;
     fingerprintTemplate.Finger = IMSUtil.GetFingerByNumber(request.FingerPrint[index].FingerPosition.Value);
     GenericIdentifier genericIdentifier = new GenericIdentifier();
     byte[] afisReadyBmp = ImageUtil.GetAFISReadyBMP(request.FingerPrint[index].FingerPrintImage);
     genericIdentifier.RawData = afisReadyBmp;
     genericIdentifier.IdentType = new IdentifierType();
     genericIdentifier.IdentType.Type = EBiometricIdentifierType.FingerPrint;
     fingerprintTemplate.Identifier = (IIdentifier) genericIdentifier;
     compositeTemplate.Collection.Add((object) fingerprintTemplate);
       }
       if (request.FaceImage != null)
       {
     IMSUtil.log.Info("Face Image Is Not Null");
     FacialTemplate facialTemplate = new FacialTemplate();
     facialTemplate.DataType = EBiometricDataType.Raw;
     GenericIdentifier genericIdentifier = new GenericIdentifier();
     genericIdentifier.IdentType = new IdentifierType(EBiometricIdentifierType.FacialFeatures);
     genericIdentifier.RawData = request.FaceImage;
     facialTemplate.Identifier = (IIdentifier) genericIdentifier;
     compositeTemplate.Collection.Add((object) facialTemplate);
       }
       return compositeTemplate;
 }
 private static CompositeTemplate CreateFingerprintTemplateFromTemplate(IDSolRequestType request)
 {
     CompositeTemplate compositeTemplate = new CompositeTemplate();
       compositeTemplate.DataType = EBiometricDataType.Processed;
       for (int index = 0; index < request.FingerPrint.Length; ++index)
       {
     FingerprintTemplate fingerprintTemplate = new FingerprintTemplate();
     fingerprintTemplate.DataType = EBiometricDataType.Processed;
     fingerprintTemplate.Finger = IMSUtil.GetFingerByNumber(request.FingerPrint[index].FingerPosition.Value);
     GenericIdentifier genericIdentifier = new GenericIdentifier();
     genericIdentifier.RawData = request.FingerPrint[index].FingerPrintImage;
     genericIdentifier.IdentType = new IdentifierType();
     genericIdentifier.IdentType.Type = EBiometricIdentifierType.FingerPrint;
     fingerprintTemplate.Identifier = (IIdentifier) genericIdentifier;
     compositeTemplate.Collection.Add((object) fingerprintTemplate);
       }
       return compositeTemplate;
 }