private List <ValidationResult> ValidateInputXml(ValidationContent content, ValidationProfile profile)
        {
            string dataContent = System.Text.ASCIIEncoding.UTF8.GetString(content.Data);
            List <ValidationResult> results = new List <ValidationResult>();

            using (StringReader ms = new StringReader(dataContent))
            {
                XmlReader   sourceReader = XmlReader.Create(ms);
                XmlDocument sourceDoc    = new XmlDocument();

                try
                {
                    sourceDoc.LoadXml(dataContent);
                }
                catch (XmlException ex)
                {
                    results.Add(new ValidationResult()
                    {
                        FileName     = content.FileName,
                        ErrorMessage = "Could not load XML document: " + ex.Message
                    });
                    return(results);
                }

                XmlNamespaceManager nsManager = new XmlNamespaceManager(sourceDoc.NameTable);

                results.AddRange(
                    ValidateSchema(content.FileName, profile, content.Data, nsManager));

                results.AddRange(
                    ValidateSchematron(profile.SchematronValidator, content));
            }

            return(results);
        }
Exemplo n.º 2
0
        private List <ValidationResult> ValidateSchema(string fileName, ValidationProfile profile, byte[] sourceData, XmlNamespaceManager nsManager)
        {
            Dictionary <string, string> namespaces = null;

#pragma warning disable CS0618 // Type or member is obsolete
            XmlSchemaCollection schemas = new XmlSchemaCollection();
#pragma warning restore CS0618 // Type or member is obsolete
            schemas.Add(Helper.GetSchema(profile.SchemaLocation, out namespaces));

            XmlParserContext context = new XmlParserContext(null, nsManager, null, XmlSpace.None);

            using (MemoryStream sourceStream = new MemoryStream(sourceData))
            {
#pragma warning disable CS0618 // Type or member is obsolete
                XmlValidatingReader validatingReader = new XmlValidatingReader(sourceStream, XmlNodeType.Document, context);
#pragma warning restore CS0618 // Type or member is obsolete
                validatingReader.ValidationType = ValidationType.Schema;
                validatingReader.Schemas.Add(schemas);

                List <ValidationResult> results   = new List <ValidationResult>();
                ValidationResult        newResult = null;

                validatingReader.ValidationEventHandler += new ValidationEventHandler(delegate(object sender, ValidationEventArgs e)
                {
                    newResult = new ValidationResult()
                    {
                        FileName     = fileName,
                        ErrorMessage = e.Message,
                        Severity     = e.Severity.ToString(),
                        TestContext  = "Schema",
                        Test         = "N/A",
                        Location     = "N/A",
                        LineNumber   = e.Exception.LineNumber
                    };

                    results.Add(newResult);
                });

                while (validatingReader.Read())
                {
                    if (newResult != null)
                    {
                        newResult.Test = validatingReader.Name;
                        results.Add(newResult);
                        newResult = null;
                    }
                }

                return(results);
            }
        }
        /// <summary>
        /// Validates each of the contents and returns the validation results
        /// </summary>
        /// <param name="profile">The profile to validate the content against</param>
        /// <param name="contents">The content to validate against the profile</param>
        /// <returns></returns>
        public List <ValidationResult> ValidateDocument(int profileId, List <ValidationContent> contents)
        {
            List <ValidationResult> results = new List <ValidationResult>();

            using (TemplateDatabaseDataSource tdb = new TemplateDatabaseDataSource())
            {
                // Get the requested profile
                ValidationProfile profile = null;

                try
                {
                    profile = GetValidationProfile(tdb, profileId);
                }
                catch (Exception ex)
                {
                    results.Add(new ValidationResult()
                    {
                        ErrorMessage = "Preparing validation package failed with the following error: " + ex.Message,
                        Severity     = "Critical"
                    });

                    return(results);
                }

                foreach (ValidationContent cContent in contents)
                {
                    try
                    {
                        // Validate the document with the profile
                        results.AddRange(ValidateInputXml(cContent, profile));
                    }
                    catch (Exception ex)
                    {
                        results.Add(new ValidationResult()
                        {
                            ErrorMessage = "Validating document resulted in a critical system error: " + ex.Message,
                            FileName     = cContent.FileName,
                            Severity     = "Critical"
                        });
                    }
                }
            }

            return(results);
        }
        private ValidationProfile GetStoredValidationProfile(IObjectRepository tdb, int implementationGuideFileId)
        {
            ValidationProfile           foundProfile     = loadedProfiles.SingleOrDefault(y => y.Id == implementationGuideFileId);
            ImplementationGuideFileData latestSchematron = (from igf in tdb.ImplementationGuideFiles
                                                            join igfd in tdb.ImplementationGuideFileDatas on igf.Id equals igfd.ImplementationGuideFileId
                                                            where igf.Id == implementationGuideFileId
                                                            select igfd).OrderByDescending(y => y.UpdatedDate).FirstOrDefault();
            ImplementationGuideFile igFile = tdb.ImplementationGuideFiles.Single(y => y.Id == implementationGuideFileId);
            int implementationGuideId      = igFile.ImplementationGuideId;

            if (foundProfile != null && latestSchematron != null && foundProfile.LastUpdated != latestSchematron.UpdatedDate)
            {
                lock (loadedProfilesLock)
                {
                    loadedProfiles.Remove(foundProfile);
                }

                foundProfile = null;
            }

            // The profile is not already loaded
            if (foundProfile == null)
            {
                lock (loadedProfilesLock)
                {
                    string type           = igFile.ImplementationGuide.ImplementationGuideType.Name;
                    string schemaLocation = Path.Combine(
                        Trifolia.Shared.Helper.GetSchemasDirectory(igFile.ImplementationGuide.ImplementationGuideType.Name),
                        igFile.ImplementationGuide.ImplementationGuideType.SchemaLocation);

                    foundProfile = new ValidationProfile()
                    {
                        Id = implementationGuideFileId
                    };

                    List <ImplementationGuideFile> schHelperFiles = (from pigf in tdb.ImplementationGuideFiles
                                                                     join igf in tdb.ImplementationGuideFiles on pigf.ImplementationGuideId equals igf.ImplementationGuideId
                                                                     where pigf.ImplementationGuideId == implementationGuideId && igf.ContentType == ImplementationGuideFile.ContentTypeSchematronHelper
                                                                     select igf).ToList();

                    IValidator schValidator = SchematronValidationFactory.NewValidator(ASCIIEncoding.UTF8.GetString(latestSchematron.Data));

                    List <ImplementationGuideFile> additionalFiles = (from pigf in tdb.ImplementationGuideFiles
                                                                      join igf in tdb.ImplementationGuideFiles on pigf.ImplementationGuideId equals igf.ImplementationGuideId
                                                                      where pigf.Id == implementationGuideFileId && igf.ContentType == ImplementationGuideFile.ContentTypeVocabulary
                                                                      select igf).ToList();

                    foreach (ImplementationGuideFile cAdditionalFile in additionalFiles)
                    {
                        ImplementationGuideFileData latestVersion = cAdditionalFile.Versions
                                                                    .OrderByDescending(y => y.UpdatedDate)
                                                                    .FirstOrDefault();

                        schValidator.AddInclude(cAdditionalFile.FileName, latestVersion.Data);
                    }

                    foundProfile.SchematronValidator = schValidator;
                    foundProfile.LastUpdated         = latestSchematron.UpdatedDate;
                    foundProfile.Type           = type;
                    foundProfile.SchemaPrefix   = igFile.ImplementationGuide.ImplementationGuideType.SchemaPrefix;
                    foundProfile.SchemaUri      = igFile.ImplementationGuide.ImplementationGuideType.SchemaURI;
                    foundProfile.SchemaLocation = schemaLocation;

                    loadedProfiles.Add(foundProfile);
                }
            }

            return(foundProfile);
        }