//'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


        //Sign PDF file
        public bool SignPDFFile(
            string FileToSign,
            string UserName,
            string Password,
            int X,
            int Y,
            int Width,
            int Height,
            int Page,
            bool isVisible)
        {
            //Create Request object contains signature parameters
            RequestBaseType Req = new RequestBaseType();

            Req.OptionalInputs = new RequestBaseTypeOptionalInputs();

            //Here Operation Type is set: Verify/Create Signature Field/Sign/etc
            Req.OptionalInputs.SignatureType = SignatureTypeFieldCreateSign;

            //Configure Create and Sign operation parameters:
            Req.OptionalInputs.ClaimedIdentity                              = new ClaimedIdentity();
            Req.OptionalInputs.ClaimedIdentity.Name                         = new NameIdentifierType();
            Req.OptionalInputs.ClaimedIdentity.Name.Value                   = UserName;    //User Name
            Req.OptionalInputs.ClaimedIdentity.Name.NameQualifier           = " ";         //Domain (relevant for Active Directory environment only)
            Req.OptionalInputs.ClaimedIdentity.SupportingInfo               = new CoSignAuthDataType();
            Req.OptionalInputs.ClaimedIdentity.SupportingInfo.LogonPassword = Password;    //User Password
            Req.OptionalInputs.SAPISigFieldSettings                         = new SAPISigFieldSettingsType();
            Req.OptionalInputs.SAPISigFieldSettings.X                       = X;           //Signature Field X coordinate
            Req.OptionalInputs.SAPISigFieldSettings.XSpecified              = true;
            Req.OptionalInputs.SAPISigFieldSettings.Y                       = Y;           //Signature Field Y coordinate
            Req.OptionalInputs.SAPISigFieldSettings.YSpecified              = true;
            Req.OptionalInputs.SAPISigFieldSettings.Page                    = Page;        //Page number the signature field will appear on
            Req.OptionalInputs.SAPISigFieldSettings.PageSpecified           = true;
            Req.OptionalInputs.SAPISigFieldSettings.Width                   = Width;       //Signature Field width
            Req.OptionalInputs.SAPISigFieldSettings.WidthSpecified          = true;
            Req.OptionalInputs.SAPISigFieldSettings.Height                  = Height;      //Signature Field Height
            Req.OptionalInputs.SAPISigFieldSettings.HeightSpecified         = true;
            Req.OptionalInputs.SAPISigFieldSettings.Invisible               = !isVisible;  //Specifies whether the signature will be visible or not
            Req.OptionalInputs.SAPISigFieldSettings.InvisibleSpecified      = true;


            // Set configuration parameters /////////////////////////////////////////////////////////
            int numConfigurationParams = 6;

            Req.OptionalInputs.ConfigurationValues = new ConfValueType[numConfigurationParams];
            for (int i = 0; i < numConfigurationParams; i++)
            {
                Req.OptionalInputs.ConfigurationValues[i] = new ConfValueType();
            }

            // Add reason
            Req.OptionalInputs.ConfigurationValues[0].ConfValueID = ConfIDEnum.Reason;
            Req.OptionalInputs.ConfigurationValues[0].Item        = "I am the author of this document";

            // Add TSA:

            /*
             * Req.OptionalInputs.ConfigurationValues[1].ConfValueID = ConfIDEnum.UseTimestamp;
             * Req.OptionalInputs.ConfigurationValues[1].Item = 1;
             *
             * Req.OptionalInputs.ConfigurationValues[2].ConfValueID = ConfIDEnum.TimestampURL;
             * Req.OptionalInputs.ConfigurationValues[2].Item = "http://www.ca-soft.com/request.aspx";
             *
             * Req.OptionalInputs.ConfigurationValues[3].ConfValueID = ConfIDEnum.TimestampAdditionalBytes;
             * Req.OptionalInputs.ConfigurationValues[3].Item = 4000;
             *
             * Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.TimestampUser;
             * Req.OptionalInputs.ConfigurationValues[4].Item = "";
             *
             * Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.TimestampPWD;
             * Req.OptionalInputs.ConfigurationValues[5].Item = "";
             *
             * // OCSP (NOTE: Server must contain comodo CA in order to use the following OCSP URL)
             * Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.UseOCSP;
             * Req.OptionalInputs.ConfigurationValues[4].Item = 1;
             *
             * Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.OCSPURL;
             * Req.OptionalInputs.ConfigurationValues[5].Item = "ocsp.comodoca.com";
             */
            // End setting configuration parameters ////////////////////////////////////////////////

            //Set Session ID
            Req.RequestID = Guid.NewGuid().ToString();

            //Prepare the Data to be signed
            DocumentType           doc1    = new DocumentType();
            DocumentTypeBase64Data b64data = new DocumentTypeBase64Data();

            Req.InputDocuments       = new RequestBaseTypeInputDocuments();
            Req.InputDocuments.Items = new object[1];

            b64data.MimeType = "application/pdf";     //Can also be: application/msword, image/tiff, pplication/octet-string (ocsp/tsa are supported in PDF only)
            Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
            Req.OptionalInputs.ReturnPDFTailOnly          = true;
            b64data.Value = ReadFile(FileToSign, true); //Read the file to the Bytes Array

            doc1.Item = b64data;
            Req.InputDocuments.Items[0] = doc1;

            //Call sign service
            ResponseBaseType Resp = null;

            try
            {
                // Create the Web Service client object
                DSS service = new DSS();
                service.Url = "https://prime.cosigntrial.com:8080/SAPIWS/dss.asmx";  //This url is constant and shouldn't be changed

                SignRequest sreq = new SignRequest();
                sreq.InputDocuments = Req.InputDocuments;
                sreq.OptionalInputs = Req.OptionalInputs;

                //Perform Signature operation
                Resp = service.DssSign(sreq);

                if (Resp.Result.ResultMajor != Success)
                {
                    MessageBox.Show("Error: " + Resp.Result.ResultMajor + " " +
                                    Resp.Result.ResultMinor + " " +
                                    Resp.Result.ResultMessage.Value, "Error");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                if (ex is WebException)
                {
                    WebException we          = ex as WebException;
                    WebResponse  webResponse = we.Response;
                    if (webResponse != null)
                    {
                        MessageBox.Show(we.Response.ToString(), "Web Response");
                    }
                }
                return(false);
            }


            //Handle Reply
            DssSignResult sResp = (DssSignResult)Resp;



            //object sig = sResp.SignatureObject.Item;
            //SignatureObjectTypeBase64Signature sig = (SignatureObjectTypeBase64Signature) sResp.SignatureObject.Item;
            DssSignResultSignatureObjectBase64Signature sig = (DssSignResultSignatureObjectBase64Signature)sResp.SignatureObject.Item;

            byte[] signature = sig.Value;

            return(PDFAttachSignature(FileToSign, signature, true)); //Attach Signature to the PDF file
        }
 private String ValidateResult(ResponseBaseType response)
 {
     Result result = response.Result;
     String resultMajor = result.ResultMajor;
     String resultMinor = result.ResultMinor;
     Console.WriteLine("result major: " + resultMajor);
     if (!DSSConstants.RESULT_MAJOR_SUCCESS.Equals(resultMajor))
     {
         Console.WriteLine("result minor: " + resultMinor);
         if (null != resultMinor && resultMinor.Equals(
             DSSConstants.RESULT_MINOR_NOT_PARSEABLE_XML_DOCUMENT))
         {
             throw new NotParseableXMLDocumentException();
         }
         throw new DSSRequestFailedException("unsuccessful result",resultMajor, resultMinor);
     }
     return resultMinor;
 }
 private void CheckResponse(ResponseBaseType response, String requestId)
 {
     if (null == response)
     {
         throw new SystemException("No response returned");
     }
     String responseRequestId = response.RequestID;
     if (null == responseRequestId)
     {
         throw new SystemException("Missing Response.RequestID");
     }
     if (!responseRequestId.Equals(requestId))
     {
         throw new SystemException("Incorrect Response.RequestID");
     }
 }
        private DSSXSDNamespace.VerificationReportType FindVerificationReport(ResponseBaseType responseBase)
        {
            if (null == responseBase.OptionalOutputs)
            {
                return null;
            }
            foreach (XmlElement optionalOutput in responseBase.OptionalOutputs.Any)
            {
                if (optionalOutput.NamespaceURI.Equals(DSSConstants.VR_NAMESPACE) &&
                    optionalOutput.LocalName.Equals("VerificationReport"))
                {
                    DSSXSDNamespace.VerificationReportType verificationReport =
                        (DSSXSDNamespace.VerificationReportType)FromDom("VerificationReport",
                        DSSConstants.VR_NAMESPACE, optionalOutput,
                        typeof(DSSXSDNamespace.VerificationReportType));
                    return verificationReport;
                }
            }

            return null;
        }
        //'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


        //Sign PDF file
        public bool SignPDFFile(
            string CoSignDNS,
            string FileToSign,
            string UserName,
            string Password,
            string PdfPassword,
            string grSigName,
            int X,
            int Y,
            int Width,
            int Height,
            int Page,
            bool isVisible,
            int GMTOffset,
            int AppearanceMask)
        {
            //Create Request object contains signature parameters
            RequestBaseType Req = new RequestBaseType();

            Req.OptionalInputs = new RequestBaseTypeOptionalInputs();

            //Here Operation Type is set: Verify/Create Signature Field/Sign/etc
            Req.OptionalInputs.SignatureType = SignatureTypeFieldCreateSign;

            //Configure Create and Sign operation parameters:
            Req.OptionalInputs.ClaimedIdentity                              = new ClaimedIdentity();
            Req.OptionalInputs.ClaimedIdentity.Name                         = new NameIdentifierType();
            Req.OptionalInputs.ClaimedIdentity.Name.Value                   = UserName;    //User Name
            Req.OptionalInputs.ClaimedIdentity.Name.NameQualifier           = " ";         //Domain (relevant for Active Directory environment only)
            Req.OptionalInputs.ClaimedIdentity.SupportingInfo               = new CoSignAuthDataType();
            Req.OptionalInputs.ClaimedIdentity.SupportingInfo.LogonPassword = Password;    //User Password
            Req.OptionalInputs.SAPISigFieldSettings                         = new SAPISigFieldSettingsType();
            Req.OptionalInputs.SAPISigFieldSettings.X                       = X;           //Signature Field X coordinate
            Req.OptionalInputs.SAPISigFieldSettings.XSpecified              = true;
            Req.OptionalInputs.SAPISigFieldSettings.Y                       = Y;           //Signature Field Y coordinate
            Req.OptionalInputs.SAPISigFieldSettings.YSpecified              = true;
            Req.OptionalInputs.SAPISigFieldSettings.Page                    = Page;        //Page number the signature field will appear on
            Req.OptionalInputs.SAPISigFieldSettings.PageSpecified           = true;
            Req.OptionalInputs.SAPISigFieldSettings.Width                   = Width;       //Signature Field width
            Req.OptionalInputs.SAPISigFieldSettings.WidthSpecified          = true;
            Req.OptionalInputs.SAPISigFieldSettings.Height                  = Height;      //Signature Field Height
            Req.OptionalInputs.SAPISigFieldSettings.HeightSpecified         = true;
            Req.OptionalInputs.SAPISigFieldSettings.Invisible               = !isVisible;  //Specifies whether the signature will be visible or not
            Req.OptionalInputs.SAPISigFieldSettings.InvisibleSpecified      = true;

            //display only graphical signature in signature field
            Req.OptionalInputs.SAPISigFieldSettings.AppearanceMask          = (uint)AppearanceMask;
            Req.OptionalInputs.SAPISigFieldSettings.AppearanceMaskSpecified = true;

            int numConfigurationParams = 0;

            if (!string.IsNullOrEmpty(PdfPassword))
            {
                numConfigurationParams += 2;
            }
            if (!string.IsNullOrEmpty(grSigName))
            {
                numConfigurationParams += 1;
            }
            if ((GMTOffset != 0) && ((GMTOffset % 60) == 0))
            {
                numConfigurationParams += 1;
            }

            if (numConfigurationParams > 0)
            {
                Req.OptionalInputs.ConfigurationValues = new ConfValueType[numConfigurationParams];
                for (int i = 0; i < numConfigurationParams; i++)
                {
                    Req.OptionalInputs.ConfigurationValues[i] = new ConfValueType();
                }
            }

            int confArrayCurrentLoc = -1;

            if (!string.IsNullOrEmpty(PdfPassword))
            {
                // Add DECRYPT PDF password
                confArrayCurrentLoc += 1;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].ConfValueID = ConfIDEnum.PDFOwnerPwd;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].Item        = PdfPassword;

                confArrayCurrentLoc += 1;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].ConfValueID = ConfIDEnum.PDFUserPwd;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].Item        = PdfPassword;
            }

            //choose the 'grSigName' graphical signature from signer account
            if (!string.IsNullOrEmpty(grSigName))
            {
                //specify graphical signature name
                confArrayCurrentLoc += 1;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].ConfValueID = ConfIDEnum.GRSigPrefName;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].Item        = grSigName;
            }

            if ((GMTOffset != 0) && ((GMTOffset % 60) == 0))
            {
                //GMTOffset
                confArrayCurrentLoc += 1;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].ConfValueID = ConfIDEnum.GMTOffset;
                Req.OptionalInputs.ConfigurationValues[confArrayCurrentLoc].Item        = GMTOffset;
            }

            // Add reason
            //Req.OptionalInputs.ConfigurationValues[0].ConfValueID = ConfIDEnum.Reason;
            //Req.OptionalInputs.ConfigurationValues[0].Item = "I am the author of this document";

            // Add TSA:

            /*
             * Req.OptionalInputs.ConfigurationValues[1].ConfValueID = ConfIDEnum.UseTimestamp;
             * Req.OptionalInputs.ConfigurationValues[1].Item = 1;
             *
             * Req.OptionalInputs.ConfigurationValues[2].ConfValueID = ConfIDEnum.TimestampURL;
             * Req.OptionalInputs.ConfigurationValues[2].Item = "http://www.ca-soft.com/request.aspx";
             *
             * Req.OptionalInputs.ConfigurationValues[3].ConfValueID = ConfIDEnum.TimestampAdditionalBytes;
             * Req.OptionalInputs.ConfigurationValues[3].Item = 4000;
             *
             * Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.TimestampUser;
             * Req.OptionalInputs.ConfigurationValues[4].Item = "";
             *
             * Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.TimestampPWD;
             * Req.OptionalInputs.ConfigurationValues[5].Item = "";
             *
             * // OCSP (NOTE: Server must contain comodo CA in order to use the following OCSP URL)
             * Req.OptionalInputs.ConfigurationValues[4].ConfValueID = ConfIDEnum.UseOCSP;
             * Req.OptionalInputs.ConfigurationValues[4].Item = 1;
             *
             * Req.OptionalInputs.ConfigurationValues[5].ConfValueID = ConfIDEnum.OCSPURL;
             * Req.OptionalInputs.ConfigurationValues[5].Item = "ocsp.comodoca.com";
             */
            // End setting configuration parameters ////////////////////////////////////////////////

            //Set Session ID
            Req.RequestID = Guid.NewGuid().ToString();

            //Prepare the Data to be signed
            DocumentType           doc1    = new DocumentType();
            DocumentTypeBase64Data b64data = new DocumentTypeBase64Data();

            Req.InputDocuments       = new RequestBaseTypeInputDocuments();
            Req.InputDocuments.Items = new object[1];

            b64data.MimeType = "application/pdf";     //Can also be: application/msword, image/tiff, pplication/octet-string (ocsp/tsa are supported in PDF only)
            //Req.OptionalInputs.ReturnPDFTailOnlySpecified = true;
            Req.OptionalInputs.ReturnPDFTailOnlySpecified = false;
            Req.OptionalInputs.ReturnPDFTailOnly          = false;
            b64data.Value = ReadFile(FileToSign, true); //Read the file to the Bytes Array

            doc1.Item = b64data;
            Req.InputDocuments.Items[0] = doc1;

            //Call sign service
            ResponseBaseType Resp = null;

            try
            {
                // Create the Web Service client object
                DSS service = new DSS();
                service.Url = "https://" + CoSignDNS + ":8080/sapiws/dss.asmx";

                SignRequest sreq = new SignRequest();
                sreq.InputDocuments = Req.InputDocuments;
                sreq.OptionalInputs = Req.OptionalInputs;

                //Perform Signature operation
                Resp = service.DssSign(sreq);

                if (Resp.Result.ResultMajor != Success)
                {
                    MessageBox.Show("Error: " + Resp.Result.ResultMajor + " " +
                                    Resp.Result.ResultMinor + " " +
                                    Resp.Result.ResultMessage.Value, "Error");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                if (ex is WebException)
                {
                    WebException we          = ex as WebException;
                    WebResponse  webResponse = we.Response;
                    if (webResponse != null)
                    {
                        MessageBox.Show(we.Response.ToString(), "Web Response");
                    }
                }
                return(false);
            }

            //Handle Reply
            DssSignResult sResp = (DssSignResult)Resp;

            //return Tail only code
            //DssSignResultSignatureObjectBase64Signature sig = (DssSignResultSignatureObjectBase64Signature)sResp.SignatureObject.Item;
            //byte[] signature = sig.Value;
            //return PDFAttachSignature(FileToSign, signature, true); //Attach Signature to the PDF file

            DocumentTypeBase64Data signedDoc = (DocumentTypeBase64Data)sResp.OptionalOutputs.DocumentWithSignature.Document.Item;

            byte[] docData = signedDoc.Value;
            //return PDFAttachSignature(FileToSign + ".signed.pdf", docData, true);
            return(PDFReWrite(FileToSign, docData, true));
        }