/// <summary>
        /// Cancels the document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public bool CancelDocument( SignatureDocument document, out List<string> errorMessages )
        {
            errorMessages = new List<string>();
            if ( document == null || document.SignatureDocumentTemplate == null )
            {
                errorMessages.Add( "Invalid Document or Template." );
            }

            if ( !errorMessages.Any() )
            {
                var provider = DigitalSignatureContainer.GetComponent( document.SignatureDocumentTemplate.ProviderEntityType.Name );
                if ( provider == null || !provider.IsActive )
                {
                    errorMessages.Add( "Digital Signature provider was not found or is not active." );
                }
                else
                {
                    if ( provider.CancelDocument( document, out errorMessages ) )
                    {
                        if ( document.Status != SignatureDocumentStatus.Cancelled )
                        {
                            document.LastStatusDate = RockDateTime.Now;
                        }
                        document.Status = SignatureDocumentStatus.Cancelled;

                        return true;
                    }
                }
            }

            return false;
        }
Esempio n. 2
0
        /// <summary>
        /// Cancels the document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public override bool CancelDocument( SignatureDocument document, out List<string> errors )
        {
            errors = new List<string>();

            if ( document == null )
            {
                errors.Add( "Invalid Document!" );
                return false;
            }

            // Get the access token
            string errorMessage = string.Empty;
            string accessToken = GetAccessToken( false, out errorMessage );
            if ( string.IsNullOrWhiteSpace( accessToken ) )
            {
                errors.Add( errorMessage );
                return false;
            }

            JObject CancelRes = CudaSign.Document.CancelInvite( accessToken, document.DocumentKey );
            errors = ParseErrors( CancelRes );
            if ( errors.Any() )
            {
                return false;
            }

            return true;
        }
        /// <summary>
        /// Inserta un documento para generar una firma externally detached.
        /// </summary>
        /// <param name="fileName"></param>
        private void SetContentExternallyDetached(SignatureDocument sigDocument, string fileName)
        {
            _refContent = new Reference();

            sigDocument.Document       = new XmlDocument();
            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);

            _refContent.Uri = new Uri(fileName).AbsoluteUri;
            _refContent.Id  = "Reference-" + Guid.NewGuid().ToString();

            if (_refContent.Uri.EndsWith(".xml") || _refContent.Uri.EndsWith(".XML"))
            {
                _mimeType = "text/xml";
                _refContent.AddTransform(new XmlDsigC14NTransform());
            }


            sigDocument.XadesSignature.AddReference(_refContent);
        }
        private void AddCertificateInfo(SignatureDocument sigDocument, SignatureParameters parameters)
        {
            sigDocument.XadesSignature.SigningKey = parameters.Signer.SigningKey;

            KeyInfo keyInfo = new KeyInfo();

            keyInfo.Id = "KeyInfoId-" + sigDocument.XadesSignature.Signature.Id;
            keyInfo.AddClause(new KeyInfoX509Data((X509Certificate)parameters.Signer.Certificate));
            keyInfo.AddClause(new RSAKeyValue((RSA)parameters.Signer.SigningKey));

            sigDocument.XadesSignature.KeyInfo = keyInfo;

            Reference reference = new Reference();

            reference.Id  = "ReferenceKeyInfo";
            reference.Uri = "#KeyInfoId-" + sigDocument.XadesSignature.Signature.Id;

            sigDocument.XadesSignature.AddReference(reference);
        }
Esempio n. 5
0
        private void AddXPathTransform(SignatureDocument sigDocument, Dictionary <string, string> namespaces, string XPathString)
        {
            XmlDocument xmlDocument = (sigDocument.Document == null) ? new XmlDocument() : sigDocument.Document;
            XmlElement  xmlElement  = xmlDocument.CreateElement("XPath");

            foreach (KeyValuePair <string, string> @namespace in namespaces)
            {
                XmlAttribute xmlAttribute = xmlDocument.CreateAttribute("xmlns:" + @namespace.Key);
                xmlAttribute.Value = @namespace.Value;
                xmlElement.Attributes.Append(xmlAttribute);
            }
            xmlElement.InnerText = XPathString;
            XmlDsigXPathTransform xmlDsigXPathTransform = new XmlDsigXPathTransform();

            xmlDsigXPathTransform.LoadInnerXml(xmlElement.SelectNodes("."));
            Reference reference = sigDocument.XadesSignature.SignedInfo.References[0] as Reference;

            reference.AddTransform(xmlDsigXPathTransform);
        }
        private void TimeStampCertRefs(SignatureDocument signatureDocument, UpgradeParameters parameters)
        {
            TimeStamp xadesXTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[] signatureValueHash;

            XmlElement nodoFirma = signatureDocument.XadesSignature.GetSignatureElement();

            XmlNamespaceManager nm = new XmlNamespaceManager(signatureDocument.Document.NameTable);

            nm.AddNamespace("xades", XadesSignedXml.XadesNamespaceUri);
            nm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            XmlNode xmlCompleteCertRefs = nodoFirma.SelectSingleNode("ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CompleteCertificateRefs", nm);

            if (xmlCompleteCertRefs == null)
            {
                signatureDocument.UpdateDocument();
            }

            signatureValueElementXpaths = new ArrayList();
            signatureValueElementXpaths.Add("ds:SignatureValue");
            signatureValueElementXpaths.Add("ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:SignatureTimeStamp");
            signatureValueElementXpaths.Add("ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CompleteCertificateRefs");
            signatureValueElementXpaths.Add("ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:CompleteRevocationRefs");
            signatureValueHash = DigestUtil.ComputeHashValue(XMLUtil.ComputeValueOfElementList(signatureDocument.XadesSignature, signatureValueElementXpaths), parameters.DigestMethod);

            byte[] tsa = parameters.TimeStampClient.GetTimeStamp(signatureValueHash, parameters.DigestMethod, true);

            xadesXTimeStamp    = new TimeStamp("SigAndRefsTimeStamp");
            xadesXTimeStamp.Id = "SigAndRefsStamp-" + signatureDocument.XadesSignature.Signature.Id;
            xadesXTimeStamp.EncapsulatedTimeStamp.PkiData = tsa;
            xadesXTimeStamp.EncapsulatedTimeStamp.Id      = "SigAndRefsStamp-" + Guid.NewGuid().ToString();
            UnsignedProperties unsignedProperties = signatureDocument.XadesSignature.UnsignedProperties;

            unsignedProperties.UnsignedSignatureProperties.RefsOnlyTimeStampFlag = false;
            unsignedProperties.UnsignedSignatureProperties.SigAndRefsTimeStampCollection.Add(xadesXTimeStamp);


            signatureDocument.XadesSignature.UnsignedProperties = unsignedProperties;
        }
        public void Upgrade(SignatureDocument signatureDocument, UpgradeParameters parameters)
        {
            TimeStamp signatureTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[]             signatureValueHash;
            UnsignedProperties unsignedProperties = signatureDocument.XadesSignature.UnsignedProperties;

            try
            {
                if (unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Count > 0)
                {
                    throw new Exception("The signature already contains a time stamp");
                }

                signatureValueElementXpaths = new ArrayList
                {
                    "ds:SignatureValue"
                };
                signatureValueHash = DigestUtil.ComputeHashValue(XMLUtil.ComputeValueOfElementList(signatureDocument.XadesSignature, signatureValueElementXpaths), parameters.DigestMethod);

                byte[] tsa = parameters.TimeStampClient.GetTimeStamp(signatureValueHash, parameters.DigestMethod, true);

                signatureTimeStamp = new TimeStamp("SignatureTimeStamp")
                {
                    Id = "SignatureTimeStamp-" + signatureDocument.XadesSignature.Signature.Id
                };
                signatureTimeStamp.EncapsulatedTimeStamp.PkiData = tsa;
                signatureTimeStamp.EncapsulatedTimeStamp.Id      = "SignatureTimeStamp-" + Guid.NewGuid().ToString();

                unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Add(signatureTimeStamp);

                signatureDocument.XadesSignature.UnsignedProperties = unsignedProperties;

                signatureDocument.UpdateDocument();
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred while inserting the time stamp", ex);
            }
        }
Esempio n. 8
0
        public void Upgrade(SignatureDocument signatureDocument, UpgradeParameters parameters)
        {
            TimeStamp signatureTimeStamp;
            ArrayList signatureValueElementXpaths;

            byte[]             signatureValueHash;
            UnsignedProperties unsignedProperties = signatureDocument.XadesSignature.UnsignedProperties;

            try
            {
                if (unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Count > 0)
                {
                    throw new Exception("La firma ya contiene un sello de tiempo");
                }

                XmlDsigExcC14NTransform excTransform = new XmlDsigExcC14NTransform();

                signatureValueElementXpaths = new ArrayList();
                signatureValueElementXpaths.Add("ds:SignatureValue");
                signatureValueHash = DigestUtil.ComputeHashValue(XMLUtil.ComputeValueOfElementList(signatureDocument.XadesSignature, signatureValueElementXpaths, excTransform), parameters.DigestMethod);

                byte[] tsa = parameters.TimeStampClient.GetTimeStamp(signatureValueHash, parameters.DigestMethod, true);

                signatureTimeStamp    = new TimeStamp("SignatureTimeStamp");
                signatureTimeStamp.Id = "SignatureTimeStamp-" + signatureDocument.XadesSignature.Signature.Id;
                signatureTimeStamp.CanonicalizationMethod           = new CanonicalizationMethod();
                signatureTimeStamp.CanonicalizationMethod.Algorithm = excTransform.Algorithm;
                signatureTimeStamp.EncapsulatedTimeStamp.PkiData    = tsa;
                signatureTimeStamp.EncapsulatedTimeStamp.Id         = "SignatureTimeStamp-" + Guid.NewGuid().ToString();

                unsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Add(signatureTimeStamp);

                signatureDocument.XadesSignature.UnsignedProperties = unsignedProperties;

                signatureDocument.UpdateDocument();
            }
            catch (Exception ex)
            {
                throw new Exception("Ha ocurrido un error al insertar el sellado de tiempo.", ex);
            }
        }
Esempio n. 9
0
 private void PrepareSignature(SignatureDocument sigDocument, SignatureParameters parameters)
 {
     sigDocument.XadesSignature.SignedInfo.SignatureMethod = parameters.SignatureMethod.URI;
     AddCertificateInfo(sigDocument, parameters);
     AddXadesInfo(sigDocument, parameters);
     foreach (Reference reference in sigDocument.XadesSignature.SignedInfo.References)
     {
         reference.DigestMethod = parameters.DigestMethod.URI;
     }
     if (parameters.SignatureDestination != null)
     {
         SetSignatureDestination(sigDocument, parameters.SignatureDestination);
     }
     if (parameters.XPathTransformations.Count > 0)
     {
         foreach (SignatureXPathExpression xPathTransformation in parameters.XPathTransformations)
         {
             AddXPathTransform(sigDocument, xPathTransformation.Namespaces, xPathTransformation.XPathExpression);
         }
     }
 }
Esempio n. 10
0
        public SignatureDocument[] Load(XmlDocument xmlDocument)
        {
            XmlNodeList elementsByTagName = xmlDocument.GetElementsByTagName("Signature", "http://www.w3.org/2000/09/xmldsig#");

            if (elementsByTagName.Count == 0)
            {
                throw new Exception("No se ha encontrado ninguna firma.");
            }
            List <SignatureDocument> list = new List <SignatureDocument>();

            foreach (object item in elementsByTagName)
            {
                SignatureDocument signatureDocument = new SignatureDocument();
                signatureDocument.Document = (XmlDocument)xmlDocument.Clone();
                signatureDocument.Document.PreserveWhitespace = true;
                signatureDocument.XadesSignature = new XadesSignedXml(signatureDocument.Document);
                signatureDocument.XadesSignature.LoadXml((XmlElement)item);
                list.Add(signatureDocument);
            }
            return(list.ToArray());
        }
Esempio n. 11
0
        /// <summary>
        /// Inserta un contenido XML para generar una firma enveloping.
        /// </summary>
        /// <param name="xmlDocument"></param>
        private void SetContentEveloping(SignatureDocument sigDocument, XmlDocument xmlDocument, string objectId, string refType)
        {
            _refContent = new Reference();

            sigDocument.XadesSignature = new XadesSignedXml();

            XmlDocument doc = (XmlDocument)xmlDocument.Clone();

            doc.PreserveWhitespace = true;

            if (doc.ChildNodes[0].NodeType == XmlNodeType.XmlDeclaration)
            {
                doc.RemoveChild(doc.ChildNodes[0]);
            }

            //Add an object
            string     dataObjectId = "DataObject-" + Guid.NewGuid().ToString();
            DataObject dataObject   = new System.Security.Cryptography.Xml.DataObject();

            dataObject.Data = doc.ChildNodes;
            dataObject.Id   = dataObjectId;
            sigDocument.XadesSignature.AddObject(dataObject);

            _refContent.Id = "Reference-" + Guid.NewGuid().ToString();
            if (!string.IsNullOrEmpty(objectId))
            {
                _refContent.Uri = "#" + objectId;
            }
            else
            {
                _refContent.Uri = "#" + dataObjectId;
            }
            _refContent.Type = refType;

            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();

            _refContent.AddTransform(transform);

            sigDocument.XadesSignature.AddReference(_refContent);
        }
Esempio n. 12
0
        private void btnCoFirmar_Click(object sender, EventArgs e)
        {
            if (_signatureDocument == null)
            {
                return;
            }

            SignatureParameters parametros = ObtenerParametrosFirma();

            parametros.Certificate        = CertUtil.SelectCertificate();
            parametros.SignaturePackaging = _signatureDocument.SignaturePackaging;

            using (parametros.Signer = new Signer((X509Certificate2)parametros.Certificate))
            {
                CadesService cs = new CadesService();

                _signatureDocument = cs.CoSign(_signatureDocument, parametros);
            }

            MessageBox.Show("Firma completada, ahora puede Guardar la firma o ampliarla a CAdES-T.", "Test firma CAdES",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 13
0
 private void SetContentInternallyDetached(SignatureDocument sigDocument, XmlDocument xmlDocument, string elementId, string mimeType)
 {
     sigDocument.Document = xmlDocument;
     _refContent          = new Reference();
     _refContent.Uri      = "#" + elementId;
     _refContent.Id       = "Reference-" + Guid.NewGuid().ToString();
     _mimeType            = mimeType;
     if (mimeType == "text/xml")
     {
         XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
         _refContent.AddTransform(transform);
         _encoding = "UTF-8";
     }
     else
     {
         XmlDsigBase64Transform xmlDsigBase64Transform = new XmlDsigBase64Transform();
         _refContent.AddTransform(xmlDsigBase64Transform);
         _encoding = xmlDsigBase64Transform.Algorithm;
     }
     sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);
     sigDocument.XadesSignature.AddReference(_refContent);
 }
Esempio n. 14
0
        public void Upgrade(SignatureDocument sigDocument, SignatureFormat toFormat, UpgradeParameters parameters)
        {
            XadesTUpgrader  xadesTUpgrader  = null;
            XadesXLUpgrader xadesXLUpgrader = null;

            SignatureDocument.CheckSignatureDocument(sigDocument);
            if (toFormat == SignatureFormat.XAdES_T)
            {
                xadesTUpgrader = new XadesTUpgrader();
                xadesTUpgrader.Upgrade(sigDocument, parameters);
            }
            else
            {
                if (sigDocument.XadesSignature.UnsignedProperties.UnsignedSignatureProperties.SignatureTimeStampCollection.Count == 0)
                {
                    xadesTUpgrader = new XadesTUpgrader();
                    xadesTUpgrader.Upgrade(sigDocument, parameters);
                }
                xadesXLUpgrader = new XadesXLUpgrader();
                xadesXLUpgrader.Upgrade(sigDocument, parameters);
            }
        }
Esempio n. 15
0
        public ValidationResult Validate(SignatureDocument sigDocument, SignerInfoNode signerNode)
        {
            ValidationResult result = new ValidationResult();

            try
            {
                if (!signerNode.SignerInformation.Verify(signerNode.Certificate))
                {
                    result.IsValid = false;
                    result.Message = "Signature verification failed";

                    return(result);
                }

                if (signerNode.TimeStamp != null)
                {
                    DigestMethod tokenDigestMethod  = DigestMethod.GetByOid(signerNode.TimeStamp.TimeStampInfo.HashAlgorithm.ObjectID.Id);
                    byte[]       signatureValueHash = tokenDigestMethod.CalculateDigest(signerNode.SignerInformation.GetSignature());

                    if (!signerNode.TimeStamp.TimeStampInfo.GetMessageImprintDigest().SequenceEqual(signatureValueHash))
                    {
                        result.IsValid = false;
                        result.Message = "The stamp of the time stamp does not correspond to the one calculated";

                        return(result);
                    }
                }

                result.IsValid = true;
                result.Message = "Signature verification suceeded";
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Message = ex.Message;
            }

            return(result);
        }
Esempio n. 16
0
        private void btnCoFirmar_Click(object sender, EventArgs e)
        {
            if (_signatureDocument == null)
            {
                return;
            }

            SignatureParameters parametros = ObtenerParametrosFirma();

            parametros.Certificate        = CertUtil.SelectCertificate();
            parametros.SignaturePackaging = _signatureDocument.SignaturePackaging;

            using (parametros.Signer = new Signer((X509Certificate2)parametros.Certificate))
            {
                CadesService cs = new CadesService();

                _signatureDocument = cs.CoSign(_signatureDocument, parametros);
            }

            MessageBox.Show("Signature completed, you can now save the signature or extend it to CAdES-T.", "CAdES signature test",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 17
0
        private void btnFirmaMavisa_Click(object sender, EventArgs e)
        {
            // Demostración de firma masiva

            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                DirectoryInfo   dirInfo = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
                List <FileInfo> files   = new List <FileInfo>(dirInfo.EnumerateFiles("*.pdf"));

                if (files.Count == 0)
                {
                    MessageBox.Show("No se han encontrado documentos");
                    return;
                }

                using (Signer signer = new Signer(SelectCertificate()))
                {
                    SignatureParameters sp = new SignatureParameters
                    {
                        Signer              = signer,
                        SignaturePackaging  = SignaturePackaging.INTERNALLY_DETACHED,
                        InputMimeType       = "application/pdf",
                        SignatureMethod     = ObtenerAlgoritmo(),
                        SignaturePolicyInfo = ObtenerPolitica()
                    };

                    XadesService xadesService = new XadesService();

                    foreach (var file in files)
                    {
                        SignatureDocument sigDocument = xadesService.Sign(file.OpenRead(), sp);

                        sigDocument.Save(string.Format(@"{0}\{1}.{2}", folderBrowserDialog1.SelectedPath, Path.GetFileNameWithoutExtension(file.Name), "xsig"));
                    }
                }

                MessageBox.Show("Process completed.");
            }
        }
Esempio n. 18
0
        public ValidationResult Validate(SignatureDocument sigDocument, SignerInfoNode signerNode)
        {
            ValidationResult result = new ValidationResult();

            try
            {
                if (!signerNode.SignerInformation.Verify(signerNode.Certificate))
                {
                    result.IsValid = false;
                    result.Message = "La verificación de la firma no ha sido satisfactoria";

                    return(result);
                }

                if (signerNode.TimeStamp != null)
                {
                    DigestMethod tokenDigestMethod  = DigestMethod.GetByOid(signerNode.TimeStamp.TimeStampInfo.HashAlgorithm.ObjectID.Id);
                    byte[]       signatureValueHash = tokenDigestMethod.CalculateDigest(signerNode.SignerInformation.GetSignature());

                    if (!signerNode.TimeStamp.TimeStampInfo.GetMessageImprintDigest().SequenceEqual(signatureValueHash))
                    {
                        result.IsValid = false;
                        result.Message = "La huella del sello de tiempo no se corresponde con la calculada";

                        return(result);
                    }
                }

                result.IsValid = true;
                result.Message = "Verificación de la firma satisfactoria";
            }
            catch (Exception ex)
            {
                result.IsValid = false;
                result.Message = ex.Message;
            }

            return(result);
        }
        private void SetContentEnveloped(SignatureDocument sigDocument, XmlDocument xmlDocument)
        {
            sigDocument.Document       = xmlDocument;
            _refContent                = new Reference();
            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);
            _refContent.Id             = "xmldsig-ab2df1fb-1819-413d-8b8c-79e9ed75638a-ref0";
            _refContent.Uri            = "";
            _mimeType = "text/xml";
            _encoding = "UTF-8";
            for (int i = 0; i < sigDocument.Document.DocumentElement.Attributes.Count; i++)
            {
                if (sigDocument.Document.DocumentElement.Attributes[i].Name.Equals("id", StringComparison.InvariantCultureIgnoreCase))
                {
                    _refContent.Uri = "#" + sigDocument.Document.DocumentElement.Attributes[i].Value;
                    break;
                }
            }
            XmlDsigEnvelopedSignatureTransform transform = new XmlDsigEnvelopedSignatureTransform();

            _refContent.AddTransform(transform);
            sigDocument.XadesSignature.AddReference(_refContent);
        }
Esempio n. 20
0
        /// <summary>
        /// Inserta un contenido XML para generar una firma enveloping.
        /// </summary>
        /// <param name="xmlDocument"></param>
        private void SetContentEveloping(SignatureDocument sigDocument, XmlDocument xmlDocument)
        {
            _refContent = new Reference();

            sigDocument.XadesSignature = new XadesSignedXml();

            XmlDocument doc = (XmlDocument)xmlDocument.Clone();

            doc.PreserveWhitespace = true;

            if (doc.ChildNodes[0].NodeType == XmlNodeType.XmlDeclaration)
            {
                doc.RemoveChild(doc.ChildNodes[0]);
            }

            //Add an object
            string dataObjectId = "DataObject-" + Guid.NewGuid().ToString();

            System.Security.Cryptography.Xml.DataObject dataObject = new System.Security.Cryptography.Xml.DataObject
            {
                Data = doc.ChildNodes,
                Id   = dataObjectId
            };
            sigDocument.XadesSignature.AddObject(dataObject);

            _refContent.Id   = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Uri  = "#" + dataObjectId;
            _refContent.Type = XadesSignedXml.XmlDsigObjectType;

            XmlDsigC14NTransform transform = new XmlDsigC14NTransform();

            _refContent.AddTransform(transform);

            _mimeType = "text/xml";
            _encoding = "UTF-8";

            sigDocument.XadesSignature.AddReference(_refContent);
        }
Esempio n. 21
0
        private void AddCertificateInfo(SignatureDocument sigDocument, SignatureParameters parameters)
        {
            sigDocument.XadesSignature.SigningKey = parameters.Signer.SigningKey;
            sigDocument.XadesSignature.HsmWrapper = parameters.Signer.HsmWrapper;
            KeyInfo keyInfo = new KeyInfo();

            keyInfo.Id = "KeyInfoId-" + sigDocument.XadesSignature.Signature.Id;
            var signerCertificate = parameters.Signer.Certificate;
            var rsapublicKey      = signerCertificate.GetRSAPublicKey();

            keyInfo.AddClause(new KeyInfoX509Data((X509Certificate)signerCertificate));
            keyInfo.AddClause(new RSAKeyValue((RSA)rsapublicKey));


            sigDocument.XadesSignature.KeyInfo = keyInfo;

            Reference reference = new Reference();

            reference.Id  = "ReferenceKeyInfo";
            reference.Uri = "#KeyInfoId-" + sigDocument.XadesSignature.Signature.Id;

            sigDocument.XadesSignature.AddReference(reference);
        }
Esempio n. 22
0
        private void SetSignatureDestination(SignatureDocument sigDocument, SignatureXPathExpression destination)
        {
            XmlNode xmlNode;

            if (destination.Namespaces.Count > 0)
            {
                XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(sigDocument.Document.NameTable);
                foreach (KeyValuePair <string, string> @namespace in destination.Namespaces)
                {
                    xmlNamespaceManager.AddNamespace(@namespace.Key, @namespace.Value);
                }
                xmlNode = sigDocument.Document.SelectSingleNode(destination.XPathExpression, xmlNamespaceManager);
            }
            else
            {
                xmlNode = sigDocument.Document.SelectSingleNode(destination.XPathExpression);
            }
            if (xmlNode == null)
            {
                throw new Exception("Elemento no encontrado");
            }
            sigDocument.XadesSignature.SignatureNodeDestination = (XmlElement)xmlNode;
        }
Esempio n. 23
0
        public SignatureDialog(Window owner, SignatureDocument document, Signature parentSignature)
        {
            InitializeComponent();

            Owner = owner;

            Items = new ObservableCollection <SignedItem>();
            Items.Add(new SignedItem()
            {
                Type = parentSignature == null ? SignedItemType.Document : SignedItemType.Signature
            });

            CertificateList = new ObservableCollection <X509Certificate2>(Utils.GetCertificates().OfType <X509Certificate2>());

            SelectedPolicy      = Policies?.FirstOrDefault();
            SelectedCertificate = CertificateList.FirstOrDefault();

            _document        = document;
            _parentSignature = parentSignature;
            _lastDirectory   = Path.GetDirectoryName(document.BaseUri);

            DataContext = this;
        }
Esempio n. 24
0
        public void Upgrade(SignatureDocument signatureDocument, UpgradeParameters parameters)
        {
            UnsignedProperties unsignedProperties = null;
            CertificateValues  certificateValues  = null;

            X509Certificate2 signingCertificate = signatureDocument.XadesSignature.GetSigningCertificate();

            unsignedProperties = signatureDocument.XadesSignature.UnsignedProperties;
            unsignedProperties.UnsignedSignatureProperties.CompleteCertificateRefs = new CompleteCertificateRefs
            {
                Id = "CompleteCertificates-" + Guid.NewGuid().ToString()
            };

            unsignedProperties.UnsignedSignatureProperties.CertificateValues = new CertificateValues();
            certificateValues    = unsignedProperties.UnsignedSignatureProperties.CertificateValues;
            certificateValues.Id = "CertificatesValues-" + Guid.NewGuid().ToString();

            unsignedProperties.UnsignedSignatureProperties.CompleteRevocationRefs = new CompleteRevocationRefs
            {
                Id = "CompleteRev-" + Guid.NewGuid().ToString()
            };

            unsignedProperties.UnsignedSignatureProperties.RevocationValues = new RevocationValues
            {
                Id = "RevocationValues-" + Guid.NewGuid().ToString()
            };

            AddCertificate(signingCertificate, unsignedProperties, false, parameters.OCSPServers, parameters.CRL, parameters.DigestMethod, parameters.GetOcspUrlFromCertificate);

            AddTSACertificates(unsignedProperties, parameters.OCSPServers, parameters.CRL, parameters.DigestMethod, parameters.GetOcspUrlFromCertificate);

            signatureDocument.XadesSignature.UnsignedProperties = unsignedProperties;

            TimeStampCertRefs(signatureDocument, parameters);

            signatureDocument.UpdateDocument();
        }
Esempio n. 25
0
        private void btnFirmarHuella_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtHuellaPrecalculada.Text))
            {
                MessageBox.Show("Debe especificar el valor de huella a firmar");
                return;
            }

            SignatureParameters parametros = ObtenerParametrosFirma();

            byte[] digestValue = Convert.FromBase64String(txtHuellaPrecalculada.Text);

            if ((parametros.DigestMethod == DigestMethod.SHA1 &&
                 digestValue.Length != 20) ||
                (parametros.DigestMethod == DigestMethod.SHA256 &&
                 digestValue.Length != 32) ||
                (parametros.DigestMethod == DigestMethod.SHA512 &&
                 digestValue.Length != 64))
            {
                MessageBox.Show("La longitud del valor de la huella no coincide con el algoritmo de huella seleccionado.");
                return;
            }

            parametros.Certificate         = CertUtil.SelectCertificate();
            parametros.SignaturePolicyInfo = null;
            parametros.PreCalculatedDigest = digestValue;

            CadesService cs = new CadesService();

            using (parametros.Signer = new Signer((X509Certificate2)parametros.Certificate))
            {
                _signatureDocument = cs.Sign(null, parametros);
            }

            MessageBox.Show("Firma completada, ahora puede Guardar la firma o ampliarla a CAdES-T.", "Test firma CAdES",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 26
0
        private void btnFirmarHuella_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtHuellaPrecalculada.Text))
            {
                MessageBox.Show("You must specify the fingerprint value to sign");
                return;
            }

            SignatureParameters parametros = ObtenerParametrosFirma();

            byte[] digestValue = Convert.FromBase64String(txtHuellaPrecalculada.Text);

            if ((parametros.DigestMethod == DigestMethod.SHA1 &&
                 digestValue.Length != 20) ||
                (parametros.DigestMethod == DigestMethod.SHA256 &&
                 digestValue.Length != 32) ||
                (parametros.DigestMethod == DigestMethod.SHA512 &&
                 digestValue.Length != 64))
            {
                MessageBox.Show("The length of the fingerprint value does not match the selected fingerprint algorithm.");
                return;
            }

            parametros.Certificate         = CertUtil.SelectCertificate();
            parametros.SignaturePolicyInfo = null;
            parametros.PreCalculatedDigest = digestValue;

            CadesService cs = new CadesService();

            using (parametros.Signer = new Signer((X509Certificate2)parametros.Certificate))
            {
                _signatureDocument = cs.Sign(null as Stream, parametros);
            }

            MessageBox.Show("Signature completed, you can now save the signature or extend it to CAdES-T.", "CAdES signature test",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        /// <summary>
        /// Inserta un documento para generar una firma internally detached.
        /// </summary>
        /// <param name="content"></param>
        /// <param name="mimeType"></param>
        private void SetContentInternallyDetachedHashed(SignatureDocument sigDocument, XmlDocument input)
        {
            sigDocument.Document = new XmlDocument();

            XmlElement rootElement = sigDocument.Document.CreateElement("DOCFIRMA");

            sigDocument.Document.AppendChild(rootElement);

            string id = "CONTENT-" + Guid.NewGuid().ToString();

            _refContent = new Reference();

            _refContent.Uri  = "#" + id;
            _refContent.Id   = "Reference-" + Guid.NewGuid().ToString();
            _refContent.Type = XadesSignedXml.XmlDsigObjectType;

            XmlElement contentElement = sigDocument.Document.CreateElement("CONTENT");

            XmlDsigBase64Transform transform = new XmlDsigBase64Transform();

            _refContent.AddTransform(transform);

            using (SHA256 sha2 = SHA256.Create())
            {
                contentElement.InnerText = Convert.ToBase64String(sha2.ComputeHash(Encoding.UTF8.GetBytes(input.InnerXml)));
            }

            contentElement.SetAttribute("Id", id);
            contentElement.SetAttribute("MimeType", _dataFormat.MimeType);
            contentElement.SetAttribute("Encoding", _dataFormat.Encoding);

            rootElement.AppendChild(contentElement);

            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);

            sigDocument.XadesSignature.AddReference(_refContent);
        }
Esempio n. 28
0
        public void Upgrade(SignatureDocument signatureDocument, SignerInfoNode signerInfoNode, UpgradeParameters parameters)
        {
            BcCms.AttributeTable unsigned         = signerInfoNode.SignerInformation.UnsignedAttributes;
            IDictionary          unsignedAttrHash = null;

            if (unsigned == null)
            {
                unsignedAttrHash = new Dictionary <DerObjectIdentifier, BcCms.Attribute>();
            }
            else
            {
                unsignedAttrHash = signerInfoNode.SignerInformation.UnsignedAttributes.ToDictionary();
            }

            BcCms.Attribute signatureTimeStamp = GetTimeStampAttribute(PkcsObjectIdentifiers.IdAASignatureTimeStampToken
                                                                       , parameters.TsaClient, parameters.DigestMethod, signerInfoNode.SignerInformation.GetSignature());

            unsignedAttrHash.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp);

            SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(signerInfoNode.SignerInformation,
                                                                                  new BcCms.AttributeTable(unsignedAttrHash));

            signerInfoNode.SignerInformation = newsi;
        }
        /// <summary>
        /// Carga el documento XML especificado y establece para firmar el elemento especificado en elementId
        /// </summary>
        /// <param name="xmlDocument"></param>
        /// <param name="elementId"></param>
        /// <param name="mimeType"></param>
        private void SetContentInternallyDetached(SignatureDocument sigDocument, XmlDocument xmlDocument, string elementId)
        {
            sigDocument.Document = xmlDocument;

            _refContent = new Reference();

            _refContent.Uri = "#" + elementId;
            _refContent.Id  = "Reference-" + Guid.NewGuid().ToString();

            if (_dataFormat.MimeType == "text/xml")
            {
                XmlDsigC14NTransform transform = new XmlDsigC14NTransform();
                _refContent.AddTransform(transform);
            }
            else
            {
                XmlDsigBase64Transform transform = new XmlDsigBase64Transform();
                _refContent.AddTransform(transform);
            }

            sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);

            sigDocument.XadesSignature.AddReference(_refContent);
        }
        /// <summary>
        /// Carga un archivo de firma.
        /// </summary>
        /// <param name="xmlDocument"></param>
        public SignatureDocument[] Load(XmlDocument xmlDocument)
        {
            XmlNodeList signatureNodeList = xmlDocument.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl);

            if (signatureNodeList.Count == 0)
            {
                throw new Exception("No se ha encontrado ninguna firma.");
            }

            List <SignatureDocument> firmas = new List <SignatureDocument>();

            foreach (var signatureNode in signatureNodeList)
            {
                SignatureDocument sigDocument = new SignatureDocument();
                sigDocument.Document = (XmlDocument)xmlDocument.Clone();
                sigDocument.Document.PreserveWhitespace = true;
                sigDocument.XadesSignature = new XadesSignedXml(sigDocument.Document);
                sigDocument.XadesSignature.LoadXml((XmlElement)signatureNode);

                firmas.Add(sigDocument);
            }

            return(firmas.ToArray());
        }
        /// <summary>
        /// Handles the Click event of the btnSaveType control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            bool inviteCancelled = false;

            var rockContext = new RockContext();

            int? documentTemplateId = ddlDocumentType.SelectedValueAsInt();
            if ( !documentTemplateId.HasValue )
            {
                nbErrorMessage.Title = string.Empty;
                nbErrorMessage.Text = "Document Template is Required!";
                nbErrorMessage.NotificationBoxType = NotificationBoxType.Danger;
                nbErrorMessage.Visible = true;
                return;
            }

            SignatureDocument signatureDocument = null;
            SignatureDocumentService service = new SignatureDocumentService( rockContext );

            int signatureDocumentId = hfSignatureDocumentId.ValueAsInt();

            int? origBinaryFileId = null;

            if ( signatureDocumentId != 0 )
            {
                signatureDocument = service.Get( signatureDocumentId );
            }

            if ( signatureDocument == null )
            {
                signatureDocument = new SignatureDocument();
                service.Add( signatureDocument );
            }

            signatureDocument.Name = tbName.Text;

            var newStatus = rbStatus.SelectedValueAsEnum<SignatureDocumentStatus>( SignatureDocumentStatus.None );
            if ( signatureDocument.Status != newStatus )
            {
                signatureDocument.Status = newStatus;
                signatureDocument.LastStatusDate = RockDateTime.Now;
                inviteCancelled = newStatus == SignatureDocumentStatus.Cancelled;
            }

            signatureDocument.AppliesToPersonAliasId = ppAppliesTo.PersonAliasId;
            signatureDocument.AssignedToPersonAliasId = ppAssignedTo.PersonAliasId;
            signatureDocument.SignedByPersonAliasId = ppSignedBy.PersonAliasId;

            signatureDocument.SignatureDocumentTemplateId = documentTemplateId.Value;

            origBinaryFileId = signatureDocument.BinaryFileId;
            signatureDocument.BinaryFileId = fuDocument.BinaryFileId;

            if ( !signatureDocument.IsValid )
            {
                // Controls will render the error messages
                return;
            }

            BinaryFileService binaryFileService = new BinaryFileService( rockContext );
            if ( origBinaryFileId.HasValue && origBinaryFileId.Value != signatureDocument.BinaryFileId )
            {
                // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up
                var oldBinaryFile = binaryFileService.Get( origBinaryFileId.Value );
                if ( oldBinaryFile != null && !oldBinaryFile.IsTemporary )
                {
                    oldBinaryFile.IsTemporary = true;
                }
            }

            // ensure the IsTemporary is set to false on binaryFile associated with this document
            if ( signatureDocument.BinaryFileId.HasValue )
            {
                var binaryFile = binaryFileService.Get( signatureDocument.BinaryFileId.Value );
                if ( binaryFile != null && binaryFile.IsTemporary )
                {
                    binaryFile.IsTemporary = false;
                }
            }

            rockContext.SaveChanges();

            if ( inviteCancelled && !string.IsNullOrWhiteSpace( signatureDocument.DocumentKey ) )
            {
                var errorMessages = new List<string>();
                if ( new SignatureDocumentTemplateService( rockContext ).CancelDocument( signatureDocument, out errorMessages ) )
                {
                    rockContext.SaveChanges();
                }
            }

            ReturnToParent();
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="signatureDocument">Type of the defined.</param>
        private void ShowEditDetails( SignatureDocument signatureDocument, bool onlyStatusDetails )
        {
            if ( !onlyStatusDetails )
            {
                string titleName = signatureDocument.SignatureDocumentTemplate != null ? signatureDocument.SignatureDocumentTemplate.Name + " Document" : SignatureDocument.FriendlyTypeName;
                if ( signatureDocument.Id > 0 )
                {
                    lTitle.Text = ActionTitle.Edit( titleName ).FormatAsHtmlTitle();
                }
                else
                {
                    lTitle.Text = ActionTitle.Add( titleName ).FormatAsHtmlTitle();
                }

                btnSend.Visible = signatureDocument.Id > 0 && signatureDocument.Status != SignatureDocumentStatus.Signed;
                btnSend.Text = signatureDocument.Status == SignatureDocumentStatus.Sent ? "Resend Invite" : "Send Invite";

                SetEditMode( true );

                tbName.Text = signatureDocument.Name;

                ppAppliesTo.SetValue( signatureDocument.AppliesToPersonAlias != null ? signatureDocument.AppliesToPersonAlias.Person : null );
                ppAssignedTo.SetValue( signatureDocument.AssignedToPersonAlias != null ? signatureDocument.AssignedToPersonAlias.Person : null );
                ppSignedBy.SetValue( signatureDocument.SignedByPersonAlias != null ? signatureDocument.SignedByPersonAlias.Person : null );

                ddlDocumentType.Visible = signatureDocument.SignatureDocumentTemplate == null;
                ddlDocumentType.SetValue( signatureDocument.SignatureDocumentTemplateId );

                if ( signatureDocument.SignatureDocumentTemplate != null && signatureDocument.SignatureDocumentTemplate.BinaryFileType != null )
                {
                    fuDocument.BinaryFileTypeGuid = signatureDocument.SignatureDocumentTemplate.BinaryFileType.Guid;
                }
                fuDocument.BinaryFileId = signatureDocument.BinaryFileId;
            }

            rbStatus.SelectedValue = signatureDocument.Status.ConvertToInt().ToString();
            hlStatusLastUpdated.Visible = signatureDocument.LastStatusDate.HasValue;
            hlStatusLastUpdated.Text = signatureDocument.LastStatusDate.HasValue ?
                string.Format( "<span title='{0}'>Last Status Update: {1}</span>", signatureDocument.LastStatusDate.Value.ToString(), signatureDocument.LastStatusDate.Value.ToElapsedString() ) :
                string.Empty;

            lDocumentKey.Text = signatureDocument.DocumentKey;
            lDocumentKey.Visible = !string.IsNullOrWhiteSpace( signatureDocument.DocumentKey );

            lRequestDate.Visible = signatureDocument.LastInviteDate.HasValue;
            lRequestDate.Text = signatureDocument.LastInviteDate.HasValue ?
                string.Format( "<span title='{0}'>{1}</span>", signatureDocument.LastInviteDate.Value.ToString(), signatureDocument.LastInviteDate.Value.ToElapsedString() ) :
                string.Empty;
        }
        /// <summary>
        /// Shows the readonly details.
        /// </summary>
        /// <param name="signatureDocument">Type of the defined.</param>
        private void ShowReadonlyDetails( SignatureDocument signatureDocument )
        {
            SetEditMode( false );

            hfSignatureDocumentId.SetValue( signatureDocument.Id );

            lTitle.Text = signatureDocument.Name.FormatAsHtmlTitle();

            var lDetails = new DescriptionList();
            var rDetails = new DescriptionList();

            if ( signatureDocument.BinaryFile != null )
            {
                var getFileUrl = string.Format( "{0}GetFile.ashx?guid={1}", System.Web.VirtualPathUtility.ToAbsolute( "~" ), signatureDocument.BinaryFile.Guid );
                lDetails.Add( "Document", string.Format( "<a href='{0}'>View</a>", getFileUrl ) );
            }

            lDetails.Add( "Document Key", signatureDocument.DocumentKey );

            if ( signatureDocument.LastInviteDate.HasValue )
            {
                lDetails.Add( "Last Request Date", string.Format( "<span title='{0}'>{1}</span>", signatureDocument.LastInviteDate.Value.ToString(), signatureDocument.LastInviteDate.Value.ToElapsedString() ) );
            }

            if ( signatureDocument.AppliesToPersonAlias != null && signatureDocument.AppliesToPersonAlias.Person != null )
            {
                rDetails.Add( "Applies To", signatureDocument.AppliesToPersonAlias.Person.FullName );
            }

            if ( signatureDocument.AssignedToPersonAlias != null && signatureDocument.AssignedToPersonAlias.Person != null )
            {
                rDetails.Add( "Assigned To", signatureDocument.AssignedToPersonAlias.Person.FullName );
            }

            if ( signatureDocument.SignedByPersonAlias != null && signatureDocument.SignedByPersonAlias.Person != null )
            {
                rDetails.Add( "Signed By", signatureDocument.SignedByPersonAlias.Person.FullName );
            }

            if ( signatureDocument.SignatureDocumentTemplate != null )
            {
                lDetails.Add( "Signature Document Type", signatureDocument.SignatureDocumentTemplate.Name );
            }

            lLeftDetails.Text = lDetails.Html;
            lRightDetails.Text = rDetails.Html;
        }
Esempio n. 34
0
        /// <summary>
        /// Resends the document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public override bool ResendDocument( SignatureDocument document, out List<string> errors )
        {
            errors = new List<string>();

            if ( document == null )
            {
                errors.Add( "Invalid Document!" );
            }

            if ( document.AssignedToPersonAlias == null || document.AssignedToPersonAlias.Person == null ||
                string.IsNullOrWhiteSpace( document.AssignedToPersonAlias.Person.Email ) )
            {
                errors.Add( "Invalid Assigned To Person or Email!" );
            }

            if ( errors.Any() )
            {
                return false;
            }

            // Get the access token
            string errorMessage = string.Empty;
            string accessToken = GetAccessToken( false, out errorMessage );
            if ( string.IsNullOrWhiteSpace( accessToken ) )
            {
                errors.Add( errorMessage );
                return false;
            }

            // Get the document to determine the roles (if any) are needed
            JObject getDocumentRes = CudaSign.Document.Get( accessToken, document.DocumentKey );
            errors = ParseErrors( getDocumentRes );
            if ( errors.Any() )
            {
                errorMessage = errors.AsDelimited( "; " );
                return false;
            }

            // Cancel existing invite
            JObject CancelRes = CudaSign.Document.CancelInvite( accessToken, document.DocumentKey );
            errors = ParseErrors( CancelRes );
            if ( errors.Any() )
            {
                return false;
            }

            string orgAbbrev = GlobalAttributesCache.Value( "OrganizationAbbreviation" );
            if ( string.IsNullOrWhiteSpace( orgAbbrev ) )
            {
                orgAbbrev = GlobalAttributesCache.Value( "OrganizationName" );
            }

            string subject = string.Format( "Digital Signature Request from {0}", orgAbbrev );
            string message = string.Format( "{0} has requested a digital signature for a '{1}' document for {2}.",
                GlobalAttributesCache.Value( "OrganizationName" ), document.SignatureDocumentTemplate.Name,
                document.AppliesToPersonAlias != null ? document.AppliesToPersonAlias.Person.FullName : document.AssignedToPersonAlias.Person.FullName );

            dynamic inviteObj = null;
            JArray roles = getDocumentRes.Value<JArray>( "roles" );
            if ( roles != null && roles.Count > 0 )
            {
                var to = new List<dynamic>();
                foreach ( JObject role in roles )
                {
                    to.Add( new
                    {
                        email = document.AssignedToPersonAlias.Person.Email,
                        role_id = string.Empty,
                        role = role.Value<string>( "name" ),
                        order = role.Value<int>( "signing_order" ),
                        expiration_days = 15,
                        reminder = 5
                    } );
                }

                inviteObj = new
                {
                    to = to.ToArray(),
                    from = GetAttributeValue( "Username" ),
                    subject = subject,
                    message = message
                };
            }
            else
            {
                inviteObj = new
                {
                    to = document.AssignedToPersonAlias.Person.Email,
                    from = GetAttributeValue( "Username" ),
                    subject = subject,
                    message = message
                };
            }

            // Send the invite
            JObject inviteRes = CudaSign.Document.Invite( accessToken, document.DocumentKey, inviteObj );
            errors = ParseErrors( inviteRes );
            if ( errors.Any() )
            {
                return false;
            }

            return true;
        }
Esempio n. 35
0
        /// <summary>
        /// Resends the document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public override bool ResendDocument(SignatureDocument document, out List <string> errors)
        {
            errors = new List <string>();

            if (document == null)
            {
                errors.Add("Invalid Document!");
            }

            if (document.AssignedToPersonAlias == null || document.AssignedToPersonAlias.Person == null ||
                string.IsNullOrWhiteSpace(document.AssignedToPersonAlias.Person.Email))
            {
                errors.Add("Invalid Assigned To Person or Email!");
            }

            if (errors.Any())
            {
                return(false);
            }

            // Get the access token
            string errorMessage = string.Empty;
            string accessToken  = GetAccessToken(false, out errorMessage);

            if (string.IsNullOrWhiteSpace(accessToken))
            {
                errors.Add(errorMessage);
                return(false);
            }

            // Get the document to determine the roles (if any) are needed
            JObject getDocumentRes = SignNowSDK.Document.Get(accessToken, document.DocumentKey);

            errors = ParseErrors(getDocumentRes);
            if (errors.Any())
            {
                errorMessage = errors.AsDelimited("; ");
                return(false);
            }

            // Cancel existing invite
            JObject CancelRes = SignNowSDK.Document.CancelInvite(accessToken, document.DocumentKey);

            errors = ParseErrors(CancelRes);
            if (errors.Any())
            {
                return(false);
            }

            string orgAbbrev = GlobalAttributesCache.Value("OrganizationAbbreviation");

            if (string.IsNullOrWhiteSpace(orgAbbrev))
            {
                orgAbbrev = GlobalAttributesCache.Value("OrganizationName");
            }

            string subject = string.Format("Digital Signature Request from {0}", orgAbbrev);
            string message = string.Format("{0} has requested a digital signature for a '{1}' document for {2}.",
                                           GlobalAttributesCache.Value("OrganizationName"), document.SignatureDocumentTemplate.Name,
                                           document.AppliesToPersonAlias != null ? document.AppliesToPersonAlias.Person.FullName : document.AssignedToPersonAlias.Person.FullName);


            dynamic inviteObj = null;
            JArray  roles     = getDocumentRes.Value <JArray>("roles");

            if (roles != null && roles.Count > 0)
            {
                var to = new List <dynamic>();
                foreach (JObject role in roles)
                {
                    to.Add(new
                    {
                        email           = document.AssignedToPersonAlias.Person.Email,
                        role_id         = string.Empty,
                        role            = role.Value <string>("name"),
                        order           = role.Value <int>("signing_order"),
                        expiration_days = 15,
                        reminder        = 5
                    });
                }

                inviteObj = new
                {
                    to      = to.ToArray(),
                    from    = GetAttributeValue("Username"),
                    subject = subject,
                    message = message
                };
            }
            else
            {
                inviteObj = new
                {
                    to      = document.AssignedToPersonAlias.Person.Email,
                    from    = GetAttributeValue("Username"),
                    subject = subject,
                    message = message
                };
            }

            // Send the invite
            JObject inviteRes = SignNowSDK.Document.Invite(accessToken, document.DocumentKey, inviteObj);

            errors = ParseErrors(inviteRes);
            if (errors.Any())
            {
                return(false);
            }

            return(true);
        }
        private void AddSignatureProperties(SignatureDocument sigDocument, SignedSignatureProperties signedSignatureProperties, SignedDataObjectProperties signedDataObjectProperties,
                                            UnsignedSignatureProperties unsignedSignatureProperties, SignatureParameters parameters)
        {
            Cert cert;

            cert = new Cert();
            cert.IssuerSerial.X509IssuerName   = parameters.Signer.Certificate.IssuerName.Name;
            cert.IssuerSerial.X509SerialNumber = parameters.Signer.Certificate.GetSerialNumberAsDecimalString();
            DigestUtil.SetCertDigest(parameters.Signer.Certificate.GetRawCertData(), parameters.DigestMethod, cert.CertDigest);
            signedSignatureProperties.SigningCertificate.CertCollection.Add(cert);

            if (parameters.SignaturePolicyInfo != null)
            {
                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyIdentifier))
                {
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyImplied = false;
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyId.Identifier.IdentifierUri = parameters.SignaturePolicyInfo.PolicyIdentifier;
                }

                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyUri))
                {
                    SigPolicyQualifier spq = new SigPolicyQualifier();
                    spq.AnyXmlElement           = sigDocument.Document.CreateElement(XadesSignedXml.XmlXadesPrefix, "SPURI", XadesSignedXml.XadesNamespaceUri);
                    spq.AnyXmlElement.InnerText = parameters.SignaturePolicyInfo.PolicyUri;

                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyQualifiers.SigPolicyQualifierCollection.Add(spq);
                }

                if (!string.IsNullOrEmpty(parameters.SignaturePolicyInfo.PolicyHash))
                {
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestMethod.Algorithm = parameters.SignaturePolicyInfo.PolicyDigestAlgorithm.URI;
                    signedSignatureProperties.SignaturePolicyIdentifier.SignaturePolicyId.SigPolicyHash.DigestValue            = Convert.FromBase64String(parameters.SignaturePolicyInfo.PolicyHash);
                }
            }

            signedSignatureProperties.SigningTime = parameters.SigningDate.HasValue ? parameters.SigningDate.Value : DateTime.Now;

            if (_dataFormat != null)
            {
                DataObjectFormat newDataObjectFormat = new DataObjectFormat();

                newDataObjectFormat.MimeType    = _dataFormat.MimeType;
                newDataObjectFormat.Encoding    = _dataFormat.Encoding;
                newDataObjectFormat.Description = _dataFormat.Description;
                newDataObjectFormat.ObjectReferenceAttribute = "#" + _refContent.Id;

                if (_dataFormat.ObjectIdentifier != null)
                {
                    newDataObjectFormat.ObjectIdentifier.Identifier.IdentifierUri = _dataFormat.ObjectIdentifier.Identifier.IdentifierUri;
                }

                signedDataObjectProperties.DataObjectFormatCollection.Add(newDataObjectFormat);
            }

            if (parameters.SignerRole != null &&
                (parameters.SignerRole.CertifiedRoles.Count > 0 || parameters.SignerRole.ClaimedRoles.Count > 0))
            {
                signedSignatureProperties.SignerRole = new Microsoft.Xades.SignerRole();

                foreach (X509Certificate certifiedRole in parameters.SignerRole.CertifiedRoles)
                {
                    signedSignatureProperties.SignerRole.CertifiedRoles.CertifiedRoleCollection.Add(new CertifiedRole()
                    {
                        PkiData = certifiedRole.GetRawCertData()
                    });
                }

                foreach (string claimedRole in parameters.SignerRole.ClaimedRoles)
                {
                    signedSignatureProperties.SignerRole.ClaimedRoles.ClaimedRoleCollection.Add(new ClaimedRole()
                    {
                        InnerText = claimedRole
                    });
                }
            }

            foreach (SignatureCommitment signatureCommitment in parameters.SignatureCommitments)
            {
                CommitmentTypeIndication cti = new CommitmentTypeIndication();
                cti.CommitmentTypeId.Identifier.IdentifierUri = signatureCommitment.CommitmentType.URI;
                cti.AllSignedDataObjects = true;

                foreach (XmlElement signatureCommitmentQualifier in signatureCommitment.CommitmentTypeQualifiers)
                {
                    CommitmentTypeQualifier ctq = new CommitmentTypeQualifier();
                    ctq.AnyXmlElement = signatureCommitmentQualifier;

                    cti.CommitmentTypeQualifiers.CommitmentTypeQualifierCollection.Add(ctq);
                }

                signedDataObjectProperties.CommitmentTypeIndicationCollection.Add(cti);
            }

            if (parameters.SignatureProductionPlace != null)
            {
                signedSignatureProperties.SignatureProductionPlace.City            = parameters.SignatureProductionPlace.City;
                signedSignatureProperties.SignatureProductionPlace.StateOrProvince = parameters.SignatureProductionPlace.StateOrProvince;
                signedSignatureProperties.SignatureProductionPlace.PostalCode      = parameters.SignatureProductionPlace.PostalCode;
                signedSignatureProperties.SignatureProductionPlace.CountryName     = parameters.SignatureProductionPlace.CountryName;
            }
        }
Esempio n. 37
0
 /// <summary>
 /// Resends the document.
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="errors">The errors.</param>
 /// <returns></returns>
 public abstract bool ResendDocument( SignatureDocument document, out List<string> errors );
Esempio n. 38
0
 /// <summary>
 /// Gets the invite link.
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="recipient">The recipient.</param>
 /// <param name="errors">The errors.</param>
 /// <returns></returns>
 public abstract string GetInviteLink( SignatureDocument document, Person recipient, out List<string> errors );
Esempio n. 39
0
 /// <summary>
 /// Gets the document.
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="folderPath">The folder path.</param>
 /// <param name="errors">The errors.</param>
 /// <returns></returns>
 public abstract string GetDocument( SignatureDocument document, string folderPath, out List<string> errors );
Esempio n. 40
0
        /// <summary>
        /// Gets the document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="folderPath">The folder path.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public override string GetDocument( SignatureDocument document, string folderPath, out List<string> errors )
        {
            errors = new List<string>();

            if ( document == null )
            {
                errors.Add( "Invalid Document!" );
                return null;
            }

            // Get the access token
            string errorMessage = string.Empty;
            string accessToken = GetAccessToken( false, out errorMessage );
            if ( string.IsNullOrWhiteSpace( accessToken ) )
            {
                errors.Add( errorMessage );
                return null;
            }

            var folder = new DirectoryInfo( folderPath );
            if ( !folder.Exists )
            {
                folder.Create();
            }

            int i = 1;
            string fileName = document.Name;
            while ( File.Exists( Path.Combine( folder.FullName, fileName ) + ".pdf" ) )
            {
                fileName = string.Format( "{0}_{1}", document.Name, i++ );
            }

            string filePath = Path.Combine( folder.FullName, fileName );
            JObject downloadRes = CudaSign.Document.Download( accessToken, document.DocumentKey, filePath, fileName );
            errors = ParseErrors( downloadRes );
            if ( !errors.Any() )
            {
                return downloadRes.Value<string>( "file" );
            }

            return null;
        }
Esempio n. 41
0
 /// <summary>
 /// Updates the document status
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="errors">The errors.</param>
 /// <returns></returns>
 public abstract bool UpdateDocumentStatus( SignatureDocument document, out List<string> errors );
 /// <summary>
 /// Sends the document.
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="alternateEmail">The alternate email.</param>
 /// <param name="errorMessages">The error messages.</param>
 /// <returns></returns>
 public bool SendDocument( SignatureDocument document, string alternateEmail, out List<string> errorMessages )
 {
     return SendDocument( document, null, null, null, string.Empty, alternateEmail, out errorMessages );
 }
Esempio n. 43
0
        /// <summary>
        /// updates the document status
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public override bool UpdateDocumentStatus( SignatureDocument document, out List<string> errors )
        {
            errors = new List<string>();

            if ( document == null )
            {
                errors.Add( "Invalid Document!" );
                return false;
            }

            // Get the access token
            string errorMessage = string.Empty;
            string accessToken = GetAccessToken( false, out errorMessage );
            if ( string.IsNullOrWhiteSpace( accessToken ) )
            {
                errors.Add( errorMessage );
                return false;
            }

            // Get the document to determine the roles (if any) are needed
            JObject getDocumentRes = CudaSign.Document.Get( accessToken, document.DocumentKey );
            errors = ParseErrors( getDocumentRes );
            if ( errors.Any() )
            {
                errorMessage = errors.AsDelimited( "; " );
                return false;
            }
            JArray signatures = getDocumentRes.Value<JArray>( "signatures" );
            if ( signatures != null && signatures.Count > 0 )
            {
                document.Status = SignatureDocumentStatus.Signed;
            }
            else
            {
                JArray invites = getDocumentRes.Value<JArray>( "field_invites" );
                if ( invites != null )
                {
                    foreach( JObject invite in invites )
                    {
                        string inviteStatus = invite.Value<string>( "status" );
                        if ( inviteStatus == "expired" )
                        {
                            document.Status = SignatureDocumentStatus.Expired;
                            break;
                        }
                    }
                }
            }

            return true;
        }
Esempio n. 44
0
        /// <summary>
        /// Saves the registration.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="hasPayment">if set to <c>true</c> [has payment].</param>
        /// <returns></returns>
        private Registration SaveRegistration( RockContext rockContext, bool hasPayment )
        {
            var registrationService = new RegistrationService( rockContext );
            var registrantService = new RegistrationRegistrantService( rockContext );
            var registrantFeeService = new RegistrationRegistrantFeeService( rockContext );
            var personService = new PersonService( rockContext );
            var groupService = new GroupService( rockContext );
            var documentService = new SignatureDocumentService( rockContext );

            // variables to keep track of the family that new people should be added to
            int? singleFamilyId = null;
            var multipleFamilyGroupIds = new Dictionary<Guid, int>();

            var dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
            var dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );
            var familyGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY );
            var adultRoleId = familyGroupType.Roles
                .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) )
                .Select( r => r.Id )
                .FirstOrDefault();
            var childRoleId = familyGroupType.Roles
                .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid() ) )
                .Select( r => r.Id )
                .FirstOrDefault();

            bool newRegistration = false;
            Registration registration = null;
            Person registrar = null;
            var registrationChanges = new List<string>();

            if ( RegistrationState.RegistrationId.HasValue )
            {
                registration = registrationService.Get( RegistrationState.RegistrationId.Value );
            }

            if ( registration == null )
            {
                newRegistration = true;
                registration = new Registration();
                registrationService.Add( registration );
                registrationChanges.Add( "Created Registration" );
            }
            else
            {
                if ( registration.PersonAlias != null && registration.PersonAlias.Person != null )
                {
                    registrar = registration.PersonAlias.Person;
                }
            }

            registration.RegistrationInstanceId = RegistrationInstanceState.Id;

            // If the Registration Instance linkage specified a group, load it now
            Group group = null;
            if ( GroupId.HasValue )
            {
                group = new GroupService( rockContext ).Get( GroupId.Value );
                if ( group != null && ( !registration.GroupId.HasValue || registration.GroupId.Value != group.Id ) )
                {
                    registration.GroupId = group.Id;
                    History.EvaluateChange( registrationChanges, "Group", string.Empty, group.Name );
                }
            }

            bool newRegistrar = newRegistration ||
                registration.FirstName == null || !registration.FirstName.Equals( RegistrationState.FirstName, StringComparison.OrdinalIgnoreCase ) ||
                registration.LastName == null || !registration.LastName.Equals( RegistrationState.LastName, StringComparison.OrdinalIgnoreCase );

            History.EvaluateChange( registrationChanges, "First Name", registration.FirstName, RegistrationState.FirstName );
            registration.FirstName = RegistrationState.FirstName;

            History.EvaluateChange( registrationChanges, "Last Name", registration.LastName, RegistrationState.LastName );
            registration.LastName = RegistrationState.LastName;

            History.EvaluateChange( registrationChanges, "Confirmation Email", registration.ConfirmationEmail, RegistrationState.ConfirmationEmail );
            registration.ConfirmationEmail = RegistrationState.ConfirmationEmail;

            History.EvaluateChange( registrationChanges, "Discount Code", registration.DiscountCode, RegistrationState.DiscountCode );
            registration.DiscountCode = RegistrationState.DiscountCode;

            History.EvaluateChange( registrationChanges, "Discount Percentage", registration.DiscountPercentage, RegistrationState.DiscountPercentage );
            registration.DiscountPercentage = RegistrationState.DiscountPercentage;

            History.EvaluateChange( registrationChanges, "Discount Amount", registration.DiscountAmount, RegistrationState.DiscountAmount );
            registration.DiscountAmount = RegistrationState.DiscountAmount;

            if ( newRegistrar )
            {
                // Businesses have no first name.  This resolves null reference issues downstream.
                if ( CurrentPerson != null && CurrentPerson.FirstName == null )
                {
                    CurrentPerson.FirstName = "";
                }

                if ( CurrentPerson != null && CurrentPerson.NickName == null )
                {
                    CurrentPerson.NickName = CurrentPerson.FirstName;
                }

                // If the 'your name' value equals the currently logged in person, use their person alias id
                if ( CurrentPerson != null &&
                ( CurrentPerson.NickName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) ||
                    CurrentPerson.FirstName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) ) &&
                CurrentPerson.LastName.Trim().Equals( registration.LastName.Trim(), StringComparison.OrdinalIgnoreCase ) )
                {
                    registrar = CurrentPerson;
                    registration.PersonAliasId = CurrentPerson.PrimaryAliasId;

                    // If email that logged in user used is different than their stored email address, update their stored value
                    if ( !string.IsNullOrWhiteSpace( registration.ConfirmationEmail ) &&
                        !registration.ConfirmationEmail.Trim().Equals( CurrentPerson.Email.Trim(), StringComparison.OrdinalIgnoreCase ) &&
                        ( !cbUpdateEmail.Visible || cbUpdateEmail.Checked ) )
                    {
                        var person = personService.Get( CurrentPerson.Id );
                        if ( person != null )
                        {
                            var personChanges = new List<string>();
                            History.EvaluateChange( personChanges, "Email", person.Email, registration.ConfirmationEmail );
                            person.Email = registration.ConfirmationEmail;

                            HistoryService.SaveChanges(
                                new RockContext(),
                                typeof( Person ),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                person.Id,
                                personChanges, true, CurrentPersonAliasId );
                        }
                    }
                }
                else
                {
                    // otherwise look for one and one-only match by name/email
                    var personMatches = personService.GetByMatch( registration.FirstName, registration.LastName, registration.ConfirmationEmail );
                    if ( personMatches.Count() == 1 )
                    {
                        registrar = personMatches.First();
                        registration.PersonAliasId = registrar.PrimaryAliasId;
                    }
                    else
                    {
                        registrar = null;
                        registration.PersonAlias = null;
                        registration.PersonAliasId = null;
                    }
                }
            }

            // Set the family guid for any other registrants that were selected to be in the same family
            if ( registrar != null )
            {
                var family = registrar.GetFamilies( rockContext ).FirstOrDefault();
                if ( family != null )
                {
                    multipleFamilyGroupIds.AddOrIgnore( RegistrationState.FamilyGuid, family.Id );
                    if ( !singleFamilyId.HasValue )
                    {
                        singleFamilyId = family.Id;
                    }
                }
            }

            // Make sure there's an actual person associated to registration
            if ( !registration.PersonAliasId.HasValue )
            {
                // If a match was not found, create a new person
                var person = new Person();
                person.FirstName = registration.FirstName;
                person.LastName = registration.LastName;
                person.IsEmailActive = true;
                person.Email = registration.ConfirmationEmail;
                person.EmailPreference = EmailPreference.EmailAllowed;
                person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                if ( dvcConnectionStatus != null )
                {
                    person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                }
                if ( dvcRecordStatus != null )
                {
                    person.RecordStatusValueId = dvcRecordStatus.Id;
                }

                registrar = SavePerson( rockContext, person, RegistrationState.FamilyGuid, CampusId, null, adultRoleId, childRoleId, multipleFamilyGroupIds, ref singleFamilyId );
                registration.PersonAliasId = registrar != null ? registrar.PrimaryAliasId : (int?)null;

                History.EvaluateChange( registrationChanges, "Registrar", string.Empty, registrar.FullName );
            }
            else
            {
                if ( newRegistration )
                {
                    History.EvaluateChange( registrationChanges, "Registrar", string.Empty, registration.ToString() );
                }

            }

            // if this registration was marked as temporary (started from another page, then specified in the url), set IsTemporary to False now that we are done
            if ( registration.IsTemporary )
            {
                registration.IsTemporary = false;
            }

            // Save the registration ( so we can get an id )
            rockContext.SaveChanges();
            RegistrationState.RegistrationId = registration.Id;

            try
            {

                Task.Run( () =>
                    HistoryService.SaveChanges(
                        new RockContext(),
                        typeof( Registration ),
                        Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(),
                        registration.Id,
                        registrationChanges, true, CurrentPersonAliasId )
                );

                // Get each registrant
                foreach ( var registrantInfo in RegistrationState.Registrants.ToList() )
                {
                    var registrantChanges = new List<string>();
                    var personChanges = new List<string>();
                    var familyChanges = new List<string>();

                    RegistrationRegistrant registrant = null;
                    Person person = null;

                    string firstName = registrantInfo.GetFirstName( RegistrationTemplate );
                    string lastName = registrantInfo.GetLastName( RegistrationTemplate );
                    string email = registrantInfo.GetEmail( RegistrationTemplate );

                    if ( registrantInfo.Id > 0 )
                    {
                        registrant = registration.Registrants.FirstOrDefault( r => r.Id == registrantInfo.Id );
                        if ( registrant != null )
                        {
                            person = registrant.Person;
                            if ( person != null && (
                                ( registrant.Person.FirstName.Equals( firstName, StringComparison.OrdinalIgnoreCase ) || registrant.Person.NickName.Equals( firstName, StringComparison.OrdinalIgnoreCase ) ) &&
                                registrant.Person.LastName.Equals( lastName, StringComparison.OrdinalIgnoreCase ) ) )
                            {
                                //
                            }
                            else
                            {
                                person = null;
                                registrant.PersonAlias = null;
                                registrant.PersonAliasId = null;
                            }
                        }
                    }
                    else
                    {
                        if ( registrantInfo.PersonId.HasValue && RegistrationTemplate.ShowCurrentFamilyMembers )
                        {
                            person = personService.Get( registrantInfo.PersonId.Value );
                        }
                    }

                    if ( person == null )
                    {
                        // Try to find a matching person based on name and email address
                        var personMatches = personService.GetByMatch( firstName, lastName, email );
                        if ( personMatches.Count() == 1 )
                        {
                            person = personMatches.First();
                        }

                        // Try to find a matching person based on name within same family as registrar
                        if ( person == null && registrar != null && registrantInfo.FamilyGuid == RegistrationState.FamilyGuid )
                        {
                            var familyMembers = registrar.GetFamilyMembers( true, rockContext )
                                .Where( m =>
                                    ( m.Person.FirstName == firstName || m.Person.NickName == firstName ) &&
                                    m.Person.LastName == lastName )
                                .Select( m => m.Person )
                                .ToList();

                            if ( familyMembers.Count() == 1 )
                            {
                                person = familyMembers.First();
                                if ( !string.IsNullOrWhiteSpace( email ) )
                                {
                                    person.Email = email;
                                }
                            }

                            if ( familyMembers.Count() > 1 && !string.IsNullOrWhiteSpace( email ) )
                            {
                                familyMembers = familyMembers
                                    .Where( m =>
                                        m.Email != null &&
                                        m.Email.Equals( email, StringComparison.OrdinalIgnoreCase ) )
                                    .ToList();
                                if ( familyMembers.Count() == 1 )
                                {
                                    person = familyMembers.First();
                                }
                            }
                        }
                    }

                    if ( person == null )
                    {
                        // If a match was not found, create a new person
                        person = new Person();
                        person.FirstName = firstName;
                        person.LastName = lastName;
                        person.IsEmailActive = true;
                        person.Email = email;
                        person.EmailPreference = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                        if ( dvcConnectionStatus != null )
                        {
                            person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                        }

                        if ( dvcRecordStatus != null )
                        {
                            person.RecordStatusValueId = dvcRecordStatus.Id;
                        }
                    }

                    int? campusId = CampusId;
                    Location location = null;

                    // Set any of the template's person fields
                    foreach ( var field in RegistrationTemplate.Forms
                        .SelectMany( f => f.Fields
                            .Where( t => t.FieldSource == RegistrationFieldSource.PersonField ) ) )
                    {
                        // Find the registrant's value
                        var fieldValue = registrantInfo.FieldValues
                            .Where( f => f.Key == field.Id )
                            .Select( f => f.Value.FieldValue )
                            .FirstOrDefault();

                        if ( fieldValue != null )
                        {
                            switch ( field.PersonFieldType )
                            {
                                case RegistrationPersonFieldType.Campus:
                                    {
                                        if ( fieldValue != null )
                                        {
                                            campusId = fieldValue.ToString().AsIntegerOrNull();
                                        }
                                        break;
                                    }

                                case RegistrationPersonFieldType.Address:
                                    {
                                        location = fieldValue as Location;
                                        break;
                                    }

                                case RegistrationPersonFieldType.Birthdate:
                                    {
                                        var birthMonth = person.BirthMonth;
                                        var birthDay = person.BirthDay;
                                        var birthYear = person.BirthYear;

                                        person.SetBirthDate( fieldValue as DateTime? );

                                        History.EvaluateChange( personChanges, "Birth Month", birthMonth, person.BirthMonth );
                                        History.EvaluateChange( personChanges, "Birth Day", birthDay, person.BirthDay );
                                        History.EvaluateChange( personChanges, "Birth Year", birthYear, person.BirthYear );

                                        break;
                                    }

                                case RegistrationPersonFieldType.Grade:
                                    {
                                        var newGraduationYear = fieldValue.ToString().AsIntegerOrNull();
                                        History.EvaluateChange( personChanges, "Graduation Year", person.GraduationYear, newGraduationYear );
                                        person.GraduationYear = newGraduationYear;

                                        break;
                                    }

                                case RegistrationPersonFieldType.Gender:
                                    {
                                        var newGender = fieldValue.ToString().ConvertToEnumOrNull<Gender>() ?? Gender.Unknown;
                                        History.EvaluateChange( personChanges, "Gender", person.Gender, newGender );
                                        person.Gender = newGender;
                                        break;
                                    }

                                case RegistrationPersonFieldType.MaritalStatus:
                                    {
                                        if ( fieldValue != null )
                                        {
                                            int? newMaritalStatusId = fieldValue.ToString().AsIntegerOrNull();
                                            History.EvaluateChange( personChanges, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) );
                                            person.MaritalStatusValueId = newMaritalStatusId;
                                        }
                                        break;
                                    }

                                case RegistrationPersonFieldType.MobilePhone:
                                    {
                                        SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), personChanges );
                                        break;
                                    }

                                case RegistrationPersonFieldType.HomePhone:
                                    {
                                        SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), personChanges );
                                        break;
                                    }

                                case RegistrationPersonFieldType.WorkPhone:
                                    {
                                        SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK.AsGuid(), personChanges );
                                        break;
                                    }
                            }
                        }
                    }

                    // Save the person ( and family if needed )
                    SavePerson( rockContext, person, registrantInfo.FamilyGuid, campusId, location, adultRoleId, childRoleId, multipleFamilyGroupIds, ref singleFamilyId );

                    // Load the person's attributes
                    person.LoadAttributes();

                    // Set any of the template's person fields
                    foreach ( var field in RegistrationTemplate.Forms
                        .SelectMany( f => f.Fields
                            .Where( t =>
                                t.FieldSource == RegistrationFieldSource.PersonAttribute &&
                                t.AttributeId.HasValue ) ) )
                    {
                        // Find the registrant's value
                        var fieldValue = registrantInfo.FieldValues
                            .Where( f => f.Key == field.Id )
                            .Select( f => f.Value.FieldValue )
                            .FirstOrDefault();

                        if ( fieldValue != null )
                        {
                            var attribute = AttributeCache.Read( field.AttributeId.Value );
                            if ( attribute != null )
                            {
                                string originalValue = person.GetAttributeValue( attribute.Key );
                                string newValue = fieldValue.ToString();
                                person.SetAttributeValue( attribute.Key, fieldValue.ToString() );

                                // DateTime values must be stored in ISO8601 format as http://www.rockrms.com/Rock/Developer/BookContent/16/16#datetimeformatting
                                if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE.AsGuid() ) ||
                                    attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE_TIME.AsGuid() ) )
                                {
                                    DateTime aDateTime;
                                    if ( DateTime.TryParse( newValue, out aDateTime ) )
                                    {
                                        newValue = aDateTime.ToString( "o" );
                                    }
                                }

                                if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() )
                                {
                                    string formattedOriginalValue = string.Empty;
                                    if ( !string.IsNullOrWhiteSpace( originalValue ) )
                                    {
                                        formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false );
                                    }

                                    string formattedNewValue = string.Empty;
                                    if ( !string.IsNullOrWhiteSpace( newValue ) )
                                    {
                                        formattedNewValue = attribute.FieldType.Field.FormatValue( null, newValue, attribute.QualifierValues, false );
                                    }

                                    Helper.SaveAttributeValue( person, attribute, newValue, rockContext );
                                    History.EvaluateChange( personChanges, attribute.Name, formattedOriginalValue, formattedNewValue );

                                }
                            }
                        }
                    }

                    string registrantName = person.FullName + ": ";

                    personChanges.ForEach( c => registrantChanges.Add( c ) );

                    if ( registrant == null )
                    {
                        registrant = new RegistrationRegistrant();
                        registrant.Guid = registrantInfo.Guid;
                        registrantService.Add( registrant );
                        registrant.RegistrationId = registration.Id;
                    }

                    registrant.OnWaitList = registrantInfo.OnWaitList;
                    registrant.PersonAliasId = person.PrimaryAliasId;
                    registrant.Cost = registrantInfo.Cost;
                    registrant.DiscountApplies = registrantInfo.DiscountApplies;

                    // Remove fees
                    // Remove/delete any registrant fees that are no longer in UI with quantity
                    foreach ( var dbFee in registrant.Fees.ToList() )
                    {
                        if ( !registrantInfo.FeeValues.Keys.Contains( dbFee.RegistrationTemplateFeeId ) ||
                            registrantInfo.FeeValues[dbFee.RegistrationTemplateFeeId] == null ||
                            !registrantInfo.FeeValues[dbFee.RegistrationTemplateFeeId]
                                .Any( f =>
                                    f.Option == dbFee.Option &&
                                    f.Quantity > 0 ) )
                        {
                            registrantChanges.Add( string.Format( "Removed '{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}",
                                dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option ) );

                            registrant.Fees.Remove( dbFee );
                            registrantFeeService.Delete( dbFee );
                        }
                    }

                    // Add or Update fees
                    foreach ( var uiFee in registrantInfo.FeeValues.Where( f => f.Value != null ) )
                    {
                        foreach ( var uiFeeOption in uiFee.Value )
                        {
                            var dbFee = registrant.Fees
                                .Where( f =>
                                    f.RegistrationTemplateFeeId == uiFee.Key &&
                                    f.Option == uiFeeOption.Option )
                                .FirstOrDefault();

                            if ( dbFee == null )
                            {
                                dbFee = new RegistrationRegistrantFee();
                                dbFee.RegistrationTemplateFeeId = uiFee.Key;
                                dbFee.Option = uiFeeOption.Option;
                                registrant.Fees.Add( dbFee );
                            }

                            var templateFee = dbFee.RegistrationTemplateFee;
                            if ( templateFee == null )
                            {
                                templateFee = RegistrationTemplate.Fees.Where( f => f.Id == uiFee.Key ).FirstOrDefault();
                            }

                            string feeName = templateFee != null ? templateFee.Name : "Fee";
                            if ( !string.IsNullOrWhiteSpace( uiFeeOption.Option ) )
                            {
                                feeName = string.Format( "{0} ({1})", feeName, uiFeeOption.Option );
                            }

                            if ( dbFee.Id <= 0 )
                            {
                                registrantChanges.Add( feeName + " Fee Added" );
                            }

                            History.EvaluateChange( registrantChanges, feeName + " Quantity", dbFee.Quantity, uiFeeOption.Quantity );
                            dbFee.Quantity = uiFeeOption.Quantity;

                            History.EvaluateChange( registrantChanges, feeName + " Cost", dbFee.Cost, uiFeeOption.Cost );
                            dbFee.Cost = uiFeeOption.Cost;
                        }
                    }

                    rockContext.SaveChanges();
                    registrantInfo.Id = registrant.Id;

                    // Set any of the templat's registrant attributes
                    registrant.LoadAttributes();
                    foreach ( var field in RegistrationTemplate.Forms
                        .SelectMany( f => f.Fields
                            .Where( t =>
                                t.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                t.AttributeId.HasValue ) ) )
                    {
                        // Find the registrant's value
                        var fieldValue = registrantInfo.FieldValues
                            .Where( f => f.Key == field.Id )
                            .Select( f => f.Value.FieldValue )
                            .FirstOrDefault();

                        if ( fieldValue != null )
                        {
                            var attribute = AttributeCache.Read( field.AttributeId.Value );
                            if ( attribute != null )
                            {
                                string originalValue = registrant.GetAttributeValue( attribute.Key );
                                string newValue = fieldValue.ToString();
                                registrant.SetAttributeValue( attribute.Key, fieldValue.ToString() );

                                // DateTime values must be stored in ISO8601 format as http://www.rockrms.com/Rock/Developer/BookContent/16/16#datetimeformatting
                                if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE.AsGuid() ) ||
                                    attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE_TIME.AsGuid() ) )
                                {
                                    DateTime aDateTime;
                                    if ( DateTime.TryParse( fieldValue.ToString(), out aDateTime ) )
                                    {
                                        newValue = aDateTime.ToString( "o" );
                                    }
                                }

                                if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() )
                                {
                                    string formattedOriginalValue = string.Empty;
                                    if ( !string.IsNullOrWhiteSpace( originalValue ) )
                                    {
                                        formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false );
                                    }

                                    string formattedNewValue = string.Empty;
                                    if ( !string.IsNullOrWhiteSpace( newValue ) )
                                    {
                                        formattedNewValue = attribute.FieldType.Field.FormatValue( null, newValue, attribute.QualifierValues, false );
                                    }

                                    Helper.SaveAttributeValue( registrant, attribute, newValue, rockContext );
                                    History.EvaluateChange( registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue );
                                }
                            }
                        }
                    }

                    Task.Run( () =>
                        HistoryService.SaveChanges(
                            new RockContext(),
                            typeof( Registration ),
                            Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(),
                            registration.Id,
                            registrantChanges,
                            "Registrant: " + person.FullName,
                            null, null, true, CurrentPersonAliasId )
                    );

                    // Clear this registran't family guid so it's not updated again
                    registrantInfo.FamilyGuid = Guid.Empty;

                    // Save the signed document
                    try
                    {
                        if ( RegistrationTemplate.RequiredSignatureDocumentTemplateId.HasValue && !string.IsNullOrWhiteSpace( registrantInfo.SignatureDocumentKey ) )
                        {
                            var document = new SignatureDocument();
                            document.SignatureDocumentTemplateId = RegistrationTemplate.RequiredSignatureDocumentTemplateId.Value;
                            document.DocumentKey = registrantInfo.SignatureDocumentKey;
                            document.Name = string.Format( "{0}_{1}", RegistrationInstanceState.Name.RemoveSpecialCharacters(), person.FullName.RemoveSpecialCharacters() ); ;
                            document.AppliesToPersonAliasId = person.PrimaryAliasId;
                            document.AssignedToPersonAliasId = registrar.PrimaryAliasId;
                            document.SignedByPersonAliasId = registrar.PrimaryAliasId;
                            document.Status = SignatureDocumentStatus.Signed;
                            document.LastInviteDate = registrantInfo.SignatureDocumentLastSent;
                            document.LastStatusDate = registrantInfo.SignatureDocumentLastSent;
                            documentService.Add( document );
                            rockContext.SaveChanges();

                            var updateDocumentTxn = new Rock.Transactions.UpdateDigitalSignatureDocumentTransaction( document.Id );
                            Rock.Transactions.RockQueue.TransactionQueue.Enqueue( updateDocumentTxn );
                        }
                    }
                    catch( System.Exception ex )
                    {
                        ExceptionLogService.LogException( ex, Context, this.RockPage.PageId, this.RockPage.Site.Id, CurrentPersonAlias );
                    }
                }

                rockContext.SaveChanges();

            }

            catch ( Exception ex )
            {
                using ( var newRockContext = new RockContext() )
                {
                    if ( newRegistration )
                    {
                        var newRegistrationService = new RegistrationService( newRockContext );
                        var savedRegistration = new RegistrationService( newRockContext ).Get( registration.Id );
                        if ( savedRegistration != null )
                        {
                            HistoryService.DeleteChanges( newRockContext, typeof( Registration ), savedRegistration.Id );

                            newRegistrationService.Delete( savedRegistration );
                            newRockContext.SaveChanges();
                        }
                    }
                }

                throw ex;
            }

            return registration;
        }
        /// <summary>
        /// Sends the invite.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="component">The component.</param>
        /// <param name="document">The document.</param>
        /// <param name="person">The person.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        private bool SendInvite( RockContext rockContext, DigitalSignatureComponent component, SignatureDocument document, Person person, out List<string> errors )
        {
            errors = new List<string>();
            if ( document != null &&
                document.SignatureDocumentTemplate != null &&
                document.SignatureDocumentTemplate.InviteSystemEmailId.HasValue &&
                person != null &&
                !string.IsNullOrWhiteSpace( person.Email ) )
            {
                string inviteLink = component.GetInviteLink( document, person, out errors );
                if ( !errors.Any() )
                {
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( null, person );
                    mergeFields.Add( "SignatureDocument", document );
                    mergeFields.Add( "InviteLink", inviteLink );

                    var recipients = new List<RecipientData>();
                    recipients.Add( new RecipientData( person.Email, mergeFields ) );

                    var systemEmail = new SystemEmailService( rockContext ).Get( document.SignatureDocumentTemplate.InviteSystemEmailId.Value );
                    if ( systemEmail != null )
                    {
                        var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read( rockContext ).GetValue( "InternalApplicationRoot" );
                        Email.Send( systemEmail.Guid, recipients, appRoot, string.Empty, false );
                    }
                }
                else
                {
                    return false;
                }
            }

            return true;
        }
        /// <summary>
        /// Sends the document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="signatureDocumentTemplate">Type of the signature document.</param>
        /// <param name="appliesToPerson">The person.</param>
        /// <param name="assignedToPerson">The assigned to person.</param>
        /// <param name="documentName">Name of the document.</param>
        /// <param name="alternateEmail">The alternate email.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        private bool SendDocument( SignatureDocument document, SignatureDocumentTemplate signatureDocumentTemplate, Person appliesToPerson, Person assignedToPerson, string documentName, string alternateEmail, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            // If document was passed and other values were not, set them from the document
            if ( document != null )
            {
                signatureDocumentTemplate = signatureDocumentTemplate ?? document.SignatureDocumentTemplate;
                if ( document.AppliesToPersonAlias != null && document.AppliesToPersonAlias.Person != null )
                {
                    appliesToPerson = appliesToPerson ?? document.AppliesToPersonAlias.Person;
                }
                if ( document.AssignedToPersonAlias != null && document.AssignedToPersonAlias.Person != null )
                {
                    assignedToPerson = assignedToPerson ?? document.AppliesToPersonAlias.Person;
                    alternateEmail = !string.IsNullOrWhiteSpace( alternateEmail ) ? alternateEmail : document.AppliesToPersonAlias.Person.Email;
                }

                documentName = !string.IsNullOrWhiteSpace( documentName ) ? documentName : document.Name;
            }

            if ( signatureDocumentTemplate == null )
            {
                errorMessages.Add( "Invalid Document Type." );
            }

            if ( appliesToPerson == null )
            {
                errorMessages.Add( "Invalid Applies To Person." );
            }

            if ( assignedToPerson == null )
            {
                errorMessages.Add( "Invalid Assigned To Person." );
            }

            if ( !errorMessages.Any() )
            {
                var provider = DigitalSignatureContainer.GetComponent( signatureDocumentTemplate.ProviderEntityType.Name );
                if ( provider == null || !provider.IsActive )
                {
                    errorMessages.Add( "Digital Signature provider was not found or is not active." );
                }
                else
                {
                    string email = string.IsNullOrWhiteSpace( alternateEmail ) ? assignedToPerson.Email : alternateEmail;
                    if ( string.IsNullOrWhiteSpace( email ) )
                    {
                        errorMessages.Add( string.Format( "There is no email address for {0}.", assignedToPerson.FullName ) );
                    }
                    else
                    {
                        var sendErrors = new List<string>();

                        var rockContext = this.Context as RockContext;
                        var documentService = new SignatureDocumentService( rockContext );

                        if ( document == null )
                        {
                            document = documentService.Queryable()
                                .Where( d =>
                                    d.SignatureDocumentTemplateId == signatureDocumentTemplate.Id &&
                                    d.AppliesToPersonAlias.PersonId == appliesToPerson.Id &&
                                    d.AssignedToPersonAlias.PersonId == assignedToPerson.Id &&
                                    d.Status != SignatureDocumentStatus.Signed )
                                .OrderByDescending( d => d.CreatedDateTime )
                                .FirstOrDefault();
                        }

                        string documentKey = string.Empty;
                        if ( document == null || string.IsNullOrWhiteSpace( documentKey ) )
                        {
                            documentKey = provider.CreateDocument( signatureDocumentTemplate, appliesToPerson, assignedToPerson, documentName, out sendErrors, true );
                        }
                        else
                        {
                            documentKey = document.DocumentKey;
                            provider.ResendDocument( document, out sendErrors );
                        }

                        if ( document == null )
                        {
                            document = new SignatureDocument();
                            document.SignatureDocumentTemplate = signatureDocumentTemplate;
                            document.SignatureDocumentTemplateId = signatureDocumentTemplate.Id;
                            document.Name = documentName;
                            document.AppliesToPersonAliasId = appliesToPerson.PrimaryAliasId;
                            document.AssignedToPersonAliasId = assignedToPerson.PrimaryAliasId;
                            documentService.Add( document );
                        }

                        if ( !sendErrors.Any() )
                        {
                            document.DocumentKey = documentKey;
                            document.LastInviteDate = RockDateTime.Now;
                            document.InviteCount = document.InviteCount + 1;
                            if ( document.Status != SignatureDocumentStatus.Sent )
                            {
                                document.LastStatusDate = document.LastInviteDate;
                            }
                            document.Status = SignatureDocumentStatus.Sent;

                            return true;
                        }
                        else
                        {
                            errorMessages.AddRange( sendErrors );
                        }
                    }
                }
            }

            return false;
        }
Esempio n. 47
0
        private void SaveGroupMember()
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();

                // Verify valid group
                var groupService = new GroupService( rockContext );
                var group = groupService.Get( hfGroupId.ValueAsInt() );
                if ( group == null )
                {
                    nbErrorMessage.Title = "Please select a Role";
                    return;
                }

                // Check to see if a person was selected
                int? personId = ppGroupMemberPerson.PersonId;
                int? personAliasId = ppGroupMemberPerson.PersonAliasId;
                if ( !personId.HasValue || !personAliasId.HasValue )
                {
                    nbErrorMessage.Title = "Please select a Person";
                    return;
                }

                // check to see if the user selected a role
                var role = new GroupTypeRoleService( rockContext ).Get( ddlGroupRole.SelectedValueAsInt() ?? 0 );
                if ( role == null )
                {
                    nbErrorMessage.Title = "Please select a Role";
                    return;
                }

                var groupMemberService = new GroupMemberService( rockContext );
                var groupMemberRequirementService = new GroupMemberRequirementService( rockContext );
                GroupMember groupMember;

                int groupMemberId = int.Parse( hfGroupMemberId.Value );

                // if adding a new group member
                if ( groupMemberId.Equals( 0 ) )
                {
                    groupMember = new GroupMember { Id = 0 };
                    groupMember.GroupId = group.Id;
                }
                else
                {
                    // load existing group member
                    groupMember = groupMemberService.Get( groupMemberId );
                }

                groupMember.PersonId = personId.Value;
                groupMember.GroupRoleId = role.Id;
                groupMember.Note = tbNote.Text;
                groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum<GroupMemberStatus>();

                if ( cbIsNotified.Visible )
                {
                    groupMember.IsNotified = cbIsNotified.Checked;
                }

                if ( pnlRequirements.Visible )
                {
                    foreach ( var checkboxItem in cblManualRequirements.Items.OfType<ListItem>() )
                    {
                        int groupRequirementId = checkboxItem.Value.AsInteger();
                        var groupMemberRequirement = groupMember.GroupMemberRequirements.FirstOrDefault( a => a.GroupRequirementId == groupRequirementId );
                        bool metRequirement = checkboxItem.Selected;
                        if ( metRequirement )
                        {
                            if ( groupMemberRequirement == null )
                            {
                                groupMemberRequirement = new GroupMemberRequirement();
                                groupMemberRequirement.GroupRequirementId = groupRequirementId;

                                groupMember.GroupMemberRequirements.Add( groupMemberRequirement );
                            }

                            // set the RequirementMetDateTime if it hasn't been set already
                            groupMemberRequirement.RequirementMetDateTime = groupMemberRequirement.RequirementMetDateTime ?? RockDateTime.Now;

                            groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now;
                        }
                        else
                        {
                            if ( groupMemberRequirement != null )
                            {
                                // doesn't meets the requirement
                                groupMemberRequirement.RequirementMetDateTime = null;
                                groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now;
                            }
                        }
                    }
                }

                if ( group.RequiredSignatureDocumentTemplate != null )
                {
                    var person = new PersonService( rockContext ).Get( personId.Value );

                    var documentService = new SignatureDocumentService( rockContext );
                    var binaryFileService = new BinaryFileService( rockContext );
                    SignatureDocument document = null;

                    int? signatureDocumentId = hfSignedDocumentId.Value.AsIntegerOrNull();
                    int? binaryFileId = fuSignedDocument.BinaryFileId;
                    if ( signatureDocumentId.HasValue )
                    {
                        document = documentService.Get( signatureDocumentId.Value );
                    }

                    if ( document == null && binaryFileId.HasValue )
                    {
                        document = new SignatureDocument();
                        document.SignatureDocumentTemplateId = group.RequiredSignatureDocumentTemplate.Id;
                        document.AppliesToPersonAliasId = personAliasId.Value;
                        document.AssignedToPersonAliasId = personAliasId.Value;
                        document.Name = string.Format( "{0}_{1}",
                            group.Name.RemoveSpecialCharacters(),
                            ( person != null ? person.FullName.RemoveSpecialCharacters() : string.Empty ) );
                        document.Status = SignatureDocumentStatus.Signed;
                        document.LastStatusDate = RockDateTime.Now;
                        documentService.Add( document );
                    }

                    if ( document != null )
                    {
                        int? origBinaryFileId = document.BinaryFileId;
                        document.BinaryFileId = binaryFileId;

                        if ( origBinaryFileId.HasValue && origBinaryFileId.Value != document.BinaryFileId )
                        {
                            // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up
                            var oldBinaryFile = binaryFileService.Get( origBinaryFileId.Value );
                            if ( oldBinaryFile != null && !oldBinaryFile.IsTemporary )
                            {
                                oldBinaryFile.IsTemporary = true;
                            }
                        }

                        // ensure the IsTemporary is set to false on binaryFile associated with this document
                        if ( document.BinaryFileId.HasValue )
                        {
                            var binaryFile = binaryFileService.Get( document.BinaryFileId.Value );
                            if ( binaryFile != null && binaryFile.IsTemporary )
                            {
                                binaryFile.IsTemporary = false;
                            }
                        }
                    }
                }

                groupMember.LoadAttributes();

                Rock.Attribute.Helper.GetEditValues( phAttributes, groupMember );

                if ( !Page.IsValid )
                {
                    return;
                }

                // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass.
                // So, make sure a message is displayed in the validation summary
                cvGroupMember.IsValid = groupMember.IsValid;

                if ( !cvGroupMember.IsValid )
                {
                    cvGroupMember.ErrorMessage = groupMember.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" );
                    return;
                }

                // using WrapTransaction because there are three Saves
                rockContext.WrapTransaction( () =>
                {
                    if ( groupMember.Id.Equals( 0 ) )
                    {
                        groupMemberService.Add( groupMember );
                    }

                    rockContext.SaveChanges();
                    groupMember.SaveAttributeValues( rockContext );
                } );

                groupMember.CalculateRequirements( rockContext, true );

                if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) )
                {
                    Rock.Security.Role.Flush( group.Id );
                }
            }
        }
        /// <summary>
        /// Updates the document status.
        /// </summary>
        /// <param name="signatureDocument">The signature document.</param>
        /// <param name="tempFolderPath">The temporary folder path.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public bool UpdateDocumentStatus( SignatureDocument signatureDocument, string tempFolderPath, out List<string> errorMessages )
        {
            errorMessages = new List<string>();
            if ( signatureDocument == null )
            {
                errorMessages.Add( "Invalid Document." );
            }

            if ( signatureDocument.SignatureDocumentTemplate == null )
            {
                errorMessages.Add( "Document has an invalid document type." );
            }

            if ( !errorMessages.Any() )
            {
                var provider = DigitalSignatureContainer.GetComponent( signatureDocument.SignatureDocumentTemplate.ProviderEntityType.Name );
                if ( provider == null || !provider.IsActive )
                {
                    errorMessages.Add( "Digital Signature provider was not found or is not active." );
                }
                else
                {
                    var originalStatus = signatureDocument.Status;
                    if ( provider.UpdateDocumentStatus( signatureDocument, out errorMessages ) )
                    {
                        if ( signatureDocument.Status == SignatureDocumentStatus.Signed && !signatureDocument.BinaryFileId.HasValue )
                        {
                            using ( var rockContext = new RockContext() )
                            {
                                string documentPath = provider.GetDocument( signatureDocument, tempFolderPath, out errorMessages );
                                if ( !string.IsNullOrWhiteSpace( documentPath ) )
                                {
                                    var binaryFileService = new BinaryFileService( rockContext );
                                    BinaryFile binaryFile = new BinaryFile();
                                    binaryFile.Guid = Guid.NewGuid();
                                    binaryFile.IsTemporary = false;
                                    binaryFile.BinaryFileTypeId = signatureDocument.SignatureDocumentTemplate.BinaryFileTypeId;
                                    binaryFile.MimeType = "application/pdf";
                                    binaryFile.FileName = new FileInfo( documentPath ).Name;
                                    binaryFile.ContentStream = new FileStream( documentPath, FileMode.Open );
                                    binaryFileService.Add( binaryFile );
                                    rockContext.SaveChanges();

                                    signatureDocument.BinaryFileId = binaryFile.Id;

                                    File.Delete( documentPath );
                                }
                            }
                        }

                        if ( signatureDocument.Status != originalStatus )
                        {
                            signatureDocument.LastStatusDate = RockDateTime.Now;
                        }

                    }

                }
            }

            return !errorMessages.Any();
        }
Esempio n. 49
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            if ( RegistrantState != null )
            {
                RockContext rockContext = new RockContext();
                var personService = new PersonService( rockContext );
                var registrantService = new RegistrationRegistrantService( rockContext );
                var registrantFeeService = new RegistrationRegistrantFeeService( rockContext );
                var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext );
                RegistrationRegistrant registrant = null;
                if ( RegistrantState.Id > 0 )
                {
                    registrant = registrantService.Get( RegistrantState.Id );
                }

                bool newRegistrant = false;
                var registrantChanges = new List<string>();

                if ( registrant == null )
                {
                    newRegistrant = true;
                    registrant = new RegistrationRegistrant();
                    registrant.RegistrationId = RegistrantState.RegistrationId;
                    registrantService.Add( registrant );
                    registrantChanges.Add( "Created Registrant" );
                }

                if ( !registrant.PersonAliasId.Equals( ppPerson.PersonAliasId ) )
                {
                    string prevPerson = ( registrant.PersonAlias != null && registrant.PersonAlias.Person != null ) ?
                        registrant.PersonAlias.Person.FullName : string.Empty;
                    string newPerson = ppPerson.PersonName;
                    History.EvaluateChange( registrantChanges, "Person", prevPerson, newPerson );
                }
                int? personId = ppPerson.PersonId.Value;
                registrant.PersonAliasId = ppPerson.PersonAliasId.Value;

                // Get the name of registrant for history
                string registrantName = "Unknown";
                if ( ppPerson.PersonId.HasValue )
                {
                    var person = personService.Get( ppPerson.PersonId.Value );
                    if ( person != null )
                    {
                        registrantName = person.FullName;
                    }
                }

                // set their status (wait list / registrant)
                registrant.OnWaitList = !tglWaitList.Checked;

                History.EvaluateChange( registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal() );
                registrant.Cost = cbCost.Text.AsDecimal();

                History.EvaluateChange( registrantChanges, "Discount Applies", registrant.DiscountApplies, cbDiscountApplies.Checked );
                registrant.DiscountApplies = cbDiscountApplies.Checked;

                if ( !Page.IsValid )
                {
                    return;
                }

                // Remove/delete any registrant fees that are no longer in UI with quantity
                foreach ( var dbFee in registrant.Fees.ToList() )
                {
                    if ( !RegistrantState.FeeValues.Keys.Contains( dbFee.RegistrationTemplateFeeId ) ||
                        RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] == null ||
                        !RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId]
                            .Any( f =>
                                f.Option == dbFee.Option &&
                                f.Quantity > 0 ) )
                    {
                        registrantChanges.Add( string.Format( "Removed '{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}",
                            dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option ) );

                        registrant.Fees.Remove( dbFee );
                        registrantFeeService.Delete( dbFee );
                    }
                }

                // Add/Update any of the fees from UI
                foreach ( var uiFee in RegistrantState.FeeValues.Where( f => f.Value != null ) )
                {
                    foreach ( var uiFeeOption in uiFee.Value )
                    {
                        var dbFee = registrant.Fees
                            .Where( f =>
                                f.RegistrationTemplateFeeId == uiFee.Key &&
                                f.Option == uiFeeOption.Option )
                            .FirstOrDefault();

                        if ( dbFee == null )
                        {
                            dbFee = new RegistrationRegistrantFee();
                            dbFee.RegistrationTemplateFeeId = uiFee.Key;
                            dbFee.Option = uiFeeOption.Option;
                            registrant.Fees.Add( dbFee );
                        }

                        var templateFee = dbFee.RegistrationTemplateFee;
                        if ( templateFee == null )
                        {
                            templateFee = registrationTemplateFeeService.Get( uiFee.Key );
                        }

                        string feeName = templateFee != null ? templateFee.Name : "Fee";
                        if ( !string.IsNullOrWhiteSpace( uiFeeOption.Option ) )
                        {
                            feeName = string.Format( "{0} ({1})", feeName, uiFeeOption.Option );
                        }

                        if ( dbFee.Id <= 0 )
                        {
                            registrantChanges.Add( feeName + " Fee Added" );
                        }

                        History.EvaluateChange( registrantChanges, feeName + " Quantity", dbFee.Quantity, uiFeeOption.Quantity );
                        dbFee.Quantity = uiFeeOption.Quantity;

                        History.EvaluateChange( registrantChanges, feeName + " Cost", dbFee.Cost, uiFeeOption.Cost );
                        dbFee.Cost = uiFeeOption.Cost;
                    }
                }

                if ( TemplateState.RequiredSignatureDocumentTemplate != null )
                {
                    var person = new PersonService( rockContext ).Get( personId.Value );

                    var documentService = new SignatureDocumentService( rockContext );
                    var binaryFileService = new BinaryFileService( rockContext );
                    SignatureDocument document = null;

                    int? signatureDocumentId = hfSignedDocumentId.Value.AsIntegerOrNull();
                    int? binaryFileId = fuSignedDocument.BinaryFileId;
                    if ( signatureDocumentId.HasValue )
                    {
                        document = documentService.Get( signatureDocumentId.Value );
                    }

                    if ( document == null && binaryFileId.HasValue )
                    {
                        var instance = new RegistrationInstanceService( rockContext ).Get( RegistrationInstanceId );

                        document = new SignatureDocument();
                        document.SignatureDocumentTemplateId = TemplateState.RequiredSignatureDocumentTemplate.Id;
                        document.AppliesToPersonAliasId = registrant.PersonAliasId.Value;
                        document.AssignedToPersonAliasId = registrant.PersonAliasId.Value;
                        document.Name = string.Format( "{0}_{1}",
                            ( instance != null ? instance.Name : TemplateState.Name ),
                            ( person != null ? person.FullName.RemoveSpecialCharacters() : string.Empty ) );
                        document.Status = SignatureDocumentStatus.Signed;
                        document.LastStatusDate = RockDateTime.Now;
                        documentService.Add( document );
                    }

                    if ( document != null )
                    {
                        int? origBinaryFileId = document.BinaryFileId;
                        document.BinaryFileId = binaryFileId;

                        if ( origBinaryFileId.HasValue && origBinaryFileId.Value != document.BinaryFileId )
                        {
                            // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up
                            var oldBinaryFile = binaryFileService.Get( origBinaryFileId.Value );
                            if ( oldBinaryFile != null && !oldBinaryFile.IsTemporary )
                            {
                                oldBinaryFile.IsTemporary = true;
                            }
                        }

                        // ensure the IsTemporary is set to false on binaryFile associated with this document
                        if ( document.BinaryFileId.HasValue )
                        {
                            var binaryFile = binaryFileService.Get( document.BinaryFileId.Value );
                            if ( binaryFile != null && binaryFile.IsTemporary )
                            {
                                binaryFile.IsTemporary = false;
                            }
                        }
                    }
                }

                if ( !registrant.IsValid )
                {
                    // Controls will render the error messages
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();

                    registrant.LoadAttributes();
                    foreach ( var field in TemplateState.Forms
                        .SelectMany( f => f.Fields
                            .Where( t =>
                                t.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                t.AttributeId.HasValue ) ) )
                    {
                        var attribute = AttributeCache.Read( field.AttributeId.Value );
                        if ( attribute != null )
                        {
                            string originalValue = registrant.GetAttributeValue( attribute.Key );
                            var fieldValue = RegistrantState.FieldValues
                                .Where( f => f.Key == field.Id )
                                .Select( f => f.Value.FieldValue )
                                .FirstOrDefault();
                            string newValue = fieldValue != null ? fieldValue.ToString() : string.Empty;

                            if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() )
                            {
                                string formattedOriginalValue = string.Empty;
                                if ( !string.IsNullOrWhiteSpace( originalValue ) )
                                {
                                    formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false );
                                }

                                string formattedNewValue = string.Empty;
                                if ( !string.IsNullOrWhiteSpace( newValue ) )
                                {
                                    formattedNewValue = attribute.FieldType.Field.FormatValue( null, newValue, attribute.QualifierValues, false );
                                }

                                History.EvaluateChange( registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue );
                            }

                            if ( fieldValue != null )
                            {
                                registrant.SetAttributeValue( attribute.Key, fieldValue.ToString() );
                            }
                        }
                    }

                    registrant.SaveAttributeValues( rockContext );
                } );

                if ( newRegistrant && TemplateState.GroupTypeId.HasValue && ppPerson.PersonId.HasValue )
                {
                    using ( var newRockContext = new RockContext() )
                    {
                        var reloadedRegistrant = new RegistrationRegistrantService( newRockContext ).Get( registrant.Id );
                        if ( reloadedRegistrant != null &&
                            reloadedRegistrant.Registration != null &&
                            reloadedRegistrant.Registration.Group != null &&
                            reloadedRegistrant.Registration.Group.GroupTypeId == TemplateState.GroupTypeId.Value )
                        {
                            int? groupRoleId = TemplateState.GroupMemberRoleId.HasValue ?
                                TemplateState.GroupMemberRoleId.Value :
                                reloadedRegistrant.Registration.Group.GroupType.DefaultGroupRoleId;
                            if ( groupRoleId.HasValue )
                            {
                                var groupMemberService = new GroupMemberService( newRockContext );
                                var groupMember = groupMemberService
                                    .Queryable().AsNoTracking()
                                    .Where( m =>
                                        m.GroupId == reloadedRegistrant.Registration.Group.Id &&
                                        m.PersonId == reloadedRegistrant.PersonId &&
                                        m.GroupRoleId == groupRoleId.Value )
                                    .FirstOrDefault();
                                if ( groupMember == null )
                                {
                                    groupMember = new GroupMember();
                                    groupMemberService.Add( groupMember );
                                    groupMember.GroupId = reloadedRegistrant.Registration.Group.Id;
                                    groupMember.PersonId = ppPerson.PersonId.Value;
                                    groupMember.GroupRoleId = groupRoleId.Value;
                                    groupMember.GroupMemberStatus = TemplateState.GroupMemberStatus;

                                    newRockContext.SaveChanges();

                                    registrantChanges.Add( string.Format( "Registrant added to {0} group", reloadedRegistrant.Registration.Group.Name ) );
                                }
                                else
                                {
                                    registrantChanges.Add( string.Format( "Registrant group member reference updated to existing person in {0} group", reloadedRegistrant.Registration.Group.Name ) );
                                }

                                reloadedRegistrant.GroupMemberId = groupMember.Id;
                                newRockContext.SaveChanges();
                            }
                        }
                    }
                }

                HistoryService.SaveChanges(
                    rockContext,
                    typeof( Registration ),
                    Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(),
                    registrant.RegistrationId,
                    registrantChanges,
                    "Registrant: " + registrantName,
                    null, null );
            }

            NavigateToRegistration();
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="signatureDocumentId">The signature document type identifier.</param>
        public void ShowDetail( int signatureDocumentId )
        {
            pnlDetails.Visible = true;
            SignatureDocument signatureDocument = null;

            using ( var rockContext = new RockContext() )
            {
                if ( !signatureDocumentId.Equals( 0 ) )
                {
                    signatureDocument = new SignatureDocumentService( rockContext ).Get( signatureDocumentId );
                }

                if ( signatureDocument == null )
                {
                    signatureDocument = new SignatureDocument { Id = 0 };

                    int? personId = PageParameter( "personId" ).AsIntegerOrNull();
                    if ( personId.HasValue )
                    {
                        var person = new PersonService( rockContext ).Get( personId.Value );
                        if ( person != null )
                        {
                            var personAlias = person.PrimaryAlias;
                            if ( personAlias != null )
                            {
                                signatureDocument.AppliesToPersonAlias = personAlias;
                                signatureDocument.AppliesToPersonAliasId = personAlias.Id;
                                signatureDocument.AssignedToPersonAlias = personAlias;
                                signatureDocument.AssignedToPersonAliasId = personAlias.Id;
                            }
                        }
                    }

                    int? documentTypeId = PageParameter( "SignatureDocumentTemplateId" ).AsIntegerOrNull();
                    if ( documentTypeId.HasValue )
                    {
                        var documentType = new SignatureDocumentTemplateService( rockContext ).Get( documentTypeId.Value );
                        if ( documentType != null )
                        {
                            signatureDocument.SignatureDocumentTemplate = documentType;
                            signatureDocument.SignatureDocumentTemplateId = documentType.Id;
                        }
                    }
                }

                hfSignatureDocumentId.SetValue( signatureDocument.Id );

                // render UI based on Authorized and IsSystem
                bool readOnly = false;

                nbEditModeMessage.Text = string.Empty;
                bool canEdit = UserCanEdit || signatureDocument.IsAuthorized( Authorization.EDIT, CurrentPerson );
                bool canView = canEdit || signatureDocument.IsAuthorized( Authorization.VIEW, CurrentPerson );

                if ( !canView )
                {
                    pnlDetails.Visible = false;
                }
                else
                {
                    pnlDetails.Visible = true;

                    if ( !canEdit )
                    {
                        readOnly = true;
                        nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( SignatureDocument.FriendlyTypeName );
                    }

                    if ( readOnly )
                    {
                        ShowReadonlyDetails( signatureDocument );
                    }
                    else
                    {
                        ShowEditDetails( signatureDocument, false );
                    }
                }
            }
        }
Esempio n. 51
0
 /// <summary>
 /// Cancels the document.
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="errors">The errors.</param>
 /// <returns></returns>
 public abstract bool CancelDocument( SignatureDocument document, out List<string> errors );
Esempio n. 52
0
        /// <summary>
        /// Gets the invite link.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="recipient">The recipient.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public override string GetInviteLink( SignatureDocument document, Person recipient, out List<string> errors )
        {
            errors = new List<string>();

            if ( document == null )
            {
                errors.Add( "Invalid Document!" );
                return null;
            }

            // Get the access token
            string errorMessage = string.Empty;
            string accessToken = GetAccessToken( false, out errorMessage );
            if ( string.IsNullOrWhiteSpace( accessToken ) )
            {
                errors.Add( errorMessage );
                return null;
            }

            JObject inviteLinkRes = CudaSign.Link.Create( accessToken, document.DocumentKey );
            string inviteLink = inviteLinkRes.Value<string>( "url_no_signup" );
            if ( string.IsNullOrWhiteSpace( inviteLink ) )
            {
                errors = ParseErrors( inviteLinkRes );
                return null;
            }

            return inviteLink;
        }