private static IEnumerable <esriGeometryType> GetSupportedErrorRepoGeometryTypes( IVerificationContext verificationContext) { if (verificationContext.NoGeometryIssueDataset != null) { yield return(esriGeometryType.esriGeometryNull); } if (verificationContext.MultipointIssueDataset != null) { yield return(esriGeometryType.esriGeometryMultipoint); } if (verificationContext.LineIssueDataset != null) { yield return(esriGeometryType.esriGeometryPolyline); } if (verificationContext.PolygonIssueDataset != null) { yield return(esriGeometryType.esriGeometryPolygon); } if (verificationContext.MultiPatchIssueDataset != null) { yield return(esriGeometryType.esriGeometryMultiPatch); } }
GetIssueDatasetsByGeometryType([NotNull] IVerificationContext context) { Assert.ArgumentNotNull(context, nameof(context)); var properties = new Dictionary <esriGeometryType, Func <IVerificationContext, IErrorDataset> > { { esriGeometryType.esriGeometryNull, c => c.NoGeometryIssueDataset }, { esriGeometryType.esriGeometryPolygon, c => c.PolygonIssueDataset }, { esriGeometryType.esriGeometryPolyline, c => c.LineIssueDataset }, { esriGeometryType.esriGeometryMultipoint, c => c.MultipointIssueDataset }, { esriGeometryType.esriGeometryMultiPatch, c => c.MultiPatchIssueDataset } }; var result = new Dictionary <esriGeometryType, IErrorDataset>(); foreach ( KeyValuePair <esriGeometryType, Func <IVerificationContext, IErrorDataset> > pair in properties) { Func <IVerificationContext, IErrorDataset> getIssueDataset = pair.Value; IErrorDataset issueDataset = getIssueDataset(context); if (issueDataset != null) { result.Add(pair.Key, issueDataset); } } return(result); }
/// <summary> /// Verification exception on missing KSI signature publication record /// </summary> public virtual void TestSignatureMissingPublicationRecord(IVerificationContext context = null) { DoesThrow <KsiVerificationException>(delegate { Rule.Verify(context ?? new TestVerificationContext(TestUtil.GetSignature())); }, "Publication record is missing from KSI signature"); }
/// <summary> /// Verification exception on missing KSI signature calendar hash chain /// </summary> public void TestSignatureMissingCalendarHashChain(IVerificationContext context) { DoesThrow <KsiVerificationException>(delegate { Rule.Verify(context); }, "Calendar hash chain is missing from KSI signature"); }
/// <summary> /// Initializes a new instance of the <see cref="QualityErrorRepositoryBase"/> class. /// </summary> /// <param name="verificationContext">The model context.</param> /// <param name="testsByQualityCondition">The dictionary of tests by quality condition. /// It can be empty in case the <see cref="AddError"/> method is never used and the /// <see cref="VerifiedQualityConditions"/> property is set.</param> /// <param name="datasetResolver">The dataset resolver.</param> /// <param name="qualityConditionRepository">The quality condition repository.</param> protected QualityErrorRepositoryBase( [NotNull] IVerificationContext verificationContext, [NotNull] Dictionary <QualityCondition, IList <ITest> > testsByQualityCondition, [NotNull] IQualityConditionObjectDatasetResolver datasetResolver, [NotNull] IQualityConditionRepository qualityConditionRepository) { Assert.ArgumentNotNull(verificationContext, nameof(verificationContext)); Assert.ArgumentNotNull(testsByQualityCondition, nameof(testsByQualityCondition)); Assert.ArgumentNotNull(datasetResolver, nameof(datasetResolver)); Assert.ArgumentNotNull(qualityConditionRepository, nameof(qualityConditionRepository)); _verificationContext = verificationContext; _testsByQualityCondition = testsByQualityCondition; IssueDatasets = new QualityErrorRepositoryDatasets(_verificationContext); VerifiedQualityConditions = testsByQualityCondition.Keys; _userName = EnvironmentUtils.UserDisplayName; _datasetResolver = datasetResolver; _qualityConditionRepository = qualityConditionRepository; int gdbMajorRelease = ((IGeodatabaseRelease) verificationContext.PrimaryWorkspaceContext.Workspace).MajorVersion + 7; _isPre10Geodatabase = gdbMajorRelease < 10; }
public static IEnumerable <IErrorDataset> GetIssueDatasets( [NotNull] IVerificationContext context) { Assert.ArgumentNotNull(context, nameof(context)); if (context.NoGeometryIssueDataset != null) { yield return(context.NoGeometryIssueDataset); } if (context.MultipointIssueDataset != null) { yield return(context.MultipointIssueDataset); } if (context.MultiPatchIssueDataset != null) { yield return(context.MultiPatchIssueDataset); } if (context.LineIssueDataset != null) { yield return(context.LineIssueDataset); } if (context.PolygonIssueDataset != null) { yield return(context.PolygonIssueDataset); } }
/// <summary> /// Check if verification context is valid. /// </summary> /// <param name="context">verification context</param> public static void CheckVerificationContext(IVerificationContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { IKsiSignature signature = GetSignature(context); PublicationData publicationData; if (context.UserPublication != null) { publicationData = context.UserPublication; } else { PublicationRecordInPublicationFile publicationRecord = GetNearestPublicationRecord(GetPublicationsFile(context), signature.AggregationTime, true); if (publicationRecord == null) { // if suitable publication record does not exist in publications file then return NA return(new VerificationResult(GetRuleName(), VerificationResultCode.Na, VerificationError.Gen02)); } publicationData = publicationRecord.PublicationData; } CalendarHashChain extendedCalendarHashChain = GetExtendedCalendarHashChain(context, publicationData.PublicationTime); HashAlgorithm deprecatedHashAlgorithm = GetDeprecatedHashAlgorithm(extendedCalendarHashChain); if (deprecatedHashAlgorithm != null) { Logger.Debug("Extender response calendar hash chain contains deprecated aggregation algorithm at publication time. Algorithm: {0}; Publication time: {1}", deprecatedHashAlgorithm.Name, extendedCalendarHashChain.PublicationTime); return(new VerificationResult(GetRuleName(), VerificationResultCode.Na, VerificationError.Gen02)); } return(new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { CalendarHashChain calendarHashChain = GetSignature(context).CalendarHashChain; // If calendar hash chain is missing, verification successful if (calendarHashChain == null) { return(new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); } IEnumerator <CalendarHashChain.Link> linksEnumerator = calendarHashChain.GetLeftLinksEnumerator(); CalendarHashChain.Link link = linksEnumerator.MoveNext() ? linksEnumerator.Current : null; while (link != null) { if (link.Value.Algorithm.IsObsolete(calendarHashChain.PublicationTime)) { Logger.Debug("Calendar hash chain contains obsolete aggregation algorithm at publication time. Algorithm: {0}; Publication time: {1}", link.Value.Algorithm.Name, calendarHashChain.PublicationTime); return(new VerificationResult(GetRuleName(), VerificationResultCode.Fail, VerificationError.Int16)); } link = linksEnumerator.MoveNext() ? linksEnumerator.Current : null; } return(new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
/// <summary> /// Verification exception on missing KSI signature calendar authentication record /// </summary> public void TestSignatureMissingCalendarAuthRecord(IVerificationContext context) { DoesThrow <KsiVerificationException>(delegate { Rule.Verify(context); }, "Calendar authentication record in missing from KSI signature"); }
public QualityVerification Verify( [NotNull] IBackgroundVerificationInputs backgroundVerificationInputs, [CanBeNull] ITrackCancel trackCancel) { QualitySpecification qualitySpecification = null; _backgroundVerificationInputs = backgroundVerificationInputs; _domainTransactions.UseTransaction( delegate { backgroundVerificationInputs.LoadInputsTx( _domainTransactions, trackCancel, OnProgress); qualitySpecification = PrepareQualitySpecificationTx(backgroundVerificationInputs); }); IVerificationContext verificationContext = Assert.NotNull(backgroundVerificationInputs.VerificationContext); VerificationServiceParameters parameters = Assert.NotNull(backgroundVerificationInputs.VerificationParameters); QualityVerification verification = Verify( verificationContext, qualitySpecification, parameters, backgroundVerificationInputs.VerifiedObjects); if (parameters.SaveVerificationStatistics && !verification.Cancelled) { backgroundVerificationInputs.SaveVerification(verification, _domainTransactions); } return(verification); }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { CheckVerificationContext(context); return(context.IsExtendingAllowed ? new VerificationResult(GetRuleName(), VerificationResultCode.Ok) : new VerificationResult(GetRuleName(), VerificationResultCode.Na, VerificationError.Gen02)); }
public void LoadDataSchemaFile(TextReader reader, IVerificationContext context) { Parsing.DataSchema parsedSchema; XmlSerializer serializer = new XmlSerializer(typeof(Parsing.DataSchema)); parsedSchema = (Parsing.DataSchema)serializer.Deserialize(reader); ApplyParsedSchema(parsedSchema, context); }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { CheckVerificationContext(context); return(context.UserPublication == null ? new VerificationResult(GetRuleName(), VerificationResultCode.Na, VerificationError.Gen02) : new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { CalendarAuthenticationRecord calendarAuthenticationRecord = GetCalendarAuthenticationRecord(GetSignature(context)); SignatureData signatureData = calendarAuthenticationRecord.SignatureData; return(GetPublicationsFile(context).FindCertificateById(signatureData.GetCertificateId()) == null ? new VerificationResult(GetRuleName(), VerificationResultCode.Fail, VerificationError.Key01) : new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { PublicationData userPublication = GetUserPublication(context); CalendarHashChain extendedCalendarHashChain = GetExtendedCalendarHashChain(context, userPublication.PublicationTime); return(extendedCalendarHashChain.PublicationData.PublicationHash != userPublication.PublicationHash ? new VerificationResult(GetRuleName(), VerificationResultCode.Fail, VerificationError.Pub01) : new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { ulong aggregationTime = GetSignature(context).AggregationTime; ulong userPublicationTime = GetUserPublication(context).PublicationTime; return(aggregationTime >= userPublicationTime ? new VerificationResult(GetRuleName(), VerificationResultCode.Na, VerificationError.Gen02) : new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { CalendarHashChain calendarHashChain = GetCalendarHashChain(GetSignature(context)); CalendarHashChain extendedSignatureCalendarHashChain = GetExtendedCalendarHashChain(context, calendarHashChain.PublicationTime); return(calendarHashChain.OutputHash != extendedSignatureCalendarHashChain.OutputHash ? new VerificationResult(GetRuleName(), VerificationResultCode.Fail, VerificationError.Cal01) : new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { ulong publicationTime = GetUserPublication(context).PublicationTime; CalendarHashChain extendedCalendarHashChain = GetExtendedCalendarHashChain(context, publicationTime); return(extendedCalendarHashChain.InputHash != GetSignature(context).GetLastAggregationHashChainRootHash() ? new VerificationResult(GetRuleName(), VerificationResultCode.Fail, VerificationError.Pub03) : new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
private static void RunTests(TestingRow testingRow, string testDataDir) { Console.WriteLine(testingRow); IKsiSignature signature; try { signature = new KsiSignatureFactory(new EmptyVerificationPolicy()).Create(File.ReadAllBytes(Path.Combine(TestSetup.LocalPath, testDataDir + testingRow.FileName))); } catch (KsiException) { if (testingRow.ActionName != "parsing") { throw; } return; } IVerificationContext verificationContext = GetVerificationContext(testingRow, signature, testDataDir, testingRow.ActionName == "userPublication"); switch (testingRow.ActionName) { case "userPublication": Verify(testingRow, new PublicationBasedVerificationPolicy(), verificationContext); break; case "publicationsFile": Verify(testingRow, new PublicationBasedVerificationPolicy(), verificationContext); break; case "key": Verify(testingRow, new KeyBasedVerificationPolicy(), verificationContext); break; case "internal": Verify(testingRow, new InternalVerificationPolicy(), verificationContext); break; case "calendar": Verify(testingRow, new CalendarBasedVerificationPolicy(), verificationContext); break; case "parsing": Assert.Fail("Parsing exception expected but nothing thrown."); break; case "not-implemented": break; default: throw new Exception("Unknown testing action: " + testingRow.ActionName); } }
protected void Verify(IVerificationContext context, VerificationResultCode expectedResultCode, VerificationError expectedVerificationError = null) { VerificationResult verificationResult = Rule.Verify(context); Assert.AreEqual(expectedResultCode, verificationResult.ResultCode, "Unexpected verification result code"); if (expectedResultCode == VerificationResultCode.Fail) { Assert.AreEqual(expectedVerificationError?.Code, verificationResult.VerificationError.Code, "Unexpected verification error code"); } }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { IKsiSignature signature = GetSignature(context); ulong levelCorrection = signature.IsRfc3161Signature ? 0 : signature.GetAggregationHashChains()[0].GetChainLinks()[0].LevelCorrection; return(context.DocumentHashLevel > levelCorrection ? new VerificationResult(GetRuleName(), VerificationResultCode.Fail, VerificationError.Gen03) : new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
/// <summary> /// Check invalid extended calendar chain returned by context extension function /// </summary> /// <param name="context"></param> public void TestSignatureWithInvalidContextExtendFunctions(IVerificationContext context = null) { DoesThrow <KsiVerificationException>(delegate { Rule.Verify(context ?? new TestVerificationContext() { Signature = TestUtil.GetSignature(Resources.KsiSignature_Ok_With_Publication_Record) }); }, "Received invalid extended calendar hash chain from context extension function: null"); }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { IKsiSignature signature = GetSignature(context); ulong publicationTime = GetCalendarHashChain(signature).PublicationData.PublicationTime; CalendarHashChain extendedCalendarHashChain = GetExtendedCalendarHashChain(context, publicationTime); return(GetCalendarHashChain(signature).AreRightLinksEqual(extendedCalendarHashChain) ? new VerificationResult(GetRuleName(), VerificationResultCode.Ok) : new VerificationResult(GetRuleName(), VerificationResultCode.Fail, VerificationError.Cal04)); }
private static void Verify(TestingRow data, VerificationPolicy policy, IVerificationContext context) { VerificationResult result = policy.Verify(context); if (!data.VerificationResultMatch(result.VerificationError)) { Assert.Fail("Unexpected verification result: " + (result.VerificationError == null ? "OK" : result.VerificationError.Code) + "; Expected result: " + data.ErrorCode); } }
private VerificationResult DoVerification(IVerificationContext context, bool writeLog = true) { VerificationRule verificationRule = FirstRule; List <VerificationResult> verificationResults = new List <VerificationResult>(); try { while (verificationRule != null) { VerificationPolicy policy = verificationRule as VerificationPolicy; VerificationResult result = policy != null?policy.DoVerification(context, false) : verificationRule.Verify(context); verificationResults.Add(result); verificationRule = verificationRule.NextRule(result.ResultCode); } } catch (Exception e) { KsiVerificationException ksiVerificationException = e as KsiVerificationException; VerificationResult resultFromException = ksiVerificationException?.VerificationResult; // if inner policy has thrown an exception and verification result is set within the exception then add this result to result list. // otherwise add a new result. verificationResults.Add(resultFromException ?? new VerificationResult(verificationRule?.GetRuleName(), VerificationResultCode.Na)); VerificationResult result = new VerificationResult(GetRuleName(), verificationResults); // write log only when topmost policy if (writeLog) { Logger.Warn("Error occured on rule {0}: {1}{2}{3}", verificationRule?.GetRuleName(), e, Environment.NewLine, result); throw; } if (resultFromException != null) { ksiVerificationException.VerificationResult = result; throw ksiVerificationException; } throw new KsiVerificationException(e.Message, e) { VerificationResult = result }; } VerificationResult verificationResult = new VerificationResult(GetRuleName(), verificationResults); // write log only when topmost policy if (writeLog) { Logger.Debug(Environment.NewLine + verificationResult); } return(verificationResult); }
/// <summary> /// Get publications file form verification context /// </summary> /// <param name="context">verification context</param> /// <returns>publications file</returns> public static IPublicationsFile GetPublicationsFile(IVerificationContext context) { CheckVerificationContext(context); if (context.PublicationsFile == null) { throw new KsiVerificationException("Invalid publications file in context: null."); } return(context.PublicationsFile); }
/// <summary> /// Get extended calendar hash chain from given publication time. /// </summary> /// <param name="context">verification context</param> /// <param name="publicationTime">publication time</param> /// <returns></returns> public static CalendarHashChain GetExtendedCalendarHashChain(IVerificationContext context, ulong publicationTime) { CalendarHashChain hashChain = context.GetExtendedCalendarHashChain(publicationTime); if (hashChain == null) { throw new KsiVerificationException("Received invalid extended calendar hash chain from context extension function: null."); } return(hashChain); }
public TestAssembler( [NotNull] IVerificationContext verificationContext, [NotNull] IQualityConditionObjectDatasetResolver datasetResolver, [NotNull] Func <ITest, QualityCondition> getQualityCondition, [CanBeNull] Predicate <VectorDataset> isRelevantVectorDataset) { _verificationContext = verificationContext; _datasetResolver = datasetResolver; _getQualityCondition = getQualityCondition; _isRelevantVectorDataset = isRelevantVectorDataset; }
/// <see cref="VerificationRule.Verify" /> public override VerificationResult Verify(IVerificationContext context) { IKsiSignature signature = GetSignature(context); ulong aggregationTime = signature.AggregationTime; PublicationRecordInPublicationFile publicationRecord = GetNearestPublicationRecord(GetPublicationsFile(context), aggregationTime); CalendarHashChain extendedCalendarHashChain = GetExtendedCalendarHashChain(context, publicationRecord.PublicationData.PublicationTime); return(extendedCalendarHashChain.InputHash != signature.GetLastAggregationHashChainRootHash() ? new VerificationResult(GetRuleName(), VerificationResultCode.Fail, VerificationError.Pub03) : new VerificationResult(GetRuleName(), VerificationResultCode.Ok)); }
protected override QualityErrorRepositoryBase CreateQualityErrorRepository( IVerificationContext verificationContext, Dictionary <QualityCondition, IList <ITest> > qualityConditionTests, IQualityConditionObjectDatasetResolver datasetResolver) { // TODO get rid of subclass; but allow injecting things like an AttributeWriter etc. // Or in the short term create a BackgroundServiceIssueRepo that is only used to read // (allowed) errors. return(_issueRepository = _backgroundVerificationInputs.CreateQualityErrorRepository( verificationContext, qualityConditionTests, datasetResolver)); }
public void Build(IVerificationContext context, IScriptDocumentGeneratorFactory docGenFactory) { var dataSchema = CompileSchema(context); if (dataSchema == null) { return; } dataSchema.Verify(context); if (context.Entries.Count != 0) { return; } context.Add(new VerificationMessage(Severity.Info, Properties.Resources.DataSchemaValidated)); foreach (var transformation in Transformations) { var targetSystem = dataSchema.TargetSystems[transformation.TargetSystemName]; if (targetSystem == null) { context.Add(new VerificationMessage(Severity.Error, string.Format(CultureInfo.CurrentCulture, Properties.Resources.TargetSystemNameInTransformationNotFound, transformation.TargetSystemName, transformation.Name))); continue; } context.Add(new VerificationMessage(Severity.Info, string.Format(CultureInfo.CurrentCulture, Properties.Resources.RunningTransformation, transformation.Name))); var transformationContext = new TransformationContext { DataSchema = dataSchema, Name = transformation.Name, TargetSystem = targetSystem, TransformationElement = transformation.Element, DocGenFactory = docGenFactory, VerificationContext = context }; transformation.Method.Transform(transformationContext); } }
//private static XmlSchemaSet GetSchema() //{ // Assembly assembly = Assembly.GetExecutingAssembly(); // using (var reader = new StreamReader(assembly.GetManifestResourceStream(schemaResourceName))) // { // XmlSchemaSet schemas = new XmlSchemaSet(); // schemas.Add(targetNamespace, XmlReader.Create(reader)); // } //} public void Verify(IVerificationContext context) { if (string.IsNullOrWhiteSpace(Name)) { context.Add(new VerificationMessage(Severity.Error, Properties.Resources.DataSchemaNameEmpty)); } foreach (var target in this.TargetSystems) { target.Verify(context); } foreach (var columnType in this.ColumnTypes) { columnType.Verify(context); } foreach (var table in this.Tables) { table.Verify(context); } }
private void ApplyParsedSchema(Parsing.DataSchema parsedSchema, IVerificationContext context) { const string PropertyMacroDefault = "(default)"; // Column types foreach (Parsing.DataSchemaColumnType parsedColumnType in parsedSchema.ColumnTypes) { ColumnType columnType = new ColumnType(); columnType.Name = parsedColumnType.name; columnType.Description = parsedColumnType.description; if (parsedColumnType.baseType != null) { ColumnType baseType = this.ColumnTypes[parsedColumnType.baseType]; if (baseType == null) { context.Add(new VerificationMessage(Verification.Severity.Error, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.ColumnTypeBaseTypeUnkown, parsedColumnType.name, parsedColumnType.baseType))); continue; } columnType.BaseType = baseType; Debug.Assert(columnType.BaseType != null); } // Set default values when no base type if (columnType.BaseType == null) { columnType.CanBeNull = false; columnType.IsDbGenerated = false; } if (parsedColumnType.canBeNullSpecified) { columnType.CanBeNull = parsedColumnType.canBeNull; } if (parsedColumnType.isDbGeneratedSpecified) { columnType.IsDbGenerated = parsedColumnType.isDbGenerated; } if (parsedColumnType.maxLengthSpecified) { columnType.MaxLength = parsedColumnType.maxLength; } if (parsedColumnType.enumType != null) { columnType.EnumTypeName = parsedColumnType.enumType; } if (parsedColumnType.precisionSpecified) { columnType.Precision = parsedColumnType.precision; } if (parsedColumnType.scaleSpecified) { columnType.Scale = parsedColumnType.scale; } if (parsedColumnType.Target != null) { foreach (var parsedTarget in parsedColumnType.Target) { TargetSystem targetSystem = this.TargetSystems[parsedTarget.name]; if (targetSystem == null) { targetSystem = new TargetSystem { Name = parsedTarget.name }; this.TargetSystems.Add(targetSystem); } Target target = new Target { TargetSystem = targetSystem, DataType = parsedTarget.dataType, DataTypeWhenReferenced = parsedTarget.dataTypeWhenReferenced, DotNetType = parsedTarget.dotNetType, DotNetTypeNullable = parsedTarget.dotNetTypeNullable }; if (parsedTarget.ExtendedProperties != null && parsedTarget.ExtendedProperties.Length > 0) { target.ExtendedProperties.Clear(); foreach (var property in parsedTarget.ExtendedProperties) { target.ExtendedProperties.Add(property.name, property.Value); } } try { columnType.Targets.Add(target); } catch (ArgumentException) { context.Add(new VerificationMessage(Severity.Error, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.ColumnTypeTargetDuplicates, target.TargetSystem.Name, columnType.Name))); } } } columnType.Verify(context); if (!this.ColumnTypes.Contains(columnType.Name)) { this.ColumnTypes.Add(columnType); } else { context.Add(new VerificationMessage(Severity.Error, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.ColumnTypeDuplicates, columnType.Name))); } } if (parsedSchema.Tables != null) { // Tables: First pass - references are skipped until second pass. foreach (var parsedTable in parsedSchema.Tables) { Table table = new Table(); table.Name = parsedTable.name; try { this.Tables.Add(table); } catch (ArgumentException) { context.Add(new VerificationTableMessage(Severity.Error, table.Name, Properties.Resources.SchemaTableExists)); } table.Description = parsedTable.description; // Columns foreach (var parsedColumn in parsedTable.Columns) { Column column = new Column(); column.Name = parsedColumn.name; column.Description = parsedColumn.description; if (parsedColumn.canBeNullSpecified) { column.CanBeNull = parsedColumn.canBeNull; } if (parsedColumn.inPrimaryKeySpecified) { column.InPrimaryKey = parsedColumn.inPrimaryKey; } if (!string.IsNullOrWhiteSpace(parsedColumn.columnType)) { ColumnType columnType = this.ColumnTypes[parsedColumn.columnType]; if (columnType != null) { column.ColumnType = columnType; } else { context.Add(new VerificationTableMessage(Severity.Error, table.Name, column.Name, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.ColumnTypeUnknown, parsedColumn.columnType))); } } table.Columns.Add(column); } // Indices if (parsedTable.Indices != null) { foreach (var parsedIndex in parsedTable.Indices) { Index index = new Index(table); if (!string.IsNullOrWhiteSpace(parsedIndex.name)) { index.Name = parsedIndex.name; } if (parsedIndex.uniqueSpecified) { index.IsUnique = parsedIndex.unique; } foreach (var parsedIndexColumn in parsedIndex.Column) { Column column = table.Columns[parsedIndexColumn.name]; if (column != null) { index.Columns.Add(column); } else { context.Add(new VerificationTableMessage(Severity.Error, table.Name, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.IndexColumnUnknown, parsedIndexColumn.name))); } } table.Indices.Add(index); } } } // Tables: Second pass - resolve references foreach (var parsedTable in parsedSchema.Tables) { Table table = this.Tables[parsedTable.name]; foreach (var parsedColumn in parsedTable.Columns) { if (!string.IsNullOrWhiteSpace(parsedColumn.references)) { Column column = table.Columns[parsedColumn.name]; string toTableName; string toColumnName; SplitReference(parsedColumn.references, out toTableName, out toColumnName); Table toTable = this.Tables[toTableName]; if (toTable == null) { context.Add(new VerificationTableMessage(Severity.Error, table.Name, column.Name, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.ReferencedTableNotExists, parsedColumn.references))); continue; } Column toColumn = toTable.Columns[toColumnName]; if (toColumn == null) { context.Add(new VerificationTableMessage(Severity.Error, table.Name, column.Name, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.ReferencedColumnNotExists, parsedColumn.references))); continue; } ForeignKey foreignKey = new ForeignKey(); foreignKey.FromTable = table; foreignKey.ToTable = toTable; foreignKey.Columns.Add(new ForeignKey.ColumnPair { FromColumn = column, ToColumn = toColumn }); if (!string.IsNullOrEmpty(parsedColumn.referenceName)) { foreignKey.Name = parsedColumn.referenceName; } table.ForeignKeys.Add(foreignKey); column.ColumnType = this.GetReferenceToColumnType(toColumn.ColumnType); column.CanBeNull = false; if (parsedColumn.canBeNullSpecified) column.CanBeNull = parsedColumn.canBeNull; // Association properties foreignKey.AssociationProperty = new AssociationProperty(); if (parsedColumn.AssociationCode != null) { if (parsedColumn.AssociationCode.Child != null) { ParsedAssociationEndPointToNative(parsedColumn.AssociationCode.Child, foreignKey.AssociationProperty.Child); } else { foreignKey.AssociationProperty.Child = null; } ParsedAssociationEndPointToNative(parsedColumn.AssociationCode.Parent, foreignKey.AssociationProperty.Parent); } else { // Check the quick-attributes for association properties if (string.IsNullOrEmpty(parsedColumn.childProperty)) { foreignKey.AssociationProperty.Child = null; } else { if (string.Compare(parsedColumn.childProperty, PropertyMacroDefault, StringComparison.Ordinal) != 0) { foreignKey.AssociationProperty.Child.Name = parsedColumn.childProperty; } else { // Using default foreignKey.AssociationProperty.Child.Name = null; } } if (string.IsNullOrEmpty(parsedColumn.parentProperty)) { foreignKey.AssociationProperty.Parent = null; } else { if (string.Compare(parsedColumn.parentProperty, PropertyMacroDefault, StringComparison.Ordinal) != 0) { foreignKey.AssociationProperty.Parent.Name = parsedColumn.parentProperty; } else { // Using default foreignKey.AssociationProperty.Parent.Name = null; } } } } } // end foreach (var parsedColumn in parsedTable.Columns) // Foreign keys if (parsedTable.ForeignKeys != null) { foreach (var parsedForeignKey in parsedTable.ForeignKeys) { ForeignKey foreignKey = new ForeignKey(); foreignKey.Name = parsedForeignKey.name; foreignKey.FromTable = table; Table toTable = this.Tables[parsedForeignKey.toTable]; if (toTable == null) { context.Add(new VerificationTableMessage(Severity.Error, table.Name, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.ForeignKeyTableNotExists, parsedForeignKey.toTable))); continue; } foreignKey.ToTable = toTable; foreach (var columnPair in parsedForeignKey.ColumnPairs) { Column fromColumn = table.Columns[columnPair.from]; if (fromColumn == null) { context.Add(new VerificationTableMessage(Severity.Error, table.Name, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.ForeignKeyFromColumnNotExists, columnPair.from))); continue; } Column toColumn = toTable.Columns[columnPair.to]; if (toColumn == null) { context.Add(new VerificationTableMessage(Severity.Error, table.Name, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.ForeignKeyToColumnNotExists, columnPair.to))); continue; } foreignKey.Columns.Add(new ForeignKey.ColumnPair { FromColumn = fromColumn, ToColumn = toColumn }); } table.ForeignKeys.Add(foreignKey); } } // Table settings if (parsedTable.Settings != null) { foreach (var parsedSetting in parsedTable.Settings) { if (!this.TargetSystems.Contains(parsedSetting.target)) { context.Add(new VerificationTableMessage(Severity.Error, table.Name, string.Format(System.Globalization.CultureInfo.CurrentCulture, Properties.Resources.TableSettingsTargetNotExists, parsedSetting.target))); continue; } table.Settings.Add(parsedSetting.target, parsedSetting.property, parsedSetting.value); } } } } }
public void Verify(IVerificationContext context, string tableName) { if (string.IsNullOrWhiteSpace(Name)) { context.Add(new VerificationTableMessage(Severity.Error, tableName, Properties.Resources.ColumnNameEmpty)); } }
public DataSchema CompileSchema(IVerificationContext context) { if (context == null) { throw new ArgumentNullException("context"); } DataSchema dataSchema = new DataSchema(); dataSchema.Name = Name; foreach (var filePath in InputFiles) { var inputFilePath = Path.GetFullPath(filePath); if (!File.Exists(inputFilePath)) { context.Add(new VerificationMessage(Severity.Error, string.Format(CultureInfo.CurrentCulture, Properties.Resources.InputFileNotFound, inputFilePath))); return null; } using (StreamReader reader = new StreamReader(inputFilePath)) { dataSchema.LoadDataSchemaFile(reader, context); } } if (!string.IsNullOrEmpty(Options.PrimaryKeyFormatString)) { dataSchema.NameFormats.PrimaryKeyFormatString = Options.PrimaryKeyFormatString; } if (!string.IsNullOrEmpty(Options.ForeignKeyFormatString)) { dataSchema.NameFormats.ForeignKeyFormatString = Options.ForeignKeyFormatString; } if (!string.IsNullOrEmpty(Options.UniqueIndexFormatString)) { dataSchema.NameFormats.UniqueIndexFormatString = Options.UniqueIndexFormatString; } if (!string.IsNullOrEmpty(Options.IndexFormatString)) { dataSchema.NameFormats.IndexFormatString = Options.IndexFormatString; } return dataSchema; }
private bool VerifyString(IVerificationContext context, string s, string errorText) { bool result = !string.IsNullOrWhiteSpace(s); if (!result) { context.Add(new VerificationMessage(Severity.Error, errorText)); } return result; }
public void LoadFrom(string projectFilePath, IVerificationContext context, ISchemaTransformationFactory schemaTransformationFactory) { string baseDirectory = Path.GetDirectoryName(projectFilePath); using (StreamReader reader = new StreamReader(projectFilePath)) { var serializer = new XmlSerializer(typeof(Parsing.Project)); var parsedProject = (Parsing.Project)serializer.Deserialize(reader); foreach (var parsedInputFile in parsedProject.ProjectSettings.InputFiles) { if (VerifyString(context, parsedInputFile.path, "Project cannot have an input file with an empty path.")) { InputFiles.Add(ExpandFilePath(parsedInputFile.path, baseDirectory)); } } Options.PrimaryKeyFormatString = parsedProject.ProjectSettings.Options.PrimaryKeyFormatString; Options.ForeignKeyFormatString = parsedProject.ProjectSettings.Options.ForeignKeyFormatString; Options.UniqueIndexFormatString = parsedProject.ProjectSettings.Options.UniqueIndexFormatString; Options.IndexFormatString = parsedProject.ProjectSettings.Options.IndexFormatString; foreach (var parsedTransformation in parsedProject.Transformations) { VerifyString(context, parsedTransformation.name, "Transformation cannot have an empty name."); VerifyString(context, parsedTransformation.method, "Transformation cannot have an empty method."); VerifyString(context, parsedTransformation.target, "Transformation cannot have an empty method."); if (context.HasErrors) { continue; } var transformation = new Transformation(); transformation.Name = parsedTransformation.name; try { transformation.Method = schemaTransformationFactory.Create(parsedTransformation.method); } catch (ArgumentException ex) { context.Add(new VerificationMessage(Severity.Error, ex.Message)); continue; } transformation.TargetSystemName = parsedTransformation.target; transformation.Element = new XElement(XName.Get("Transformation", TargetNamespace), new XAttribute("name", parsedTransformation.name), new XAttribute("method", parsedTransformation.method), new XAttribute("target", parsedTransformation.target), parsedTransformation.Any.Select(e => XElement.Parse(e.OuterXml)) ); Transformations.Add(transformation); } } Name = Path.GetFileNameWithoutExtension(projectFilePath); }