Ejemplo n.º 1
0
        private void SQLServerComboBox_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (this.SQLServerComboBox.SelectedItem != null && this.SQLServerComboBox.SelectedItem is string)
            {
                this.SQLDatabaseComboBox.Enabled      = false;
                this.SQLDatabaseComboBox.SelectedItem = null;
                this.SQLDatabaseComboBox.Text         = "";
                this.SQLDatabaseComboBox.Items.Clear();
                Application.DoEvents();
                Cursor.Current = Cursors.WaitCursor;

                string serverName = this.SQLServerComboBox.SelectedItem as string;

                foreach (string databaseName in SqlServerLocator.FindDatabases(serverName))
                {
                    this.SQLDatabaseComboBox.Items.Add(databaseName);
                }

                if (this.SQLDatabaseComboBox.Items.Count > 0)
                {
                    this.SQLDatabaseComboBox.SelectedItem = this.SQLDatabaseComboBox.Items[0];
                }

                this.SQLDatabaseComboBox.Enabled = true;
                Cursor.Current = Cursors.Default;
            }
        }
        public IdentifiedSerializerRepresentation GetIdAddIfNecessarySerializerRepresentation(
            SqlServerLocator resourceLocator,
            SerializerRepresentation serializerRepresentation = null,
            SerializationFormat serializationFormat           = SerializationFormat.String)
        {
            var localSerializerRepresentation = serializerRepresentation ?? this.DefaultSerializerRepresentation;

            var found = this.serializerRepresentationToIdentifiedSerializerMap.TryGetValue(serializerRepresentation, out var result);

            if (found)
            {
                return(result);
            }
            else
            {
                var id = this.Execute(
                    new GetOrAddIdentifiedSerializerRepresentationOp(resourceLocator, localSerializerRepresentation, serializationFormat));
                var item = new IdentifiedSerializerRepresentation(id, localSerializerRepresentation, serializationFormat);
                this.serializerRepresentationIdToIdentifiedSerializerMap.TryAdd(item.Id, item);
                this.serializerRepresentationToIdentifiedSerializerMap.TryAdd(item.SerializerRepresentation, item);
                var newFound = this.serializerRepresentationToIdentifiedSerializerMap.TryGetValue(serializerRepresentation, out var newResult);
                newFound.MustForOp("failedToFindSerializationRepresentationAfterAdding").BeTrue();
                return(newResult);
            }
        }
Ejemplo n.º 3
0
        private static SqlServerLocator GetSqlServerLocator()
        {
            //var sqlServerLocator = new SqlServerLocator("localhost", "Streams", Invariant($"[{streamName}-read-only]"), "ReadMe", "SQLDEV2017");
            var sqlServerLocator = new SqlServerLocator("localhost", "Streams", "sa", "<password>", "SQLDEV2017");

            return(sqlServerLocator);
        }
Ejemplo n.º 4
0
 private void cbServerName_DropDown(object sender, EventArgs e)
 {
     if (cbServerName.Items.Count == 0)
     {
         cbServerName.DataSource = SqlServerLocator.GetServers();
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Gets the type by identifier.
        /// </summary>
        /// <param name="locator">The locator.</param>
        /// <param name="typeWithVersionId">The type with version identifier.</param>
        /// <param name="versioned">if set to <c>true</c> [versioned].</param>
        /// <returns>TypeRepresentationWithAndWithoutVersion.</returns>
        public TypeRepresentationWithAndWithoutVersion GetTypeById(
            SqlServerLocator locator,
            int typeWithVersionId,
            bool versioned)
        {
            versioned.MustForArg(nameof(versioned)).BeTrue("Can't allow until I can confirm the that a null versioned type rep doesn't matter.");
            var found = this.assemblyQualifiedNameWithVersionIdToIdentifiedTypeMap.TryGetValue(typeWithVersionId, out var result);

            if (found)
            {
                return(result);
            }
            else
            {
                var storedProcOp = StreamSchema.Sprocs.GetTypeFromId.BuildExecuteStoredProcedureOp(
                    this.Name,
                    typeWithVersionId,
                    versioned);

                var sqlProtocol           = this.BuildSqlOperationsProtocol(locator);
                var sprocResult           = sqlProtocol.Execute(storedProcOp);
                var assemblyQualifiedName = sprocResult
                                            .OutputParameters[nameof(StreamSchema.Sprocs.GetTypeFromId.OutputParamName.AssemblyQualifiedName)]
                                            .GetValueOfType <string>();
                var typeRep = assemblyQualifiedName.ToTypeRepresentationFromAssemblyQualifiedName();
                var item    = typeRep.ToWithAndWithoutVersion();
                this.assemblyQualifiedNameWithVersionIdToIdentifiedTypeMap.TryAdd(typeWithVersionId, item);

                var newFound = this.assemblyQualifiedNameWithVersionIdToIdentifiedTypeMap.TryGetValue(typeWithVersionId, out var newResult);
                newFound.MustForOp("failedToFindSerializationRepresentationAfterAdding").BeTrue();
                return(newResult);
            }
        }
Ejemplo n.º 6
0
 private void cbDbName_DropDown(object sender, EventArgs e)
 {
     if (cbDbName.Items.Count == 0 && !(string.IsNullOrEmpty(cbServerName.Text.Trim()) || string.IsNullOrEmpty(tbUserName.Text.Trim()) || string.IsNullOrEmpty(tbPassword.Text.Trim())))
     {
         cbDbName.DataSource = SqlServerLocator.GetDatabases(cbServerName.Text, rbSQLServer.Checked, tbUserName.Text, tbPassword.Text);
     }
 }
Ejemplo n.º 7
0
        private void SQLServerComboBox_DropDown(object sender, System.EventArgs e)
        {
            if (this.refreshServerListOnDropDown)
            {
                this.Cursor = Cursors.WaitCursor;
                Application.DoEvents();

                ArrayList servers = SqlServerLocator.FindServers();
                SQLServerComboBox.Items.Clear();

                foreach (string server in servers)
                {
                    if (server.ToLower() == "(local)")
                    {
                        SQLServerComboBox.Items.Add(Environment.MachineName.ToUpper());
                    }
                    else
                    {
                        SQLServerComboBox.Items.Add(server);
                    }
                }

                this.Cursor = Cursors.Default;
                this.refreshServerListOnDropDown = false;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Builds the SQL operations protocol.
        /// </summary>
        /// <param name="sqlLocator">The SQL locator.</param>
        /// <returns>IProtocolSqlOperations.</returns>
        public IProtocolSqlOperations BuildSqlOperationsProtocol(
            SqlServerLocator sqlLocator)
        {
            var result = new SqlOperationsProtocol(sqlLocator, this.DefaultConnectionTimeout, this.DefaultCommandTimeout);

            return(result);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets the tags by identifiers.
        /// </summary>
        /// <param name="locator">The locator.</param>
        /// <param name="tagIds">The tag identifiers.</param>
        /// <returns>IReadOnlyDictionary&lt;System.String, System.String&gt;.</returns>
        public IReadOnlyCollection <NamedValue <string> > GetTagsByIds(SqlServerLocator locator, IReadOnlyCollection <long> tagIds)
        {
            if (tagIds == null)
            {
                return(null);
            }

            if (!tagIds.Any())
            {
                return(new List <NamedValue <string> >());
            }

            var result    = new List <NamedValue <string> >();
            var remaining = new List <long>();

            foreach (var id in tagIds)
            {
                var found = this.tagIdToKeyValueMap.TryGetValue(id, out var keyValuePair);
                if (found)
                {
                    result.Add(new NamedValue <string>(keyValuePair.Name, keyValuePair.Value));
                }
                else
                {
                    remaining.Add(id);
                }
            }

            if (remaining.Any())
            {
                var sqlProtocol = this.BuildSqlOperationsProtocol(locator);

                var storedProcWithVersionOp = StreamSchema.Sprocs.GetTagSetFromIds.BuildExecuteStoredProcedureOp(
                    this.Name,
                    remaining.ToList());
                var sprocResultWithVersion = sqlProtocol.Execute(storedProcWithVersionOp);
                var tagsXml    = sprocResultWithVersion.OutputParameters[nameof(StreamSchema.Sprocs.GetTagSetFromIds.OutputParamName.TagsXml)].GetValueOfType <string>();
                var additional = TagConversionTool.GetTagsFromXmlString(tagsXml).ToList() ?? new List <NamedValue <string> >();

                additional.Count.MustForOp(Invariant($"{nameof(additional)}-comparedTo-{nameof(remaining)}-Counts")).BeEqualTo(remaining.Count);

                // this is the sort order of sproc return.
                var remainingSortedOnId = remaining.OrderBy(_ => _).ToList();
                for (int idx = 0;
                     idx < remaining.Count;
                     idx++)
                {
                    this.tagKeyValueToIdMap.TryAdd(additional[idx], remainingSortedOnId[idx]);
                    this.tagIdToKeyValueMap.TryAdd(remainingSortedOnId[idx], additional[idx]);
                    result.Add(new NamedValue <string>(additional[idx].Name, additional[idx].Value));
                }
            }

            return(result);
        }
Ejemplo n.º 10
0
 private void btnTest_Click(object sender, EventArgs e)
 {
     if (SqlServerLocator.TestConnection(cbServerName.Text, cbDbName.Text, rbSQLServer.Checked, tbUserName.Text, tbPassword.Text))
     {
         MessageBox.Show("Connect Success!");
     }
     else
     {
         MessageBox.Show("Connect Fail!");
     }
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlOperationsProtocol"/> class.
        /// </summary>
        /// <param name="sqlServerLocator">The SQL locator.</param>
        /// <param name="defaultConnectionTimeout">The default connection timeout.</param>
        /// <param name="defaultCommandTimeout">The default command timeout.</param>
        public SqlOperationsProtocol(
            SqlServerLocator sqlServerLocator,
            TimeSpan defaultConnectionTimeout = default(TimeSpan),
            TimeSpan defaultCommandTimeout    = default(TimeSpan))
        {
            sqlServerLocator.MustForArg(nameof(sqlServerLocator)).NotBeNull();

            this.sqlServerLocator = sqlServerLocator;

            this.defaultConnectionTimeout = defaultConnectionTimeout == default(TimeSpan) ? TimeSpan.FromSeconds(30) : defaultConnectionTimeout;
            this.defaultCommandTimeout    = defaultCommandTimeout == default(TimeSpan) ? TimeSpan.FromSeconds(30) : defaultCommandTimeout;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets the ids add if necessary tag.
        /// </summary>
        /// <param name="locator">The locator.</param>
        /// <param name="tags">The tags.</param>
        /// <returns>IReadOnlyList&lt;System.Int64&gt;.</returns>
        public IReadOnlyList <long> GetIdsAddIfNecessaryTag(SqlServerLocator locator, IReadOnlyCollection <NamedValue <string> > tags)
        {
            if (tags == null)
            {
                return(null);
            }

            var sqlProtocol = this.BuildSqlOperationsProtocol(locator);
            var result      = new List <long>();
            var remaining   = new List <NamedValue <string> >();

            foreach (var keyValuePair in tags)
            {
                var found = this.tagKeyValueToIdMap.TryGetValue(keyValuePair, out var id);
                if (found)
                {
                    result.Add(id);
                }
                else
                {
                    remaining.Add(keyValuePair);
                }
            }

            if (remaining.Any())
            {
                var storedProcWithVersionOp = StreamSchema.Sprocs.GetIdsAddIfNecessaryTagSet.BuildExecuteStoredProcedureOp(
                    this.Name,
                    remaining);
                var sprocResultWithVersion = sqlProtocol.Execute(storedProcWithVersionOp);
                var tagIdsXml = sprocResultWithVersion
                                .OutputParameters[nameof(StreamSchema.Sprocs.GetIdsAddIfNecessaryTagSet.OutputParamName.TagIdsXml)]
                                .GetValueOfType <string>();
                var tagIds     = tagIdsXml.GetTagsFromXmlString();
                var additional = tagIds.Select(_ => long.Parse(_.Value, CultureInfo.InvariantCulture)).ToList();
                additional.Count.MustForOp(Invariant($"{nameof(additional)}-comparedTo-{nameof(remaining)}-Counts")).BeEqualTo(remaining.Count);

                // this is the sort order of the output of the sproc.
                var orderedRemaining = remaining.OrderBy(_ => _.Name).ThenBy(_ => _.Value ?? TagConversionTool.NullCanaryValue).ToList();
                for (int idx = 0;
                     idx < orderedRemaining.Count;
                     idx++)
                {
                    this.tagKeyValueToIdMap.TryAdd(orderedRemaining[idx], additional[idx]);
                    this.tagIdToKeyValueMap.TryAdd(additional[idx], orderedRemaining[idx]);
                }

                result.AddRange(additional);
            }

            return(result);
        }
        /// <summary>
        /// Gets the serializer representation from identifier (first by cache and then by database).
        /// </summary>
        /// <param name="sqlServerLocator">The resource locator.</param>
        /// <param name="serializerRepresentationId">The serializer representation identifier.</param>
        /// <returns>IdentifiedSerializerRepresentation.</returns>
        public IdentifiedSerializerRepresentation GetSerializerRepresentationFromId(
            SqlServerLocator sqlServerLocator,
            int serializerRepresentationId)
        {
            var found = this.serializerRepresentationIdToIdentifiedSerializerMap.TryGetValue(serializerRepresentationId, out var result);

            if (found)
            {
                return(result);
            }
            else
            {
                var storedProcOp = StreamSchema.Sprocs.GetSerializerRepresentationFromId.BuildExecuteStoredProcedureOp(
                    this.Name,
                    serializerRepresentationId);

                var sqlProtocol = this.BuildSqlOperationsProtocol(sqlServerLocator);
                var sprocResult = sqlProtocol.Execute(storedProcOp);

                SerializationKind serializationKind = sprocResult
                                                      .OutputParameters[nameof(StreamSchema
                                                                               .Sprocs.GetSerializerRepresentationFromId.OutputParamName
                                                                               .SerializationKind)]
                                                      .GetValueOfType <SerializationKind>();
                int configTypeWithVersionId = sprocResult
                                              .OutputParameters[nameof(StreamSchema
                                                                       .Sprocs.GetSerializerRepresentationFromId.OutputParamName
                                                                       .ConfigTypeWithVersionId)]
                                              .GetValueOfType <int>();
                CompressionKind compressionKind = sprocResult
                                                  .OutputParameters[nameof(StreamSchema
                                                                           .Sprocs.GetSerializerRepresentationFromId.OutputParamName
                                                                           .CompressionKind)]
                                                  .GetValueOfType <CompressionKind>();
                SerializationFormat serializationFormat = sprocResult
                                                          .OutputParameters[nameof(StreamSchema
                                                                                   .Sprocs.GetSerializerRepresentationFromId.OutputParamName
                                                                                   .SerializationFormat)]
                                                          .GetValueOfType <SerializationFormat>();

                var configType = this.GetTypeById(sqlServerLocator, configTypeWithVersionId, true);

                var rep  = new SerializerRepresentation(serializationKind, configType.WithVersion, compressionKind);
                var item = new IdentifiedSerializerRepresentation(serializerRepresentationId, rep, serializationFormat);

                this.serializerRepresentationIdToIdentifiedSerializerMap.TryAdd(item.Id, item);
                this.serializerRepresentationToIdentifiedSerializerMap.TryAdd(item.SerializerRepresentation, item);
                var newFound = this.serializerRepresentationIdToIdentifiedSerializerMap.TryGetValue(serializerRepresentationId, out var newResult);
                newFound.MustForOp("failedToFindSerializationRepresentationAfterAdding").BeTrue();
                return(newResult);
            }
        }
Ejemplo n.º 14
0
        public void Retrieve___Should_do_something___When_called()
        {
            var sqlServerLocator = new SqlServerLocator("localhost", "Streams", "sa", "password", "SQLDEV2017");
            var connectionString = sqlServerLocator.BuildConnectionString(TimeSpan.FromSeconds(100));
            var output           = SqlServerDatabaseManager.Retrieve(connectionString);

            output.MustForTest().NotBeNull();

            var jsonSerializer = new ObcJsonSerializer();
            var json           = jsonSerializer.SerializeToString(output);

            this.testOutputHelper.WriteLine(json);
        }
Ejemplo n.º 15
0
        public FormCreateSQLFeatureDatabase()
        {
            InitializeComponent();

            cmbType.SelectedIndex = 0;
            SqlServerLocator locator = new SqlServerLocator();

            string[] servers = locator.GetServers();
            if (servers != null)
            {
                foreach (string server in servers)
                {
                    cmbServer.Items.Add(server);
                }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Gets the type of the ids add if necessary.
        /// </summary>
        /// <param name="locator">The locator.</param>
        /// <param name="typeRepresentation">The type representation.</param>
        /// <returns>IdentifiedType.</returns>
        public IdentifiedType GetIdsAddIfNecessaryType(SqlServerLocator locator, TypeRepresentationWithAndWithoutVersion typeRepresentation)
        {
            if (typeRepresentation == null)
            {
                return(null);
            }

            var assemblyQualifiedNameWithVersion = typeRepresentation.WithVersion.BuildAssemblyQualifiedName();
            var found = this.assemblyQualifiedNameWithVersionToIdentifiedTypeMap.TryGetValue(assemblyQualifiedNameWithVersion, out var result);

            if (found)
            {
                return(result);
            }
            else
            {
                var assemblyQualifiedNameWithoutVersion = typeRepresentation.WithoutVersion.BuildAssemblyQualifiedName();

                var sqlProtocol = this.BuildSqlOperationsProtocol(locator);
                var storedProcWithoutVersionOp = StreamSchema.Sprocs.GetIdAddIfNecessaryTypeWithoutVersion.BuildExecuteStoredProcedureOp(
                    this.Name,
                    assemblyQualifiedNameWithoutVersion);

                var sprocResultWithoutVersion = sqlProtocol.Execute(storedProcWithoutVersionOp);
                var withoutVersionId          = sprocResultWithoutVersion
                                                .OutputParameters[nameof(StreamSchema.Sprocs.GetIdAddIfNecessaryTypeWithoutVersion.OutputParamName.Id)]
                                                .GetValueOfType <int>();
                var storedProcWithVersionOp = StreamSchema.Sprocs.GetIdAddIfNecessaryTypeWithVersion.BuildExecuteStoredProcedureOp(
                    this.Name,
                    assemblyQualifiedNameWithVersion);
                var sprocResultWithVersion = sqlProtocol.Execute(storedProcWithVersionOp);
                var withVersionId          = sprocResultWithVersion
                                             .OutputParameters[nameof(StreamSchema.Sprocs.GetIdAddIfNecessaryTypeWithVersion.OutputParamName.Id)]
                                             .GetValueOfType <int>();

                var item = new IdentifiedType(withoutVersionId, withVersionId);
                this.assemblyQualifiedNameWithVersionToIdentifiedTypeMap.TryAdd(assemblyQualifiedNameWithVersion, item);
                var newFound = this.assemblyQualifiedNameWithVersionToIdentifiedTypeMap.TryGetValue(assemblyQualifiedNameWithVersion, out var newResult);
                newFound.MustForOp("failedToFindSerializationRepresentationAfterAdding").BeTrue();
                return(newResult);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SqlStream"/> class.
        /// </summary>
        /// <param name="name">The name of the stream.</param>
        /// <param name="defaultConnectionTimeout">The default connection timeout.</param>
        /// <param name="defaultCommandTimeout">The default command timeout.</param>
        /// <param name="defaultSerializerRepresentation">Default serializer description to use.</param>
        /// <param name="defaultSerializationFormat">Default serializer format.</param>
        /// <param name="serializerFactory">The factory to get a serializer to use for objects.</param>
        /// <param name="resourceLocatorProtocol">The protocols for getting locators.</param>
        public SqlStream(
            string name,
            TimeSpan defaultConnectionTimeout,
            TimeSpan defaultCommandTimeout,
            SerializerRepresentation defaultSerializerRepresentation,
            SerializationFormat defaultSerializationFormat,
            ISerializerFactory serializerFactory,
            IResourceLocatorProtocols resourceLocatorProtocol)
            : base(name, serializerFactory, defaultSerializerRepresentation, defaultSerializationFormat, resourceLocatorProtocol)
        {
            name.MustForArg(nameof(name)).NotBeNullNorWhiteSpace();
            defaultSerializerRepresentation.MustForArg(nameof(defaultSerializerRepresentation)).NotBeNull();
            serializerFactory.MustForArg(nameof(serializerFactory)).NotBeNull();
            resourceLocatorProtocol.MustForArg(nameof(resourceLocatorProtocol)).NotBeNull();

            this.StreamRepresentation     = new StreamRepresentation(this.Name);
            this.DefaultConnectionTimeout = defaultConnectionTimeout;
            this.DefaultCommandTimeout    = defaultCommandTimeout;

            var allLocators = this.ResourceLocatorProtocols.Execute(new GetAllResourceLocatorsOp());

            this.singleLocator = allLocators.Count == 1 ? allLocators.Single().ConfirmAndConvert <SqlServerLocator>() : null;
        }
Ejemplo n.º 18
0
        public void CreateStreamExampleDatabaseAndScripts()
        {
            var sqlServerLocator = new SqlServerLocator("localhost", "StreamExample3", "sa", "<password>", "SQLDEV2017");
            var configuration    = SqlServerDatabaseDefinition.BuildDatabaseConfigurationUsingDefaultsAsNecessary(sqlServerLocator.DatabaseName, @"D:\SQL\");
            var createDatabaseOp = new CreateDatabaseOp(configuration, ExistingDatabaseStrategy.Throw);
            var protocol         = new SqlOperationsProtocol(sqlServerLocator);

            protocol.Execute(createDatabaseOp);

            var resourceLocatorProtocol = new SingleResourceLocatorProtocols(sqlServerLocator);

            var configurationTypeRepresentation = typeof(NullJsonSerializationConfiguration).ToRepresentation();

            SerializerRepresentation defaultSerializerRepresentation = new SerializerRepresentation(
                SerializationKind.Json,
                configurationTypeRepresentation);

            var defaultSerializationFormat = SerializationFormat.String;
            var stream = new SqlStream(
                "Example",
                TimeSpan.FromMinutes(1),
                TimeSpan.FromMinutes(3),
                defaultSerializerRepresentation,
                defaultSerializationFormat,
                new JsonSerializerFactory(),
                resourceLocatorProtocol);

            stream.Execute(new StandardCreateStreamOp(stream.StreamRepresentation, ExistingStreamStrategy.Skip));

            this.testOutputHelper.WriteLine("Created database.");

            /*
             * var path = "D:/Temp/Example";
             * var connectionString = sqlServerLocator.BuildConnectionString(TimeSpan.FromSeconds(20));
             * Scripter.ScriptDatabaseToFilePath(connectionString, path, this.testOutputHelper.WriteLine, false);
             */
        }
Ejemplo n.º 19
0
 private void btnRefresh_Click(object sender, EventArgs e)
 {
     cbServerName.DataSource = SqlServerLocator.GetServers();
 }
Ejemplo n.º 20
0
        public override CreateStreamResult Execute(
            StandardCreateStreamOp operation)
        {
            operation.MustForArg(nameof(operation)).NotBeNull();

            var allLocators    = this.ResourceLocatorProtocols.Execute(new GetAllResourceLocatorsOp());
            var alreadyExisted = false;
            var wasCreated     = true;

            foreach (var locator in allLocators)
            {
                if (locator is SqlServerLocator sqlLocator)
                {
                    using (var connection = sqlLocator.OpenSqlConnection(this.DefaultConnectionTimeout))
                    {
                        var streamAlreadyExists = connection.HasAtLeastOneRowWhenReading(
                            Invariant($"select * from sys.schemas where name = '{this.Name}'"));

                        alreadyExisted = alreadyExisted || streamAlreadyExists;
                        if (streamAlreadyExists)
                        {
                            switch (operation.ExistingStreamStrategy)
                            {
                            case ExistingStreamStrategy.Overwrite:
                                throw new NotSupportedException(FormattableString.Invariant(
                                                                    $"Overwriting streams is not currently supported; stream '{this.Name}' already exists, {nameof(operation)}.{nameof(operation.ExistingStreamStrategy)} was set to {ExistingStreamStrategy.Overwrite}."));

                            case ExistingStreamStrategy.Throw:
                                throw new InvalidOperationException(FormattableString.Invariant($"Stream '{this.Name}' already exists, {nameof(operation)}.{nameof(operation.ExistingStreamStrategy)} was set to {ExistingStreamStrategy.Throw}."));

                            case ExistingStreamStrategy.Skip:
                                wasCreated = false;
                                break;
                            }
                        }
                        else
                        {
                            var creationScripts = new[]
                            {
                                StreamSchema.BuildCreationScriptForSchema(this.Name),
                                StreamSchema.Tables.NextUniqueLong.BuildCreationScript(this.Name),
                                StreamSchema.Tables.TypeWithoutVersion.BuildCreationScript(this.Name),
                                StreamSchema.Tables.TypeWithVersion.BuildCreationScript(this.Name),
                                StreamSchema.Tables.SerializerRepresentation.BuildCreationScript(this.Name),
                                StreamSchema.Tables.Tag.BuildCreationScript(this.Name),
                                StreamSchema.Tables.Record.BuildCreationScript(this.Name),
                                StreamSchema.Tables.RecordTag.BuildCreationScript(this.Name),
                                StreamSchema.Tables.Handling.BuildCreationScript(this.Name),
                                StreamSchema.Tables.HandlingTag.BuildCreationScript(this.Name),
                                StreamSchema.Funcs.GetTagsTableVariableFromTagsXml.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.CreateStreamUser.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetDistinctStringSerializedIds.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetHandlingStatuses.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetIdAddIfNecessarySerializerRepresentation.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetIdsAddIfNecessaryTagSet.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetIdAddIfNecessaryTypeWithoutVersion.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetIdAddIfNecessaryTypeWithVersion.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetInternalRecordIds.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetLatestRecord.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetLatestStringSerializedObject.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetNextUniqueLong.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetSerializerRepresentationFromId.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetStreamDetails.BuildCreationScript(this.Name, RecordTagAssociationManagementStrategy.AssociatedDuringPutInSprocInTransaction, null),
                                StreamSchema.Sprocs.GetTagSetFromIds.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.GetTypeFromId.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.PutRecord.BuildCreationScript(this.Name, RecordTagAssociationManagementStrategy.AssociatedDuringPutInSprocInTransaction),
                                StreamSchema.Sprocs.PutHandling.BuildCreationScript(this.Name),
                                StreamSchema.Sprocs.TryHandleRecord.BuildCreationScript(this.Name, null),
                                StreamSchema.BuildCreationScriptForRoles(this.Name),                       // must be at end to reference the items.
                            };

                            foreach (var script in creationScripts)
                            {
                                connection.ExecuteNonQuery(script);
                            }
                        }
                    }
                }
                else
                {
                    throw SqlServerLocator.BuildInvalidLocatorException(locator.GetType());
                }
            }

            var createResult = new CreateStreamResult(alreadyExisted, wasCreated);

            return(createResult);
        }
        static SqlServerLocatorTest()
        {
            StringRepresentationTestScenarios
            .RemoveAllScenarios()
            .AddScenario(() =>
                         new StringRepresentationTestScenario <SqlServerLocator>
            {
                Name = "Override ToString scenario",
                SystemUnderTestExpectedStringRepresentationFunc = () =>
                {
                    var systemUnderTest = A.Dummy <SqlServerLocator>();

                    var result = new SystemUnderTestExpectedStringRepresentation <SqlServerLocator>
                    {
                        SystemUnderTest = systemUnderTest,
                        ExpectedStringRepresentation = Invariant($"Naos.SqlServer.Domain.SqlServerLocator: ServerName = {systemUnderTest.ServerName?.ToString(CultureInfo.InvariantCulture) ?? "<null>"}, DatabaseName = {systemUnderTest.DatabaseName?.ToString(CultureInfo.InvariantCulture) ?? "<null>"}, UserName = {systemUnderTest.UserName?.ToString(CultureInfo.InvariantCulture) ?? "<null>"}, Password = ***, InstanceName = {systemUnderTest.InstanceName?.ToString(CultureInfo.InvariantCulture) ?? "<null>"}, Port = {systemUnderTest.Port?.ToString(CultureInfo.InvariantCulture) ?? "<null>"}."),
                    };

                    return(result);
                },
            });

            ConstructorArgumentValidationTestScenarios
            .RemoveAllScenarios()
            .AddScenario(
                () =>
                new ConstructorArgumentValidationTestScenario <SqlServerLocator>
            {
                Name             = "constructor should throw ArgumentNullException when parameter 'serverName' is null scenario",
                ConstructionFunc = () =>
                {
                    var referenceObject = A.Dummy <SqlServerLocator>();

                    var result = new SqlServerLocator(
                        null,
                        referenceObject.DatabaseName,
                        referenceObject.UserName,
                        referenceObject.Password,
                        referenceObject.InstanceName,
                        referenceObject.Port);

                    return(result);
                },
                ExpectedExceptionType            = typeof(ArgumentNullException),
                ExpectedExceptionMessageContains = new[]
                {
                    "serverName",
                },
            })
            .AddScenario(
                () =>
                new ConstructorArgumentValidationTestScenario <SqlServerLocator>
            {
                Name             = "constructor should throw ArgumentException when parameter 'serverName' is white space scenario",
                ConstructionFunc = () =>
                {
                    var referenceObject = A.Dummy <SqlServerLocator>();

                    var result = new SqlServerLocator(
                        Invariant($"  {Environment.NewLine}  "),
                        referenceObject.DatabaseName,
                        referenceObject.UserName,
                        referenceObject.Password,
                        referenceObject.InstanceName,
                        referenceObject.Port);

                    return(result);
                },
                ExpectedExceptionType            = typeof(ArgumentException),
                ExpectedExceptionMessageContains = new[]
                {
                    "serverName",
                    "white space",
                },
            })
            .AddScenario(
                () =>
                new ConstructorArgumentValidationTestScenario <SqlServerLocator>
            {
                Name             = "constructor should throw ArgumentNullException when parameter 'databaseName' is null scenario",
                ConstructionFunc = () =>
                {
                    var referenceObject = A.Dummy <SqlServerLocator>();

                    var result = new SqlServerLocator(
                        referenceObject.ServerName,
                        null,
                        referenceObject.UserName,
                        referenceObject.Password,
                        referenceObject.InstanceName,
                        referenceObject.Port);

                    return(result);
                },
                ExpectedExceptionType            = typeof(ArgumentNullException),
                ExpectedExceptionMessageContains = new[]
                {
                    "databaseName",
                },
            })
            .AddScenario(
                () =>
                new ConstructorArgumentValidationTestScenario <SqlServerLocator>
            {
                Name             = "constructor should throw ArgumentException when parameter 'databaseName' is white space scenario",
                ConstructionFunc = () =>
                {
                    var referenceObject = A.Dummy <SqlServerLocator>();

                    var result = new SqlServerLocator(
                        referenceObject.ServerName,
                        Invariant($"  {Environment.NewLine}  "),
                        referenceObject.UserName,
                        referenceObject.Password,
                        referenceObject.InstanceName,
                        referenceObject.Port);

                    return(result);
                },
                ExpectedExceptionType            = typeof(ArgumentException),
                ExpectedExceptionMessageContains = new[]
                {
                    "databaseName",
                    "white space",
                },
            });
        }
        private RecordFilterConvertedForStoredProcedure ConvertRecordFilter(
            RecordFilter recordFilter,
            SqlServerLocator sqlServerLocator)
        {
            recordFilter.TagMatchStrategy
            .MustForArg(Invariant($"{nameof(recordFilter)}.{nameof(recordFilter.TagMatchStrategy)}"))
            .BeEqualTo(TagMatchStrategy.RecordContainsAllQueryTags, "Currently only supported tag strategy.");

            var internalRecordIdsCsv = (recordFilter.InternalRecordIds ?? new List <long>())
                                       .Select(_ => _.ToStringInvariantPreferred())
                                       .ToCsv();

            var tagIdsCsv = this.GetIdsAddIfNecessaryTag(
                sqlServerLocator,
                recordFilter.Tags ?? new List <NamedValue <string> >())
                            .Select(_ => _.ToStringInvariantPreferred())
                            .ToCsv();

            var distinctIdentifierTypes = (recordFilter.Ids ?? new List <StringSerializedIdentifier>())
                                          .Select(_ => _.IdentifierType)
                                          .Distinct()
                                          .ToList();

            var typeToIdMap = distinctIdentifierTypes.ToDictionary(
                k => k,
                v => this.GetIdsAddIfNecessaryType(sqlServerLocator, v.ToWithAndWithoutVersion()));

            var identifierTypes = (recordFilter.IdTypes ?? new List <TypeRepresentation>())
                                  .Select(_ => this.GetIdsAddIfNecessaryType(sqlServerLocator, _.ToWithAndWithoutVersion()))
                                  .ToList();
            var identifierTypeIdsCsv = identifierTypes
                                       .Select(
                _ =>
                recordFilter.VersionMatchStrategy == VersionMatchStrategy.Any
                                               ? _.IdWithoutVersion.ToStringInvariantPreferred()
                                               : _.IdWithVersion.ToStringInvariantPreferred())
                                       .ToCsv();

            var objectTypes = (recordFilter.ObjectTypes ?? new List <TypeRepresentation>())
                              .Select(_ => this.GetIdsAddIfNecessaryType(sqlServerLocator, _.ToWithAndWithoutVersion()))
                              .ToList();
            var objectTypeIdsCsv = objectTypes
                                   .Select(
                _ =>
                recordFilter.VersionMatchStrategy == VersionMatchStrategy.Any
                                               ? _.IdWithoutVersion.ToStringInvariantPreferred()
                                               : _.IdWithVersion.ToStringInvariantPreferred())
                                   .ToCsv();

            var deprecatedIdTypes = (recordFilter.DeprecatedIdTypes ?? new List <TypeRepresentation>())
                                    .Select(_ => this.GetIdsAddIfNecessaryType(sqlServerLocator, _.ToWithAndWithoutVersion()))
                                    .ToList();
            var deprecatedIdTypeIdsCsv = deprecatedIdTypes
                                         .Select(
                _ =>
                recordFilter.VersionMatchStrategy == VersionMatchStrategy.Any
                                               ? _.IdWithoutVersion.ToStringInvariantPreferred()
                                               : _.IdWithVersion.ToStringInvariantPreferred())
                                         .ToCsv();

            var stringIdsToMatchXml =
                (recordFilter.Ids ?? new List <StringSerializedIdentifier>())
                .Select(
                    _ => new NamedValue <int>(
                        _.StringSerializedId,
                        recordFilter.VersionMatchStrategy == VersionMatchStrategy.Any
                            ? typeToIdMap[_.IdentifierType].IdWithoutVersion
                            : typeToIdMap[_.IdentifierType].IdWithVersion))
                .ToList()
                .GetTagsXmlString();

            var result = new RecordFilterConvertedForStoredProcedure(
                internalRecordIdsCsv,
                identifierTypeIdsCsv,
                objectTypeIdsCsv,
                stringIdsToMatchXml,
                tagIdsCsv,
                recordFilter.TagMatchStrategy,
                recordFilter.VersionMatchStrategy,
                deprecatedIdTypeIdsCsv);

            return(result);
        }
Ejemplo n.º 23
0
        public UpdateStreamStoredProceduresResult Execute(
            UpdateStreamStoredProceduresOp operation)
        {
            var allLocators   = this.ResourceLocatorProtocols.Execute(new GetAllResourceLocatorsOp());
            var priorVersions = new List <string>();

            foreach (var locator in allLocators)
            {
                if (locator is SqlServerLocator sqlLocator)
                {
                    using (var connection = sqlLocator.OpenSqlConnection(this.DefaultConnectionTimeout))
                    {
                        var streamAlreadyExists = connection.HasAtLeastOneRowWhenReading(
                            Invariant($"select * from sys.schemas where name = '{this.Name}'"));

                        if (!streamAlreadyExists)
                        {
                            throw new InvalidDataException(Invariant($"Stream '{this.Name}' did exist, this is unexpected and not possible to ALTER stored procedures as they are not present."));
                        }

                        var alterScripts = new[]
                        {
                            StreamSchema.Funcs.GetTagsTableVariableFromTagsXml.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.CreateStreamUser.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetDistinctStringSerializedIds.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetHandlingStatuses.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetIdAddIfNecessarySerializerRepresentation.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetIdsAddIfNecessaryTagSet.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetIdAddIfNecessaryTypeWithoutVersion.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetIdAddIfNecessaryTypeWithVersion.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetInternalRecordIds.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetLatestRecord.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetLatestStringSerializedObject.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetNextUniqueLong.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetSerializerRepresentationFromId.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetStreamDetails.BuildCreationScript(
                                this.Name,
                                RecordTagAssociationManagementStrategy.AssociatedDuringPutInSprocInTransaction,
                                null,
                                true),
                            StreamSchema.Sprocs.GetTagSetFromIds.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.GetTypeFromId.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.PutRecord.BuildCreationScript(
                                this.Name,
                                RecordTagAssociationManagementStrategy.AssociatedDuringPutInSprocInTransaction,
                                true),
                            StreamSchema.Sprocs.PutHandling.BuildCreationScript(this.Name, true),
                            StreamSchema.Sprocs.TryHandleRecord.BuildCreationScript(this.Name, null, true),
                        };

                        var detailsOperation = StreamSchema.Sprocs.GetStreamDetails.BuildExecuteStoredProcedureOp(this.Name);
                        var protocol         = this.BuildSqlOperationsProtocol(sqlLocator);
                        var sprocResult      = protocol.Execute(detailsOperation);
                        var detailsXml       = sprocResult.OutputParameters[StreamSchema.Sprocs.GetStreamDetails.OutputParamName.DetailsXml.ToString()].GetValueOfType <string>();
                        var detailsMap       = detailsXml.GetTagsFromXmlString();
                        var version          = detailsMap?.FirstOrDefault(_ => _.Name == StreamSchema.Sprocs.GetStreamDetails.VersionKey)?.Value;
                        priorVersions.Add(version);

                        foreach (var script in alterScripts)
                        {
                            connection.ExecuteNonQuery(script);
                        }
                    }
                }
                else
                {
                    throw SqlServerLocator.BuildInvalidLocatorException(locator.GetType());
                }
            }

            var distinctNonNullVersions = priorVersions.Distinct().Where(_ => _ != null).ToList();
            var priorVersion            = distinctNonNullVersions.Any() ? distinctNonNullVersions.ToCsv() : null;
            var updateResult            = new UpdateStreamStoredProceduresResult(priorVersion);

            return(updateResult);
        }