/// <summary>
        /// Represents the metadata collection as a Dictionary{string,object}.
        /// </summary>
        /// <param name="version">Version of the schema to get elements from.</param>
        /// <returns>An instance of a <see cref="System.Collections.Generic.Dictionary{TKey,TValue}"/> containing
        /// all elements from the metadata collection.</returns>
        /// <remarks>
        /// <para>
        /// The method creates new instance of the <see cref="System.Collections.Generic.Dictionary{TKey,TValue}"/> and
        /// copies all elements from the specified version of the metadata collection into
        /// that instance. Therefore, modification of the dictionary will not affect the metadata
        /// collection and vice versa.
        /// </para>
        /// </remarks>
        /// <seealso cref="AsDictionary()"/>
        public Dictionary <string, object> AsDictionary(SchemaVersion version)
        {
            if (version == SchemaVersion.Committed)
            {
                return(Copy(dictionary));
            }

            if (version == SchemaVersion.Proposed && modified == null)
            {
                throw new Exception("There is no proposed version.");
            }

            if (modified != null)
            {
                Dictionary <string, object> copy = new Dictionary <string, object>(dictionary);
                CopyToDict1(copy, modified);
                return(copy);
            }

            if (version == SchemaVersion.Proposed)
            {
                throw new Exception("Key not found in the proposed version.");
            }

            Dictionary <string, object> dc = new Dictionary <string, object>(dictionary);

            return(dc);
        }
Exemple #2
0
        public void FromSchemaVersionToNull()
        {
            SchemaVersion value     = null;
            var           candidate = value.ToAsmVersion();

            Assert.IsNull(candidate, "Candidate not null");
        }
        public void OperatorOverload_LessThanOrEqual_WhenFirstLessThanSecond_ShouldReturnTrue()
        {
            var first  = new SchemaVersion("01", "01", "0123");
            var second = new SchemaVersion("01", "01", "0124");

            Assert.IsTrue(first <= second);
        }
        /// <summary>
        /// Gets the metadata value for the given key and schema version.
        /// </summary>
        /// <param name="key">The name of the metadata entry to get.</param>
        /// <param name="version">Version of the DataSet schema.</param>
        /// <returns>Value corresponding to the given key.</returns>
        /// <remarks>
        /// <para>
        /// Type of the key is always <see cref="string"/>.
        /// Type of the property value is <see cref="object"/>, but supported metadata value types
        /// are constrained. See documentation for <see cref="MetadataDictionary"/> for the
        /// specification.
        /// </para>
        /// <para>
        /// Gets the value of the metadata entry corresponding to the given <paramref name="key"/>.
        /// The value is taken from the specified version of the schema (see <see cref="SchemaVersion"/>).
        /// If the <paramref name="version"/> is SchemaVersion.Proposed and the collection has no changes,
        /// an exception is thrown.
        /// If the <paramref name="version"/> is SchemaVersion.Committed and the entry is just added
        /// to the collection and is not committed yet, an exception is thrown.
        /// </para>
        /// <para>
        /// If the given <paramref name="key"/> not found in the collection, an exception
        /// <see cref="KeyNotFoundException"/> is thrown.
        /// </para>
        /// <example>
        /// <code>
        /// dataSet.IsAutocommitEnabled = false;
        /// . . .
        /// Variable v = dataSet["var"];
        /// v.Metadata["custom"] = 10;
        /// dataSet.Commit();
        ///
        /// Console.WriteLine(v.Metadata["custom"]); // prints "10"
        ///
        /// v.Metadata["custom"] = 11;
        /// /* Now: v.HasChanges, v.Metadata.HasChanges and dataSet.HasChanges are true */
        ///
        /// Console.WriteLine(v.Metadata["custom"]); // prints committed value "10"
        /// Console.WriteLine(v.Metadata["custom", SchemaVersion.Proposed]); // prints "11"
        ///
        /// dataSet.Rollback();
        /// Console.WriteLine(v.Metadata["custom"]); // prints "10"
        /// // Console.WriteLine(v.Metadata["custom", SchemaVersion.Proposed]); // would throw an exception
        /// </code>
        /// </example>
        /// </remarks>
        /// <seealso cref="this[string]"/>
        /// <seealso cref="this[string,bool]"/>
        /// <seealso cref="this[string,SchemaVersion,bool]"/>
        /// <seealso cref="SchemaVersion"/>
        /// <seealso cref="Variable"/>
        public object this[string key, SchemaVersion version]
        {
            get
            {
                if (version == SchemaVersion.Committed)
                {
                    return(MakeReturnedValue(dictionary[key]));
                }

                if (version == SchemaVersion.Proposed && modified == null)
                {
                    throw new Exception("There is no proposed version.");
                }

                if (modified != null && modified.ContainsKey(key))
                {
                    return(MakeReturnedValue(modified[key]));
                }
                if (version == SchemaVersion.Proposed)
                {
                    throw new KeyNotFoundException("Key not found in proposed version.");
                }

                var value = dictionary[key];
                return(MakeReturnedValue(value));
            }
        }
        public void OperatorOverload_Equals_WhenFirstEqualToSecond_ShouldReturnTrue()
        {
            var first  = new SchemaVersion("01", "01", "0125");
            var second = new SchemaVersion("01", "01", "0125");

            Assert.IsTrue(first == second);
        }
        public void OperatorOverload_GreaterThan_WhenFirstGreaterThanSecond_ShouldReturnTrue()
        {
            var first = new SchemaVersion("01", "01", "0125");
            var second = new SchemaVersion("01", "01", "0124");

            Assert.IsTrue(first > second);
        }
        public void SchemaVersionSmallerThan()
        {
            SchemaVersion v1       = new SchemaVersion("00.00.00.0000");
            SchemaVersion v2       = new SchemaVersion("00.00.00.0001");
            bool          expected = true;
            bool          actual   = (v1 < v2);

            Assert.AreEqual(expected, actual);

            v1       = new SchemaVersion("00.00.00.0001");
            v2       = new SchemaVersion("00.00.00.0001");
            expected = true;
            actual   = (v1 <= v2);
            Assert.AreEqual(expected, actual);

            v1       = new SchemaVersion("00.00.00.0000");
            v2       = new SchemaVersion("00.00.00.0001");
            expected = true;
            actual   = (v1 <= v2);
            Assert.AreEqual(expected, actual);

            v1       = new SchemaVersion("02.00.00.0000");
            v2       = new SchemaVersion("01.99.99.9999");
            expected = false;
            actual   = (v1 < v2);
            Assert.AreEqual(expected, actual);
        }
Exemple #8
0
        public async Task GetSchemaVersionById()
        {
            // arrange
            var serializer = new IdSerializer();
            var schema     = new Schema(Guid.NewGuid(), "abc", "def");
            await SchemaRepository.AddSchemaAsync(schema);

            var schemaVersion = new SchemaVersion(
                Guid.NewGuid(), schema.Id, "abc", "def",
                Array.Empty <Tag>(), DateTime.UnixEpoch);
            await SchemaRepository.AddSchemaVersionAsync(schemaVersion);

            string id = serializer.Serialize("SchemaVersion", schemaVersion.Id);

            // act
            IExecutionResult result = await Executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQuery(
                    @"query($id: ID!) {
                            schemaVersionById(id: $id) {
                                id
                                sourceText
                            }
                        }")
                .SetVariableValue("id", id)
                .Create());

            // assert
            result.MatchSnapshot(o =>
                                 o.Assert(fo =>
                                          Assert.Equal(id, fo.Field <string>("Data.schemaVersionById.id"))));
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (Name.Length != 0)
            {
                hash ^= Name.GetHashCode();
            }
            if (SchemaVersion.Length != 0)
            {
                hash ^= SchemaVersion.GetHashCode();
            }
            if (Schema.Length != 0)
            {
                hash ^= Schema.GetHashCode();
            }
            if (SchemaType != global::Google.Cloud.AIPlatform.V1.MetadataSchema.Types.MetadataSchemaType.Unspecified)
            {
                hash ^= SchemaType.GetHashCode();
            }
            if (createTime_ != null)
            {
                hash ^= CreateTime.GetHashCode();
            }
            if (Description.Length != 0)
            {
                hash ^= Description.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
 public MessageSerializer(
     SchemaVersion version,
     IEnumerable <Meta <Lazy <IMessageDeserializer> > > deserializers)
 {
     this.version       = version;
     this.deserializers = deserializers;
 }
Exemple #11
0
        public static void SetSchemaVersion(string tenant, SchemaVersion schemaVersion)
        {
            var versions = GetVersions(tenant, schemaVersion.SchemaName).ToList();

            schemaVersion.LastInstalledOn = DateTimeOffset.UtcNow;

            if (!versions.Any())
            {
                versions = new List <SchemaVersion>
                {
                    schemaVersion
                };
            }
            else
            {
                var candidate = versions.FirstOrDefault(x => x.VersionNumber == schemaVersion.VersionNumber);

                if (candidate == null)
                {
                    versions.Add(schemaVersion);
                }
                else
                {
                    candidate.LastInstalledOn = DateTimeOffset.UtcNow;
                }
            }


            string versionFile = GetVersionFile(tenant, schemaVersion.SchemaName);
            string contents    = JsonConvert.SerializeObject(versions, Formatting.Indented);

            File.WriteAllText(versionFile, contents, new UTF8Encoding(false));
        }
Exemple #12
0
        public void WriteSchema(JSchema schema)
        {
            ValidationUtils.ArgumentNotNull(schema, nameof(schema));

            _rootSchema = schema;

            _knownSchemas.Clear();

            JSchemaDiscovery discovery;

            if (_externalSchemas != null)
            {
                foreach (ExternalSchema externalSchema in _externalSchemas)
                {
                    discovery = new JSchemaDiscovery(schema, _knownSchemas, KnownSchemaState.External);
                    discovery.Discover(externalSchema.Schema, externalSchema.Uri);
                }
            }

            if (_version == SchemaVersion.Unset)
            {
                _version = SchemaVersionHelpers.MapSchemaUri(schema.SchemaVersion);
            }

            discovery = new JSchemaDiscovery(schema, _knownSchemas, KnownSchemaState.InlinePending);
            discovery.Discover(schema, null);

            KnownSchema rootKnownSchema = _knownSchemas.Single(s => s.Schema == schema);

            rootKnownSchema.State = KnownSchemaState.Written;

            WriteSchemaInternal(schema);
        }
        private void LoadSchemaVersion()
        {
            var schemaChanges = GetTable(SchemaChangesTableName, SchemaChangesTableSchema);

            if (schemaChanges == null)
            {
                throw new ApplicationException("Schema changes table does not exist.");
            }
            if (schemaChanges.RowCount < 1)
            {
                throw new ApplicationException("No schema changes records");
            }

            var script =
                string.Format("SELECT TOP 1 Major, Minor, Point FROM {0}.{1} ORDER BY Major DESC, Minor DESC, Point DESC",
                              SchemaChangesTableSchema, SchemaChangesTableName);
            var set = _Database.ExecuteWithResults(script);

            var row = set.Tables[0].Rows[0];

            _Version = SchemaVersion.CreateVersion(
                row["Major"].ToString(),
                row["Minor"].ToString(),
                row["Point"].ToString());
        }
Exemple #14
0
 private static bool HasScriptBeenRunAlready(SqlConnection sqlConnection, SchemaVersion schemaVersion)
 {
     SqlCommand selectCmd = null;
     try
     {
         const string selectSql = @"SELECT COUNT(*) FROM dbo.[Schema] WHERE [MajorVersion] = {0} AND [MinorVersion] = {1} AND [ScriptVersion] = {2}";
         var stmt = string.Format(selectSql, schemaVersion.MajorVersion, schemaVersion.MinorVersion,
                                  schemaVersion.ScriptVersion);
         selectCmd = new SqlCommand(stmt, sqlConnection);
         var count = selectCmd.ExecuteScalar();
         var result = int.Parse(count.ToString());
         return result == 1;
     }
     catch
     {
         return false;
     }
     finally
     {
         if (selectCmd != null)
         {
             selectCmd.Dispose();
         }
     }
 }
Exemple #15
0
        private async static Task <Storage> InitNew()
        {
            var store         = new Storage();
            var initialSchema = SchemaVersion.Create();
            var result        = await store.UpgradeProcess(initialSchema);

            Function.Log("Applying initial store schema");

            var availableUpdates = DiscoverAvailableUpgrades(initialSchema).ToList();

            Function.Log("DiscoverAvailableUpgrades completed");
            Function.Log(String.Format("Store has {0} updates available", availableUpdates.Count));
            foreach (var update in availableUpdates)
            {
                Function.Log(String.Format("Upgrading to {0}", update.id));
                await store.UpgradeProcess(update);
            }

            if (result == UpgradeStatus.COMPLETED)
            {
                Function.Log("SQL is ready");
            }
            else if (result == UpgradeStatus.MISSING_SCHEMAS)
            {
                Function.Log("Missing schema");
            }
            else
            {
                Function.Log(String.Format("Schema upgrade failed as {0}", result));
            }
            Function.Log("InitStore completed version upgrade");


            return(store);
        }
 public void UpdateDatabase(SchemaVersion version)
 {
     Console.WriteLine(
         "This is not suggested to be used as the methods might be newer, make sure you have the correct methods version checked out when not updating to the latest schema version.");
     DirectoryManager.GetUpdateScripts(GetVersion()).Where(v => v.Version <= version).ToList().ForEach(
         s => s.ApplyUpdate(this));
 }
Exemple #17
0
 public AggregateSnapshotAccessor(SchemaVersion version, ElasticSearchConfig config)
 {
     this.version       = version;
     this.config        = config;
     this.elasticClient = this.CreateElasticClient();
     this.CheckIndexExists();
 }
        private static string GetTextCore(Keyword keyword, SchemaVersion draft = 0)
        {
            if (draft == 0)
            {
                // We default to Draft7,
                // since later drafts introduces/replaces a number of keywords
                // and might not readable by earlier versions
                // but earlier drafts may be readable by later drafts
                draft = SchemaVersion.Draft7;
            }

            switch (keyword)
            {
            case Keyword.DependentSchemas:
            case Keyword.DependentRequired:
                if (draft < SchemaVersion.Draft201909)
                {
                    return("dependencies");
                }
                break;
            }

            keyword2Name.TryGetValue(keyword, out string result);
            return(result);
        }
        public async Task AddPublishReport()
        {
            // arrange
            IMongoCollection <Schema> schemas =
                _mongoResource.CreateCollection <Schema>();
            IMongoCollection <SchemaVersion> versions =
                _mongoResource.CreateCollection <SchemaVersion>();
            IMongoCollection <SchemaPublishReport> publishReports =
                _mongoResource.CreateCollection <SchemaPublishReport>();

            var initial = new Schema("foo", "bar");
            await schemas.InsertOneAsync(initial, options : null, default);

            var initialVersion = new SchemaVersion(
                initial.Id, "foo", "bar", Array.Empty <Tag>(),
                DateTime.UtcNow);
            await versions.InsertOneAsync(initialVersion, options : null, default);

            var initialReport = new SchemaPublishReport(
                initialVersion.Id, Guid.NewGuid(), Array.Empty <Issue>(),
                PublishState.Published, DateTime.UtcNow);

            var repository = new SchemaRepository(schemas, versions, publishReports);

            // act
            await repository.AddPublishReportAsync(initialReport);

            // assert
            IReadOnlyDictionary <Guid, SchemaPublishReport> retrieved =
                await repository.GetPublishReportsAsync(new[] { initialReport.Id });

            Assert.True(retrieved.ContainsKey(initialReport.Id));
        }
        public void OperatorOverload_Equals_WhenFirstNotEqualToSecond_ShouldReturnFalse()
        {
            var first = new SchemaVersion("01", "01", "0125");
            var second = new SchemaVersion("01", "01", "0124");

            Assert.IsFalse(first == second);
        }
        public async Task GetPublishReportBySchemaVersionIdAndEnvironmentId()
        {
            // arrange
            IMongoCollection <Schema> schemas =
                _mongoResource.CreateCollection <Schema>();
            IMongoCollection <SchemaVersion> versions =
                _mongoResource.CreateCollection <SchemaVersion>();
            IMongoCollection <SchemaPublishReport> publishReports =
                _mongoResource.CreateCollection <SchemaPublishReport>();

            var initial = new Schema("foo", "bar");
            await schemas.InsertOneAsync(initial, options : null, default);

            var initialVersion = new SchemaVersion(
                initial.Id, "foo", "bar", Array.Empty <Tag>(),
                DateTime.UtcNow);
            await versions.InsertOneAsync(initialVersion, options : null, default);

            var initialReport = new SchemaPublishReport(
                initialVersion.Id, Guid.NewGuid(), Array.Empty <Issue>(),
                PublishState.Published, DateTime.UtcNow);
            await publishReports.InsertOneAsync(initialReport, options : null, default);

            var repository = new SchemaRepository(schemas, versions, publishReports);

            // act
            SchemaPublishReport retrieved = await repository.GetPublishReportAsync(
                initialReport.SchemaVersionId, initialReport.EnvironmentId);

            // assert
            Assert.Equal(initialReport.Id, retrieved.Id);
        }
        public void OperatorOverload_GreaterThanOrEqual_WhenFirstEqualToSecond_ShouldReturnTrue()
        {
            var first  = new SchemaVersion("01", "01", "0124");
            var second = new SchemaVersion("01", "01", "0124");

            Assert.IsTrue(first >= second);
        }
Exemple #23
0
        public static async Task <ValidationResult> Validate(string sbom, SchemaVersion schemaVersion)
        {
            var validationMessages = new List <string>();

            var schemaVersionString  = schemaVersion.ToString().Substring(1).Replace('_', '.');
            var expectedNamespaceURI = $"http://cyclonedx.org/schema/bom/{schemaVersionString}";

            var assembly = typeof(XmlBomValidator).GetTypeInfo().Assembly;

            using (var schemaStream = assembly.GetManifestResourceStream($"CycloneDX.Xml.Schemas.bom-{schemaVersionString}.xsd"))
                using (var spdxStream = assembly.GetManifestResourceStream("CycloneDX.Xml.Schemas.spdx.xsd"))
                    using (var stream = new MemoryStream())
                        using (var writer = new StreamWriter(stream))
                        {
                            var settings = new XmlReaderSettings();

                            settings.Schemas.Add(XmlSchema.Read(schemaStream, null));
                            settings.Schemas.Add(XmlSchema.Read(spdxStream, null));
                            settings.ValidationType = ValidationType.Schema;

                            await writer.WriteAsync(sbom);

                            await writer.FlushAsync();

                            stream.Position = 0;

                            using (var reader = XmlReader.Create(stream, settings))
                            {
                                var document = new XmlDocument();

                                try
                                {
                                    document.Load(reader);

                                    if (document.DocumentElement.NamespaceURI != expectedNamespaceURI)
                                    {
                                        validationMessages.Add($"Invalid namespace URI: expected {expectedNamespaceURI} actual {document.DocumentElement.NamespaceURI}");
                                    }
                                }
                                catch (XmlSchemaValidationException exc)
                                {
                                    var lineInfo = ((IXmlLineInfo)reader);
                                    if (lineInfo.HasLineInfo())
                                    {
                                        validationMessages.Add($"Validation failed at line number {lineInfo.LineNumber} and position {lineInfo.LinePosition}: {exc.Message}");
                                    }
                                    else
                                    {
                                        validationMessages.Add($"Validation failed at position {stream.Position}: {exc.Message}");
                                    }
                                }
                            }
                        }

            return(new ValidationResult
            {
                Valid = validationMessages.Count == 0,
                Messages = validationMessages
            });
        }
Exemple #24
0
        private static bool HasScriptBeenRunAlready(SqlConnection sqlConnection, SchemaVersion schemaVersion)
        {
            SqlCommand selectCmd = null;

            try
            {
                const string selectSql = @"SELECT COUNT(*) FROM dbo.[Schema] WHERE [MajorVersion] = {0} AND [MinorVersion] = {1} AND [ScriptVersion] = {2}";
                var          stmt      = string.Format(selectSql, schemaVersion.MajorVersion, schemaVersion.MinorVersion,
                                                       schemaVersion.ScriptVersion);
                selectCmd = new SqlCommand(stmt, sqlConnection);
                var count  = selectCmd.ExecuteScalar();
                var result = int.Parse(count.ToString());
                return(result == 1);
            }
            catch
            {
                return(false);
            }
            finally
            {
                if (selectCmd != null)
                {
                    selectCmd.Dispose();
                }
            }
        }
 private async Task <SchemaVersion> UpdateSchemaVersionAsync(
     SchemaVersion schemaVersion,
     IReadOnlyList <TagInput> tags,
     ISchemaRepository repository,
     CancellationToken cancellationToken)
 {
     if (tags is { })
        /// <summary>
        /// Determines whether the metadata contains the committed entry with the given <paramref name="key"/>.
        /// </summary>
        /// <param name="key">The case sensitive to locate in the collection.</param>
        /// <param name="version">Version of the schema to locate the key in.</param>
        /// <param name="ignoreCase">The value indicating whether the method should ignore the case of the key or not.</param>
        /// <returns><value>true</value> if the collection contains an entry with the given key; otherwise, <value>false</value>.</returns>
        /// <remarks>
        /// <example>
        /// <code>
        /// dataSet.IsAutocommitEnabled = false;
        /// . . .
        ///
        /// Variable v = dataSet["var"];
        /// v.Metadata["custom"] = 10;
        ///
        /// Console.WriteLine(v.Metadata.ContainsKey("custom", SchemaVersion.Proposed)); // prints "True"
        /// dataSet.Commit();
        ///
        /// //Console.WriteLine(v.Metadata.ContainsKey("custom", SchemaVersion.Proposed)); // throws an exception
        /// Console.WriteLine(v.Metadata.ContainsKey("custom")); // prints "True"
        /// Console.WriteLine(v.Metadata.ContainsKey("Custom")); // prints "False"
        /// Console.WriteLine(v.Metadata.ContainsKey("Custom", false)); // prints "True"
        /// </code>
        /// </example>
        /// </remarks>
        /// <seealso cref="ContainsKey(string)"/>
        /// <seealso cref="ContainsKey(string,bool)"/>
        /// <seealso cref="ContainsKey(string,SchemaVersion)"/>
        public bool ContainsKey(string key, SchemaVersion version, bool ignoreCase)
        {
            if (!ignoreCase)
            {
                return(ContainsKey(key, version));
            }

            if (version == SchemaVersion.Committed)
            {
                return(DictContainsKey(dictionary, key));
            }

            if (version == SchemaVersion.Proposed && modified == null)
            {
                return(false);
            }

            if (modified != null && DictContainsKey(modified, key))
            {
                return(true);
            }
            if (version == SchemaVersion.Proposed)
            {
                return(false);
            }

            return(DictContainsKey(dictionary, key));
        }
Exemple #27
0
        public async Task GetSchemaVersionsById_Invalid_Id_Type()
        {
            // arrange
            var serializer = new IdSerializer();
            var schema     = new Schema(Guid.NewGuid(), "abc", "def");
            await SchemaRepository.AddSchemaAsync(schema);

            var schemaVersion = new SchemaVersion(
                Guid.NewGuid(), schema.Id, "abc", "def",
                Array.Empty <Tag>(), DateTime.UnixEpoch);
            await SchemaRepository.AddSchemaVersionAsync(schemaVersion);

            string id = serializer.Serialize("Foo", schemaVersion.Id);

            // act
            IExecutionResult result = await Executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQuery(
                    @"query($ids: [ID!]!) {
                            schemaVersionsById(ids: $ids) {
                                id
                                sourceText
                            }
                        }")
                .SetVariableValue("ids", new[] { id })
                .Create());

            // assert
            result.MatchSnapshot();
        }
        /// <summary>
        /// Creates a shallow copy of the metadata collection.
        /// </summary>
        /// <param name="version">The version of the schema to clone.</param>
        /// <param name="readOnly">The value that determines that the resulting
        /// collection is read only or not.</param>
        /// <returns>MetadataDictionary instance containing the metadata copy.</returns>
        /// <remarks>
        /// <para>
        /// If the <paramref name="version"/> is SchemaVersion.Proposed or SchemaVersion.Recent and
        ///  the collection is modified, resulting collection contains both committed elements and
        ///  proposed and is unchanged.
        /// </para>
        /// <para>
        /// If the <paramref name="version"/> is SchemaVersion.Proposed and the collection has no changes,
        /// an exception is thrown.
        /// </para>
        /// </remarks>
        /// <seealso cref="AsReadOnly()"/>
        public MetadataDictionary Clone(SchemaVersion version, bool readOnly)
        {
            if (version == SchemaVersion.Committed)
            {
                return(new MetadataDictionary(readOnly, Copy(dictionary)));
            }

            if (version == SchemaVersion.Proposed && modified == null)
            {
                throw new Exception("There is no proposed version.");
            }

            if (modified != null)
            {
                Dictionary <string, object> copy = new Dictionary <string, object>(dictionary);
                CopyToDict1(copy, modified);
                return(new MetadataDictionary(readOnly, copy));
            }

            if (version == SchemaVersion.Proposed)
            {
                throw new Exception("Key not found in the proposed version.");
            }

            Dictionary <string, object> dc = new Dictionary <string, object>(dictionary);

            return(new MetadataDictionary(readOnly, dc));
        }
        private SchemaVersion mapSchemaVersion(JsonSchemaVersion version)
        {
            SchemaVersion mappedVersion = SchemaVersion.None;

            if (version == JsonSchemaVersion.All)
            {
                mappedVersion = SchemaVersion.All;
            }
            if (version == JsonSchemaVersion.Draft04)
            {
                mappedVersion = SchemaVersion.Draft04;
            }
            if (version == JsonSchemaVersion.Draft06)
            {
                mappedVersion = SchemaVersion.Draft06;
            }
            if (version == JsonSchemaVersion.Draft07)
            {
                mappedVersion = SchemaVersion.Draft07;
            }
            if (version == JsonSchemaVersion.Draft2019_09)
            {
                mappedVersion = SchemaVersion.Draft08;
            }
            return(mappedVersion);
        }
        public void CreateVersion_ValidNumbers_ParsesCorrectly()
        {
            var version = SchemaVersion.CreateVersion("001.002.003.sql");

            Expect(version.Major, Is.EqualTo(1));
            Expect(version.Minor, Is.EqualTo(2));
            Expect(version.Point, Is.EqualTo(3));
        }
Exemple #31
0
        public static async Task <int> Validate(Options options)
        {
            ValidateInputFormat(options);
            if (options.InputFormat == InputFormat.autodetect)
            {
                Console.Error.WriteLine("Unable to auto-detect input format");
                return((int)ExitCode.ParameterValidationError);
            }

            var inputBom = ReadInput(options);

            if (inputBom == null)
            {
                Console.Error.WriteLine("Error reading input, you must specify a value for --input-file or pipe in content");
                return((int)ExitCode.IOError);
            }

            SchemaVersion schemaVersion = SchemaVersion.v1_2;

            switch (options.InputFormat)
            {
            case InputFormat.xml_v1_1:
                schemaVersion = SchemaVersion.v1_1;
                break;

            case InputFormat.xml_v1_0:
                schemaVersion = SchemaVersion.v1_0;
                break;
            }

            ValidationResult validationResult;

            if (options.InputFormat.ToString().StartsWith("json", StringComparison.InvariantCulture))
            {
                Console.WriteLine("Validating JSON SBOM...");
                validationResult = await Json.Validator.Validate(inputBom, schemaVersion);
            }
            else
            {
                Console.WriteLine("Validating XML SBOM...");
                validationResult = await Json.Validator.Validate(inputBom, schemaVersion);
            }

            if (validationResult.Messages != null)
            {
                foreach (var message in validationResult.Messages)
                {
                    Console.WriteLine(message);
                }
            }

            if (options.FailOnErrors && !validationResult.Valid)
            {
                return((int)ExitCode.OkFail);
            }

            return((int)ExitCode.Ok);
        }
Exemple #32
0
        public async Task GivenInvalidVersion_WhenGettingValue_ThenThrowException(SchemaVersion version)
        {
            using CancellationTokenSource source = new CancellationTokenSource();

            _schemaVersionResolver.GetCurrentVersionAsync(source.Token).Returns(version);
            await Assert.ThrowsAsync <InvalidSchemaVersionException>(() => _versionedCache.GetAsync(source.Token));

            await _schemaVersionResolver.Received(1).GetCurrentVersionAsync(source.Token);
        }
Exemple #33
0
        } // syncCustomerInfo()

        protected override void afterPopulateProps()
        {
            SchemaVersion.SetOnBeforeRender( delegate( CswNbtNodeProp Prop )
                {
                    syncCustomerInfo();
                } );

            CompanyID.SetOnPropChange( OnCompanyIdPropChange );
        }//afterPopulateProps()
Exemple #34
0
 private static void InsertRecord(SqlConnection sqlConnection, SchemaVersion schemaVersion)
 {
     const string insertSql = @"INSERT INTO dbo.[Schema] VALUES('{0}',{1},{2},{3},'{4}')";
     var stmt = string.Format(insertSql, Path.GetFileName(schemaVersion.ScriptPath), schemaVersion.MajorVersion,
                              schemaVersion.MinorVersion, schemaVersion.ScriptVersion, DateTime.Now);
     using (var insertCmd = new SqlCommand(stmt, sqlConnection))
     {
         insertCmd.ExecuteNonQuery();
     }
 }
 public ServiceDefinition()
 {
     this.upgradeDomainCountField = 5;
     this.schemaVersionField = SchemaVersion.unspecified;
     this.topologyChangeDiscoveryField = TopologyChangeDiscovery.UpgradeDomainWalk;
 }
Exemple #36
0
        private SchemaVersion ApplySchemaChangesToDatabase(SchemaVersion currentVersion, ScriptInformation scriptInfo)
        {
            //Query the ScriptInfo Collection & Pull the Script Location for the Schema Directory...
            var schemaScriptLocation = scriptInfo.ScriptLocations.FirstOrDefault(fd => fd.ContainsSchemaScripts);
            //If there is one.
            //Pass that Off for processing.
            if (schemaScriptLocation != null)
            {
                //Ensure the scripts are ordered alphanumerically ascending
                foreach (var scriptFile in schemaScriptLocation.ScriptFiles.OrderBy(s => s))
                {
                    var fileSchemaVersion = scriptFile.ToSchemaVersion();

                    if (fileSchemaVersion > currentVersion)
                    {
                        var scriptNameToBeLogged = scriptFile.Replace(schemaScriptLocation.AbsolutePath, string.Empty);

                        //If the file's schema version is greater than the currentVersion,
                        TraceHelper.Info("Applying Schema Change '{0}'", scriptNameToBeLogged);

                        var scripts = IOManager.ReadSqlScripts(scriptFile);

                        SqlManager.ExecuteSchemaFile(scripts, scriptNameToBeLogged, fileSchemaVersion);

                        //Set that to be our new Current Version.
                        currentVersion = fileSchemaVersion;
                    }
                    else
                    {
                        TraceHelper.Verbose("Skipping '{0}' - Current Version is '{1}'", scriptFile, currentVersion);
                    }
                }
            }

            //Return the new "Current" Schema Version
            return currentVersion;
        }
Exemple #37
0
        private void ApplyScriptsToDatabase(SchemaVersion currentVersion, ScriptInformation scriptInfo)
        {
            foreach (var location in scriptInfo.ScriptLocations.Where(sl => !sl.ContainsSchemaScripts))
            {
                TraceHelper.Info("Applying Change Scripts In '{0}'", location.Path);
                TraceHelper.Info("\tRunOnce: '{0}'", location.RunOnce);
                TraceHelper.Info("\tRecursive: '{0}'", location.Recursive);

                ApplyScriptsToDatabaseRecursiveDirectoryWalk(currentVersion, location, location.AbsolutePath);
            }
        }
Exemple #38
0
        private void ApplyScriptsToDatabaseRecursiveDirectoryWalk(SchemaVersion currentVersion, ScriptLocation location, string currentDirectoryPath)
        {
            foreach (var scriptFile in location.ScriptFiles.OrderBy(s => s))
            {
                var scriptNameToBeLogged = scriptFile.Replace(location.AbsolutePath, string.Empty);

                if (!location.RunOnce) //Can be run many times
                {
                    TraceHelper.Info("Applying Script '{0}'", scriptNameToBeLogged);

                    var scripts = IOManager.ReadSqlScripts(scriptFile);

                    var hash = IOManager.GetFileMD5Hash(scriptFile);

                    SqlManager.ExecuteScriptFile(scripts, scriptNameToBeLogged, hash, currentVersion);
                }
                else
                {
                    TraceHelper.Info("Applying Script '{0}'", scriptNameToBeLogged);

                    var scripts = IOManager.ReadSqlScripts(scriptFile);

                    var hash = IOManager.GetFileMD5Hash(scriptFile);

                    SqlManager.ExecuteScriptFile(scripts, scriptNameToBeLogged, hash, currentVersion);
                }
            }

            //foreach file in the location
            // is directory marked as "runOnce"
            //if yes
            //check if file applied before in a previous version.
            //if no
            // Apply that file & log it
            //if yes
            //skip it
            //if not
            //run that file regardless

            /*
            if (!location.Recursive) return;
            //foreach directory in the location
            foreach(var subDirectoryPath in Directory.GetDirectories(currentDirectoryPath))
            {
                // Recursively repeat.
                ApplyScriptsToDatabaseRecursiveDirectoryWalk(currentVersion, location, subDirectoryPath);
            }
             */
        }
 public ServiceDefinition()
 {
     this.upgradeDomainCountField = 5;
     this.schemaVersionField = SchemaVersion.unspecified;
 }
Exemple #40
0
        /// <summary>
        /// Executes the schema file.
        /// Executes a number of sql blocks as scripts and subsequently logs the Schema File in the SchemaChangeLog
        /// All blocks are executed as a single transaction.
        /// </summary>
        /// <param name="sqlScripts">The SQL scripts.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="version">The version.</param>
        public void ExecuteSchemaFile(IEnumerable<string> sqlScripts, string fileName, SchemaVersion version)
        {
            var success = _parachuteCommand.Execute(sqlScripts);

            if (!success) return;

            using (var dc = new ParachuteContext(_connectionString))
            {
                var entry = new ParachuteSchemaChangeLog
                    {
                        MajorReleaseNumber = version.MajorVersion,
                        MinorReleaseNumber = version.MinorVersion,
                        PointReleaseNumber = version.PointRelease,
                        ScriptName = fileName
                    };

                dc.ParachuteSchemaChangeLogs.Add(entry);

                try
                {

                    dc.SaveChanges();
                }
                catch (InvalidOperationException invalidOperationEx)
                {
                    TraceHelper.Error(invalidOperationEx.Message);
                    throw;
                }
                catch (Exception ex)
                {
                    TraceHelper.Error(ex.Message);
                    throw;
                }
            }
        }
        public void OperatorOverload_LessThanOrEqual_WhenFirstLessThanSecond_ShouldReturnTrue()
        {
            var first = new SchemaVersion("01", "01", "0123");
            var second = new SchemaVersion("01", "01", "0124");

            Assert.IsTrue(first <= second);
        }
Exemple #42
0
        /// <summary>
        /// Executes the script file.
        /// </summary>
        /// <param name="sqlScripts">The SQL scripts.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="hash">The hash.</param>
        /// <param name="version">The version.</param>
        public void ExecuteScriptFile(IEnumerable<string> sqlScripts, string fileName, string hash, SchemaVersion version)
        {
            var success = _parachuteCommand.Execute(sqlScripts);
            if (!success) return;

            using (var dc = new ParachuteContext(_connectionString))
            {
                var entry = new ParachuteAppliedScriptsLog
                {
                    SchemaVersion = version.ToString(),
                    ScriptName = fileName,
                    DateApplied = DateTime.Now,
                    Hash = hash
                };

                dc.ParachuteAppliedScriptsLogs.Add(entry);
                try
                {
                    dc.SaveChanges();
                }
                catch (InvalidOperationException invalidOperationEx)
                {

                    TraceHelper.Error(invalidOperationEx.Message);
                    throw;
                }
                catch (Exception ex)
                {
                    TraceHelper.Error(ex.Message);
                    throw;
                }
            }
        }
 public void Constructor_PassingInvalidMinorRevision_ShouldInstantiateObject()
 {
     var sv = new SchemaVersion("01", "0XX", "0123");
 }
 public void Constructor_PassingInvalidPointReleaseNumber_ShouldInstantiateObject()
 {
     var sv = new SchemaVersion("01", "01", "01X3");
 }
 public void Constructor_PassingValidData_ShouldInstantiateObject()
 {
     var sv = new SchemaVersion("01", "01", "0123");
     Assert.AreEqual(typeof(SchemaVersion), sv.GetType());
 }
 public ServiceConfiguration()
 {
     this.schemaVersionField = SchemaVersion.unspecified;
 }
Exemple #47
0
 private static void SetFailure(SchemaVersion sqlFile, Exception e)
 {
     sqlFile.RunStatus = false;
     sqlFile.ErrorMessage = e.Message;
     sqlFile.FullErrorMessage = e.ToString();
 }
Exemple #48
0
 private static void SetSuccess(SchemaVersion sqlFile)
 {
     sqlFile.RunStatus = true;
     sqlFile.ErrorMessage = string.Empty;
     sqlFile.FullErrorMessage = string.Empty;
 }