Inheritance: System.Validation, ITestable
Example #1
0
        /*
        protected void SetupStream(IValidationSerializer serializer, out Stream stream, out Encoding encoding)
        {
            Response.ContentType = "text/xml";
           // stream = Response.OutputStream;
            stream = new MemoryStream();
            encoding = Response.Output.Encoding;
        }*/
        protected byte[] Validate(long byteCount, TextReader tr, string id)
        {
            byte[] bytes = new byte[0];

            try
            {
                IValidationSerializer serializer = GetSerializer();

                if (serializer != null)
                {
                    string iCalText = tr.ReadToEnd();

                    try
                    {
                        var ms = new MemoryStream(encoding.GetBytes(iCalText));
                        var ical = DDay.iCal.iCalendar.LoadFromStream(ms);
                        ms.Close();
                    }
                    catch (Exception e)
                    {
                        Utils.StoreExceptionBlob("Validate: " + e.Message + e.StackTrace);
                        bytes = ExceptionMessage(e);
                        return bytes;
                    }

                    if (SelectedRuleset != null)
                    {
                        serializer.Ruleset = SelectedRuleset;

                        RulesetValidator rulesetValidator = new RulesetValidator(ResourceManager, SelectedRuleset, iCalText);

                        if (rulesetValidator != null)
                        {
                            serializer.ValidationResults = rulesetValidator.Validate();

                            // Set the original text for the validation
                            serializer.ValidationResults.CalendarText = iCalText;
                            serializer.ValidationResults.CalendarPath = CalendarPath;
                            serializer.ValidationResults.ByteCount = byteCount;
                        }

                        Stream stream = new MemoryStream();

                        try
                        {
                            var permalink = Utils.MakePermalinkUrl(id);
                            serializer.Serialize(stream, encoding, permalink);
                            bytes = new byte[stream.Length];
                            stream.Seek(0, 0);
                            stream.Read(bytes, 0, (int)stream.Length);
                        }
                        catch (Exception e)
                        {
                            bytes = ExceptionMessage(e);
                            Utils.StoreExceptionBlob("Validate: " + e.Message + e.StackTrace);
                        }
                        finally
                        {
                            stream.Close();
                        }
                    }
                }
            }

            catch (Exception e)
            {
                bytes = ExceptionMessage(e);
                Utils.StoreExceptionBlob("Validate:" + e.Message + e.StackTrace);
            }

            finally
            {
                var results_blob = Utils.MakeResultsBlob(id);
                results_blob.UploadByteArray(bytes);
            }

            return bytes;
        }
Example #2
0
        static void ValidateFile(IXmlDocumentProvider docProvider, IValidationRuleset selectedRuleset)
        {
            IValidationSerializer serializer = GetSerializer(docProvider);
            bool needsMoreArguments = false;

            if (serializer != null)
            {
                string iCalText = null;
                long byteCount = 0;

                if (selectedRuleset != null)
                {
                    serializer.Ruleset = selectedRuleset;

                    if (_Arguments.Contains(_FileArgument))
                    {
                        // Load the calendar from a local file
                        Console.Write(ResourceManager.GetString("loadingCalendar"));
                        FileStream fs = new FileStream(_Arguments[_FileArgument].Value, FileMode.Open, FileAccess.Read);
                        if (fs != null)
                        {
                            // Get the calendar path so it can be reported later
                            _CalendarPath = Path.GetFullPath(_Arguments[_FileArgument].Value);

                            StreamReader sr = new StreamReader(fs);
                            byteCount = fs.Length;
                            iCalText = sr.ReadToEnd();
                            sr.Close();
                        }
                        Console.WriteLine(ResourceManager.GetString("Done"));
                    }
                    else if (_Arguments.Contains(_UriArgument))
                    {
                        // Load the calendar from a Uri
                        Console.Write(ResourceManager.GetString("loadingCalendar"));

                        Uri uri = new Uri(_Arguments[_UriArgument].Value);
                        string
                            username = null,
                            password = null;

                        // Determine if credentials were included in the Uri
                        // NOTE: this is not recommended practice for numerous
                        // security reasons.
                        if (!string.IsNullOrEmpty(uri.UserInfo))
                        {
                            // Extract the embedded credentials from the Uri
                            string[] parts = uri.UserInfo.Split(':');
                            if (parts.Length == 2)
                            {
                                username = parts[0];
                                password = parts[1];
                            }
                        }

                        if (_Arguments.Contains(_UsernameArgument))
                        {
                            username = _Arguments[_UsernameArgument].Value;
                            if (_Arguments.Contains(_PasswordArgument))
                                password = _Arguments[_PasswordArgument].Value;
                        }

                        WebClient client = new WebClient();
                        if (username != null && password != null)
                            client.Credentials = new System.Net.NetworkCredential(username, password);

                        // Get the calendar path so it can be reported later
                        _CalendarPath = uri.OriginalString;
                        iCalText = client.DownloadString(uri);
                        byteCount = client.Encoding.GetByteCount(iCalText);

                        Console.WriteLine(ResourceManager.GetString("Done"));
                    }
                    else
                    {
                        needsMoreArguments = true;
                    }

                    if (needsMoreArguments)
                    {
                        WriteDescription();
                    }
                    else
                    {
                        if (iCalText == null)
                        {
                            throw new Exception(ResourceManager.GetString("calendarNotFound"));
                        }
                        else
                        {
                            RulesetValidator rulesetValidator = new RulesetValidator(ResourceManager, selectedRuleset, iCalText);

                            if (rulesetValidator != null)
                            {
                                Console.Write(string.Format(
                                    ResourceManager.GetString("validatingCalendar"),
                                    ResourceManager.GetString(selectedRuleset.NameString)
                                ));

                                serializer.ValidationResults = rulesetValidator.Validate();

                                // Set the original text for the validation
                                serializer.ValidationResults.CalendarPath = _CalendarPath;
                                serializer.ValidationResults.CalendarText = iCalText;
                                serializer.ValidationResults.ByteCount = byteCount;

                                Console.WriteLine(ResourceManager.GetString("done"));
                            }
                        }

                        Stream stream;
                        Encoding encoding;
                        SetupStream(serializer, out stream, out encoding);

                        try
                        {
                            serializer.Serialize(stream, encoding, permalink: "");
                        }
                        finally
                        {
                            stream.Close();
                        }

                        // Open the output file, if requested
                        OpenOutputFile(serializer);
                    }
                }
            }
        }
Example #3
0
        static void ValidateFile(string filename, IXmlDocumentProvider docProvider, IValidationRuleset selectedRuleset)
        {
            IValidationSerializer serializer = GetSerializer(docProvider);
            bool needsMoreArguments = false;

            if (serializer != null)
            {
                string iCalText = null;
                long byteCount = 0;

                if (selectedRuleset != null)
                {
                    serializer.Ruleset = selectedRuleset;

                    // Load the calendar from a local file
                    Console.Write(ResourceManager.GetString("loadingCalendar"));
                    FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
                    if (fs != null)
                    {
                        // Get the calendar path so it can be reported later
                        _CalendarPath = Path.GetFullPath(filename);

                        StreamReader sr = new StreamReader(fs);
                        byteCount = fs.Length;
                        iCalText = sr.ReadToEnd();
                        sr.Close();
                    }
                    Console.WriteLine(ResourceManager.GetString("Done"));

                    if (iCalText == null)
                    {
                        throw new Exception(ResourceManager.GetString("calendarNotFound"));
                    }
                    else
                    {
                        RulesetValidator rulesetValidator = new RulesetValidator(ResourceManager, selectedRuleset, iCalText);

                        if (rulesetValidator != null)
                        {
                            Console.Write(string.Format(
                                ResourceManager.GetString("validatingCalendar"),
                                ResourceManager.GetString(selectedRuleset.NameString)
                            ));

                            serializer.ValidationResults = rulesetValidator.Validate();

                            // Set the original text for the validation
                            serializer.ValidationResults.CalendarPath = _CalendarPath;
                            serializer.ValidationResults.CalendarText = iCalText;
                            serializer.ValidationResults.ByteCount = byteCount;

                            Console.WriteLine(ResourceManager.GetString("done"));
                        }
                    }

                    Stream stream;
                    Encoding encoding;
                    SetupStream(serializer, out stream, out encoding);

                    try
                    {
                        serializer.Serialize(stream, encoding, permalink: "");
                    }
                    finally
                    {
                        stream.Close();
                    }
                }
            }
        }
Example #4
0
        static void SelfTest(IXmlDocumentProvider docProvider, IValidationRuleset selectedRuleset)
        {
            IValidationSerializer serializer = GetSerializer(docProvider);
            if (serializer != null)
            {
                Stream stream;
                Encoding encoding;
                SetupStream(serializer, out stream, out encoding);

                if (selectedRuleset != null)
                {
                    serializer.Ruleset = selectedRuleset;

                    Console.WriteLine(string.Format(
                        ResourceManager.GetString("performingSelfTest"),
                        ResourceManager.GetString(selectedRuleset.NameString))
                    );

                    RulesetValidator validator = new RulesetValidator(ResourceManager, selectedRuleset);
                    validator.TestProgress +=
                        delegate(object sender, TestProgressEventArgs e)
                        {
                            Console.CursorLeft = 0;
                            Console.Write(
                                string.Format(
                                    ResourceManager.GetString("testProgress"),
                                    e.Passed + e.Failed + e.NotRun,
                                    e.TotalTests
                                )
                            );
                        };

                    serializer.TestResults = validator.Test();
                }

                try
                {
                    serializer.Serialize(stream, encoding, permalink:"");
                }
                finally
                {
                    stream.Close();
                }

                // Open the output file, if requested
                OpenOutputFile(serializer);
            }
        }
        public ITestResult[] Test()
        {
            if (Ruleset != null)
            {
                List<ITestResult> results = new List<ITestResult>();

                int testsToRun = 0;
                foreach (IValidationRule rule in Ruleset.Rules)
                {
                    if (rule.Tests != null)
                        testsToRun += rule.Tests.Length;
                }

                OnTestStart(testsToRun);

                bool validatorsVerified = false;
                foreach (IValidationRule rule in Ruleset.Rules)
                {
                    if (rule.Tests != null)
                    {
                        foreach (ITest test in rule.Tests)
                        {
                            Debug.WriteLineWithTimestamp("Loading validators for test...");

                            // Load the ruleset validator using the test data.
                            RulesetValidator validator = new RulesetValidator(ResourceManager, Ruleset, test.iCalendarText, !validatorsVerified);
                            validatorsVerified = true;

                            Debug.WriteLineWithTimestamp("Done.");

                            // Validate the calendar!
                            IValidationResultCollection validationResults = validator.Validate();
                            TestResult result = new TestResult(ResourceManager, rule.Name, test, false);

                            Debug.WriteLineWithTimestamp("Interpreting test results...");

                            // Interpret the results...
                            if (test.Type == TestType.Fail)
                            {
                                if (BoolUtil.IsTrue(validationResults.Passed))
                                {
                                    // The validation passed, but the test expected it to fail.
                                    TestError error = new TestError(ResourceManager, "failExpectedError", rule.Name, validationResults);
                                    error.Message = string.Format(error.Message, test.ExpectedError);
                                    result.Error = error;
                                }
                                else
                                {
                                    IValidationResultInfo[] details = validationResults.Details;
                                    if (details.Length == 1 && !string.Equals(details[0].Name, test.ExpectedError))
                                    {
                                        // Validation failed (as expected), however, it failed with the incorrect error.
                                        TestError error = new TestError(ResourceManager, "failWithIncorrectError", rule.Name, validationResults);
                                        error.Message = string.Format(error.Message, details[0].Name, test.ExpectedError);
                                        result.Error = error;
                                    }
                                    else if (details.Length > 1)
                                    {
                                        // Validation failed (as expected), however, it failed with more than one error.
                                        TestError error = new TestError(ResourceManager, "failWithMoreThanOneError", rule.Name, validationResults);
                                        error.Message = string.Format(error.Message, test.ExpectedError);
                                        result.Error = error;
                                    }
                                    else
                                    {
                                        // The test passed, meaning the result was exactly as expected.
                                        result.Passed = true;
                                    }
                                }
                            }
                            else
                            {
                                if (BoolUtil.IsTrue(validationResults.Passed))
                                {
                                    // The test passed, meaning the result was exactly as expected.
                                    result.Passed = true;
                                }
                                else
                                {
                                    // The validation was expected to succeed, but one or more errors occurred.
                                    result.Passed = false;
                                    result.Error = new TestError(ResourceManager, "passExpectedError", rule.Name, validationResults);
                                }
                            }

                            Debug.WriteLineWithTimestamp("Done.");

                            // Notify via event the result of the test.
                            if (result.Passed == null)
                                OnTestNotRun(result);
                            else if (BoolUtil.IsTrue(result.Passed))
                                OnTestPassed(result);
                            else
                                OnTestFailed(result);

                            results.Add(result);

                            // If we encounter a fatal error, then we cannot continue processing
                            // other errors. In other words, even though a single error was caused,
                            // the fact that it was fatal may have side effects and cause errors
                            // in almost every validator (i.e. a calendar with parsing errors).
                            if (validationResults.IsFatal)
                                break;
                        }
                    }
                }

                return results.ToArray();
            }
            // FIXME: else throw exception?
            else return new ITestResult[0];
        }