Beispiel #1
0
 protected int ExecuteAndVerify(String code, ValidationData[] data, Dictionary<string, Object> context, out int nErrors)
 {
     ProtoCore.Core core = Setup();
     ProtoScript.Runners.ProtoScriptTestRunner fsr = new ProtoScript.Runners.ProtoScriptTestRunner();
     ExecutionMirror mirror = fsr.Execute(code, core, context);
     int nWarnings = core.RuntimeStatus.WarningCount;
     nErrors = core.BuildStatus.ErrorCount;
     if (data == null)
     {
         core.Cleanup();
         return nWarnings + nErrors;
     }
     TestFrameWork thisTest = new TestFrameWork();
     foreach (var item in data)
     {
         if (item.ExpectedValue == null)
         {
             object nullOb = null;
             TestFrameWork.Verify(mirror, item.ValueName, nullOb, item.BlockIndex);
         }
         else
         {
             TestFrameWork.Verify(mirror, item.ValueName, item.ExpectedValue, item.BlockIndex);
         }
     }
     core.Cleanup();
     return nWarnings + nErrors;
 }
 /// <summary>
 /// Validates model
 /// </summary>
 /// <param name="obj">Model to validate</param>
 /// <param name="results">Validation error details</param>
 /// <returns>True - validation success, false - failure</returns>
 public static bool Validate(this IBabelModel obj, out List<ValidationResult> results)
 {
     results = new List<ValidationResult>();
     if (obj == null) return true; //?or false
     var vd = new ValidationData {Results = results, IsValid = true, Prefix = ""};
     ValidateModel(obj, vd);
     return vd.IsValid;
 }
Beispiel #3
0
 protected int ExecuteAndVerify(String code, ValidationData[] data, out int nErrors)
 {
     return ExecuteAndVerify(code, data, null, out nErrors);
 }
Beispiel #4
0
 protected int ExecuteAndVerify(String code, ValidationData[] data)
 {
     int errors = 0;
     return ExecuteAndVerify(code, data, out errors);
 }
Beispiel #5
0
 protected int ExecuteAndVerify(String code, ValidationData[] data, Dictionary<string, Object> context)
 {
     int errors = 0;
     return ExecuteAndVerify(code, data, context, out errors);
 }
Beispiel #6
0
 /**
  * Add verification for a particular signature
  * @param signatureName the signature to validate (it may be a timestamp)
  * @param ocsp the interface to get the OCSP
  * @param crl the interface to get the CRL
  * @param certOption
  * @param level the validation options to include
  * @param certInclude
  * @return true if a validation was generated, false otherwise
  * @throws Exception
  */
 public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude) {
     if (used)
         throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
     PdfPKCS7 pk = acroFields.VerifySignature(signatureName);
     X509Certificate[] xc = pk.SignCertificateChain;
     ValidationData vd = new ValidationData();
     for (int k = 0; k < xc.Length; ++k) {
         byte[] ocspEnc = null;
         if (ocsp != null && level != Level.CRL && k < xc.Length - 1) {
             ocspEnc = ocsp.GetEncoded(xc[k], xc[k + 1], null);
             if (ocspEnc != null)
                 vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
         }
         if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null))) {
             byte[] cim = crl.GetEncoded(xc[k], null);
             if (cim != null) {
                 bool dup = false;
                 foreach (byte[] b in vd.crls) {
                     if (Arrays.AreEqual(b, cim)) {
                         dup = true;
                         break;
                     }
                 }
                 if (!dup)
                     vd.crls.Add(cim);
             }
         }
         if (certOption == CertificateOption.SIGNING_CERTIFICATE)
             break;
     }
     if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
         return false;
     if (certInclude == CertificateInclusion.YES) {
         foreach (X509Certificate c in xc) {
             vd.certs.Add(c.GetEncoded());
         }
     }
     validated[GetSignatureHashKey(signatureName)] = vd;
     return true;
 }
        public void CallValidateSpecWorkerJSP(ValidationData validationData)
        {
            this.validationData = validationData;

            HttpWebResponse httpWebResponse = null;
            string xmlFileName = Common.StripExtensionFileName(validationData.vuiFileName) + ".xml";

            try {
                //Creating the Web Request.
                guid = Guid.NewGuid();
                //string tempServerName = Shadow.validationServerIp;
                httpWebRequest = HttpWebRequest.Create(PathMaker.GetValidationServer() + Strings.VALIDATEJSPNAME + "?ClientTag=" + guid) as HttpWebRequest;
                //httpWebRequest = HttpWebRequest.Create(Strings.SERVERNAME + Strings.VALIDATEJSPNAME + "?ClientTag=" + guid) as HttpWebRequest;
                //Specifing the Method
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "multipart/form-data=-----------------------------";
                // Create POST data and convert it to a byte array.
                string bufferTmp = "---------------------------Content-Disposition: form-data; name=\"fileField\";filename=" + "\"" + xmlFileName + "\"Content-Type: text/xml\n\n\n";
                Byte[] buffer = Encoding.ASCII.GetBytes(bufferTmp);
                //need to fix targetfilename with a real value
                string path = validationData.xmlFileName;
                //Open xml file for reading
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                int length = (int)fs.Length;
                byte[] buffer2 = new byte[length];
                int count;
                int sum = 0;
                //Read xml into buffer2
                while ((count = fs.Read(buffer2, sum, length - sum)) > 0)
                    sum += count;
                fs.Close();

                //postDataString has to be formatted just right otherwise it won't work
                string tmpPostDataString = "\n\n\n\n-----------------------------\nContent-Disposition: form-data; ";
                tmpPostDataString += validationData.postDataString;
                tmpPostDataString += ("\n-----------------------------");
                tmpPostDataString += ("\nfilefield: " + Common.StripExtensionFileName(validationData.vuiFileName));

                Console.WriteLine("postDataString: " + tmpPostDataString);

                byte[] buffer3 = Encoding.ASCII.GetBytes(tmpPostDataString);

                //Combine the buffers
                byte[] bufferCombined = new byte[buffer.Length + buffer2.Length + buffer3.Length];
                Array.Copy(buffer, 0, bufferCombined, 0, buffer.Length);
                Array.Copy(buffer2, 0, bufferCombined, buffer.Length, buffer2.Length);
                Array.Copy(buffer3, 0, bufferCombined, buffer.Length + buffer2.Length, buffer3.Length);

                //Send Requst with PostData
                httpWebRequest.ContentLength = bufferCombined.Length;
                httpWebRequest.Timeout = System.Threading.Timeout.Infinite;

                Stream PostData = httpWebRequest.GetRequestStream();
                PostData.Write(bufferCombined, 0, bufferCombined.Length);
                PostData.Close();

                //Getting the Response and reading the result.
                httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;

                using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream())) {
                    htmlResults = sr.ReadToEnd();
                }

                httpWebResponse.Close();

            }
            catch (WebException e) {
                if (e.Status == WebExceptionStatus.ProtocolError) {
                    MessageBox.Show("Exception Message :" + e.Message +
                        "\nStatus Code : " + ((HttpWebResponse)e.Response).StatusCode +
                        "\nStatus Description : " + ((HttpWebResponse)e.Response).StatusDescription +
                        "\nPlease Contact PathMaker Support", "XML Validate Error");
                }
                else {
                    if (cancelUIRun.Equals(false))
                        MessageBox.Show("Unable to Validate XML.\nPlease make sure you are connected to Convergys Network.", "XML Validate Error");
                }
                cancelUIRun = false;
                base.OnRunWorkerCompleted(new RunWorkerCompletedEventArgs(this, null, true));
            }
            finally {
                if (httpWebResponse != null)
                    httpWebResponse.Close();
            }
        }
Beispiel #8
0
        public ValidationData ValidateCreateBooking(ClaimsPrincipal principal,
                                                    Member member,
                                                    CreateBookingModel model)
        {
            var      memberQuery    = _memberService.Members;
            var      userId         = principal.Identity.Name;
            var      validationData = new ValidationData();
            DateTime currentTime    = DateTime.UtcNow;

            if (!member.DepartmentMember.Any() && !member.AreaMember.Any())
            {
                validationData.Fail(code: AppResultCode.AccessDenied);
                return(validationData);
            }
            if (model.BookedDate == null)
            {
                validationData.Fail("Booked date must not be empty", AppResultCode.FailValidation);
            }
            if (model.NumOfPeople == null || model.NumOfPeople == 0)
            {
                validationData.Fail("Number of people is not valid", AppResultCode.FailValidation);
            }
            else if (model.FromTime == null || model.ToTime == null)
            {
                validationData.Fail(mess: "From time and to time must not be empty", AppResultCode.FailValidation);
            }
            else if (model.FromTime >= model.ToTime)
            {
                validationData.Fail(mess: "Time range is not valid", AppResultCode.FailValidation);
            }
            else
            {
                var bookedTime = model.BookedDate?.AddMinutes(model.FromTime.Value.TotalMinutes);
                if (currentTime >= bookedTime)
                {
                    validationData.Fail(mess: "Booked time must be greater than current", AppResultCode.FailValidation);
                }
            }
            if (model.UsingEmails == null || model.UsingEmails.Count == 0)
            {
                validationData.Fail(mess: "At lease one using email is required", AppResultCode.FailValidation);
            }
            else
            {
                var users = memberQuery.ByEmails(model.UsingEmails).Select(o => new
                {
                    user_id = o.UserId,
                    email   = o.Email
                }).ToList();
                var ids                = users.Select(o => o.user_id).ToList();
                var emails             = users.Select(o => o.email).ToList();
                var notFoundEmails     = model.UsingEmails.Where(o => !emails.Contains(o)).ToList();
                var notFoundEmailsList = string.Join(", ", notFoundEmails);
                if (notFoundEmails.Any())
                {
                    validationData.Fail(mess: $"One or more emails not found: {notFoundEmailsList}\n" +
                                        $"Maybe they need to log into the application at least once", AppResultCode.FailValidation);
                }
                else
                {
                    validationData.TempData["using_member_ids"] = ids;
                }
            }
            if (validationData.IsValid)
            {
                var availableRoom = _roomService.Rooms.Code(model.RoomCode)
                                    .AvailableForBooking(userId, Bookings, model.BookedDate.Value, model.FromTime.Value,
                                                         model.ToTime.Value, model.NumOfPeople.Value).FirstOrDefault();
                if (availableRoom == null)
                {
                    validationData.Fail("Room is not available for this booking", AppResultCode.FailValidation);
                }
                else
                {
                    validationData.TempData["booked_room"] = availableRoom;
                }
            }
            return(validationData);
        }
        private static object ValidateProperty(string name, Type itemType, object itemData, ValidationData vd)
        {
            if (itemData == null) return null;
            var m = itemData as IBabelModel;
            if (m!= null)
            {
                string prefix = vd.Prefix;
                vd.Prefix = (vd.Prefix.Length > 0) ? prefix + "/" + name : name;
                ValidateModel(m, vd);
                vd.Prefix = prefix;
                return itemData;
            }

            var l = itemData as IList;
            if (l!= null)
            {
                for(int i = 0; i < l.Count; i ++)
                {
                    ValidateProperty(name + "[" + i + "]", null, l[i], vd);
                }
                return itemData;
            }

            var d = itemData as IDictionary;
            if (d!= null)
            {
                foreach(DictionaryEntry kv in d)
                {
                    ValidateProperty(name + "[" + ((kv.Key == null) ? "null" : kv.Key.ToString()) + "]", null, kv.Value, vd);
                }
                return itemData;
            }

            return itemData;
        }
 private static void ValidateModel(IBabelModel obj, ValidationData vd)
 {
     var vc = new ValidationContext(obj, null, null);
     var res = new List<ValidationResult>();
     vd.IsValid = System.ComponentModel.DataAnnotations.Validator.TryValidateObject(obj, vc, res, true) & vd.IsValid;
     if(vd.Prefix.Length > 0)
     {
         foreach(var r in res)
         {
                 string[] members = (r.MemberNames == null) ? null : r.MemberNames.Select(m => vd.Prefix + "/" + m).ToArray();
                 vd.Results.Add(new ValidationResult(r.ErrorMessage, members));
         }
     }
     else
     {
         vd.Results.AddRange(res);
     }
     obj.RunOnChildren<ValidationData>(ValidateProperty, vd, false);
 }
        private void ViewValidationResult(IEnumerable<RuleValidationResult> results)
        {
            _validationCollection.Clear();
            foreach (var result in results)
            {
                var data = new ValidationData();
                var subtitle = result.Subtitle;
                if (subtitle != null)
                {
                    data.Text = string.Empty;
                    var first = true;
                    foreach (var text in subtitle.Text)
                    {
                        if (!first) data.Text += "|";
                        data.Text += text;
                        if (data.Text.Length > Maxtextsize) break;
                        first = false;
                    }
                    if (data.Text.Length > Maxtextsize)
                    {
                        data.Text.Substring(0, Maxtextsize-3);
                        data.Text += "...";
                    }

                    data.Number = subtitle.Number.ToString();

                    data.Time = string.Format("{0:00}:{1:00}:{2:00}:{3:000}", subtitle.Offset.Hours, subtitle.Offset.Minutes, subtitle.Offset.Seconds, subtitle.Offset.Milliseconds);
                }
                data.Rule = result.RuleDescription;
                data.Violation = result.ViolationDescription;
                data.Severity = result.Severity.ToString();

                _validationCollection.Add(data);
            }
        }
Beispiel #12
0
 public Interest(ValidationData vd)
 {
     jsonHelper = new JsonHelper();
     _vd        = vd;
 }
Beispiel #13
0
        /**
         * Add verification for a particular signature
         * @param signatureName the signature to validate (it may be a timestamp)
         * @param ocsp the interface to get the OCSP
         * @param crl the interface to get the CRL
         * @param certOption
         * @param level the validation options to include
         * @param certInclude
         * @return true if a validation was generated, false otherwise
         * @throws Exception
         */
        virtual public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude)
        {
            if (used)
            {
                throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
            }
            PdfPKCS7 pk = acroFields.VerifySignature(signatureName);

            LOGGER.Info("Adding verification for " + signatureName);
            X509Certificate[] xc = pk.Certificates;
            X509Certificate   cert;
            X509Certificate   signingCert = pk.SigningCertificate;
            ValidationData    vd          = new ValidationData();

            for (int k = 0; k < xc.Length; ++k)
            {
                cert = xc[k];
                LOGGER.Info("Certificate: " + cert.SubjectDN);
                if (certOption == CertificateOption.SIGNING_CERTIFICATE &&
                    !cert.Equals(signingCert))
                {
                    continue;
                }
                byte[] ocspEnc = null;
                if (ocsp != null && level != Level.CRL)
                {
                    ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, xc), null);
                    if (ocspEnc != null)
                    {
                        vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                        LOGGER.Info("OCSP added");
                    }
                }
                if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null)))
                {
                    ICollection <byte[]> cims = crl.GetEncoded(xc[k], null);
                    if (cims != null)
                    {
                        foreach (byte[] cim in cims)
                        {
                            bool dup = false;
                            foreach (byte[] b in vd.crls)
                            {
                                if (Arrays.AreEqual(b, cim))
                                {
                                    dup = true;
                                    break;
                                }
                            }
                            if (!dup)
                            {
                                vd.crls.Add(cim);
                                LOGGER.Info("CRL added");
                            }
                        }
                    }
                }
                if (certInclude == CertificateInclusion.YES)
                {
                    vd.certs.Add(xc[k].GetEncoded());
                }
            }
            if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
            {
                return(false);
            }
            validated[GetSignatureHashKey(signatureName)] = vd;
            return(true);
        }
Beispiel #14
0
        //private readonly Logger.Logger logger;
        //static HttpClient client = new HttpClient();

        //public string UrlValidation { get; set; }
        //public string DeviceID { get; set; }
        //public string RaceDayID { get; set; }

        public RestApiCommunicator(ValidationData validationData)
        {
            this.validationData = validationData;
        }
Beispiel #15
0
 /**
  * Add verification for a particular signature
  * @param signatureName the signature to validate (it may be a timestamp)
  * @param ocsp the interface to get the OCSP
  * @param crl the interface to get the CRL
  * @param certOption
  * @param level the validation options to include
  * @param certInclude
  * @return true if a validation was generated, false otherwise
  * @throws Exception
  */
 virtual public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude) {
     if (used)
         throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
     PdfPKCS7 pk = acroFields.VerifySignature(signatureName);
     LOGGER.Info("Adding verification for " + signatureName);
     X509Certificate[] xc = pk.Certificates;
     X509Certificate cert;
     X509Certificate signingCert = pk.SigningCertificate;
     ValidationData vd = new ValidationData();
     for (int k = 0; k < xc.Length; ++k) {
         cert = xc[k];
         LOGGER.Info("Certificate: " + cert.SubjectDN);
         if (certOption == CertificateOption.SIGNING_CERTIFICATE
             && !cert.Equals(signingCert)) {
             continue;
         }
         byte[] ocspEnc = null;
         if (ocsp != null && level != Level.CRL) {
             ocspEnc = ocsp.GetEncoded(cert, GetParent(cert, xc), null);
             if (ocspEnc != null) {
                 vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                 LOGGER.Info("OCSP added");
             }
         }
         if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null))) {
             ICollection<byte[]> cims = crl.GetEncoded(xc[k], null);
             if (cims != null) {
                 foreach (byte[] cim in cims) {
                     bool dup = false;
                     foreach (byte[] b in vd.crls) {
                         if (Arrays.AreEqual(b, cim)) {
                             dup = true;
                             break;
                         }
                     }
                     if (!dup) {
                         vd.crls.Add(cim);
                         LOGGER.Info("CRL added");
                     }
                 }
             }
         }
         if (certInclude == CertificateInclusion.YES) {
             vd.certs.Add(xc[k].GetEncoded());
         }
     }
     if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
         return false;
     validated[GetSignatureHashKey(signatureName)] = vd;
     return true;
 }
Beispiel #16
0
 /**
  * Alternative addVerification.
  * I assume that inputs are deduplicated.
  *
  * @throws IOException
  * @throws GeneralSecurityException
  *
  */
 virtual public bool AddVerification(String signatureName, ICollection<byte[]> ocsps, ICollection<byte[]> crls, ICollection<byte[]> certs) {
     if (used)
         throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
     ValidationData vd = new ValidationData();
     if (ocsps != null) {
         foreach (byte[] ocsp in ocsps) {
             vd.ocsps.Add(BuildOCSPResponse(ocsp));
         }
     }
     if (crls != null) {
         foreach (byte[] crl in crls) {
             vd.crls.Add(crl);
         }
     }
     if (certs != null) {
         foreach (byte[] cert in certs) {
             vd.certs.Add(cert);
         }
     }
     validated[GetSignatureHashKey(signatureName)] = vd;
     return true;
 }
        /**
         * Add verification for a particular signature
         * @param signatureName the signature to validate (it may be a timestamp)
         * @param ocsp the interface to get the OCSP
         * @param crl the interface to get the CRL
         * @param certOption
         * @param level the validation options to include
         * @param certInclude
         * @return true if a validation was generated, false otherwise
         * @throws Exception
         */
        public bool AddVerification(String signatureName, IOcspClient ocsp, ICrlClient crl, CertificateOption certOption, Level level, CertificateInclusion certInclude)
        {
            if (used)
            {
                throw new InvalidOperationException(MessageLocalization.GetComposedMessage("verification.already.output"));
            }
            PdfPKCS7 pk = acroFields.VerifySignature(signatureName);

            X509Certificate[] xc = pk.SignCertificateChain;
            ValidationData    vd = new ValidationData();

            for (int k = 0; k < xc.Length; ++k)
            {
                byte[] ocspEnc = null;
                if (ocsp != null && level != Level.CRL && k < xc.Length - 1)
                {
                    ocspEnc = ocsp.GetEncoded(xc[k], xc[k + 1], null);
                    if (ocspEnc != null)
                    {
                        vd.ocsps.Add(BuildOCSPResponse(ocspEnc));
                    }
                }
                if (crl != null && (level == Level.CRL || level == Level.OCSP_CRL || (level == Level.OCSP_OPTIONAL_CRL && ocspEnc == null)))
                {
                    byte[] cim = crl.GetEncoded(xc[k], null);
                    if (cim != null)
                    {
                        bool dup = false;
                        foreach (byte[] b in vd.crls)
                        {
                            if (Arrays.AreEqual(b, cim))
                            {
                                dup = true;
                                break;
                            }
                        }
                        if (!dup)
                        {
                            vd.crls.Add(cim);
                        }
                    }
                }
                if (certOption == CertificateOption.SIGNING_CERTIFICATE)
                {
                    break;
                }
            }
            if (vd.crls.Count == 0 && vd.ocsps.Count == 0)
            {
                return(false);
            }
            if (certInclude == CertificateInclusion.YES)
            {
                foreach (X509Certificate c in xc)
                {
                    vd.certs.Add(c.GetEncoded());
                }
            }
            validated[GetSignatureHashKey(signatureName)] = vd;
            return(true);
        }