Exemplo n.º 1
0
        internal sealed override void BeforeInvokeController(ManagedConnection connection, ClaimsPrincipal?user)
        {
            Context = connection as ServerSideConnection;
            Debug.Assert(Context != null, "Возможно перепутаны серверный и клиентский тип контроллера.");

            User = user;
        }
Exemplo n.º 2
0
        public IDocumentSession OpenSession(DocumentTracking tracking     = DocumentTracking.IdentityOnly,
                                            IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
        {
            var connection = new ManagedConnection(_connectionFactory, CommandRunnerMode.Transactional, isolationLevel);

            return(openSession(tracking, connection));
        }
Exemplo n.º 3
0
 public ResponseMessage(ManagedConnection context, int id, IActionResult actionResult)
 {
     Id           = id;
     MethodResult = actionResult;
     Method       = null;
     Context      = context;
 }
Exemplo n.º 4
0
        public async Task log_execute_with_answer_failure_1_async()
        {
            var ex     = new DivideByZeroException();
            var logger = new RecordingLogger();

            using (var connection = new ManagedConnection(new ConnectionSource())
            {
                Logger = logger
            })
            {
                await Exception <DivideByZeroException> .ShouldBeThrownByAsync(async() =>
                {
                    await connection.ExecuteAsync <string>(async(c, tkn) =>
                    {
                        await Task.CompletedTask;
                        c.CommandText = "do something";
                        throw ex;
                    });
                });



                logger.LastCommand.CommandText.ShouldBe("do something");
                logger.LastException.ShouldBe(ex);
            }
        }
Exemplo n.º 5
0
 public ResponseMessage(ManagedConnection context, int id, ControllerMethodMeta method, object?actionResult)
 {
     Id           = id;
     Method       = method;
     MethodResult = actionResult;
     Context      = context;
 }
Exemplo n.º 6
0
        public async Task increments_the_request_count()
        {
            using (var connection = new ManagedConnection(new ConnectionSource()))
            {
                connection.RequestCount.ShouldBe(0);

                connection.Execute(cmd => { });
                connection.RequestCount.ShouldBe(1);

                connection.Execute(new NpgsqlCommand(), c => { });
                connection.RequestCount.ShouldBe(2);

                connection.Execute(c => "");
                connection.RequestCount.ShouldBe(3);

                connection.Execute(new NpgsqlCommand(), c => "");
                connection.RequestCount.ShouldBe(4);



                await connection.ExecuteAsync(async (c, t) => { });
                connection.RequestCount.ShouldBe(5);

                await connection.ExecuteAsync(new NpgsqlCommand(), async (c, t) => { });
                connection.RequestCount.ShouldBe(6);

                await connection.ExecuteAsync(async (c, t) => "");
                connection.RequestCount.ShouldBe(7);

                await connection.ExecuteAsync(new NpgsqlCommand(), async (c, t) => "");
                connection.RequestCount.ShouldBe(8);

            }
        }
Exemplo n.º 7
0
        public async Task log_execute_failure_2_async()
        {
            var ex     = new DivideByZeroException();
            var logger = new RecordingLogger();

            using (var connection = new ManagedConnection(new ConnectionSource())
            {
                Logger = logger
            })
            {
                var cmd = new NpgsqlCommand();

                await Exception <DivideByZeroException> .ShouldBeThrownByAsync(async() =>
                {
                    await connection.ExecuteAsync(cmd, async(c, tkn) =>
                    {
                        await Task.CompletedTask;
                        throw ex;
                    });
                });



                logger.LastCommand.ShouldBe(cmd);
                logger.LastException.ShouldBe(ex);
            }
        }
Exemplo n.º 8
0
        public void log_execute_with_answer_failure_1()
        {
            var ex     = new DivideByZeroException();
            var logger = new RecordingLogger();

            using (var connection = new ManagedConnection(new ConnectionSource())
            {
                Logger = logger
            })
            {
                Exception <DivideByZeroException> .ShouldBeThrownBy(() =>
                {
                    connection.Execute <string>(c =>
                    {
                        c.CommandText = "do something";
                        throw ex;
                    });
                });



                logger.LastCommand.CommandText.ShouldBe("do something");
                logger.LastException.ShouldBe(ex);
            }
        }
Exemplo n.º 9
0
        public void log_execute_with_answer_failure_2()
        {
            var ex     = new DivideByZeroException();
            var logger = new RecordingLogger();

            using (var connection = new ManagedConnection(new ConnectionSource())
            {
                Logger = logger
            })
            {
                var cmd = new NpgsqlCommand();

                Exception <DivideByZeroException> .ShouldBeThrownBy(() =>
                {
                    connection.Execute <string>(cmd, c =>
                    {
                        throw ex;
                    });
                });



                logger.LastCommand.ShouldBe(cmd);
                logger.LastException.ShouldBe(ex);
            }
        }
Exemplo n.º 10
0
        private void TryMigrate(ManagedConnection connection, bool tableNewlyCreated)
        {
            try
            {
                if (tableNewlyCreated && TableExists(connection, "AccessTokens"))
                {
                    connection.RunInTransaction(
                        db =>
                    {
                        var existingColumnNames = GetColumnNames(db, "AccessTokens");

                        AddColumn(db, "AccessTokens", "UserName", "TEXT", existingColumnNames);
                        AddColumn(db, "AccessTokens", "DateLastActivity", "DATETIME", existingColumnNames);
                        AddColumn(db, "AccessTokens", "AppVersion", "TEXT", existingColumnNames);
                    }, TransactionMode);

                    connection.RunQueries(new[]
                    {
                        "update accesstokens set DateLastActivity=DateCreated where DateLastActivity is null",
                        "update accesstokens set DeviceName='Unknown' where DeviceName is null",
                        "update accesstokens set AppName='Unknown' where AppName is null",
                        "update accesstokens set AppVersion='1' where AppVersion is null",
                        "INSERT INTO Tokens (AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, IsActive, DateCreated, DateLastActivity) SELECT AccessToken, DeviceId, AppName, AppVersion, DeviceName, UserId, UserName, IsActive, DateCreated, DateLastActivity FROM AccessTokens where deviceid not null and devicename not null and appname not null and isactive=1"
                    });
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error migrating authentication database");
            }
        }
Exemplo n.º 11
0
        private void CreateInternalConnection()
        {
            InitCache();

            _anonymousConnection  = new ManagedConnection(string.Empty, _sharedTokenBucketMiddleware, _sharedWebCache, _sharedRenderCache, TimeSpan.MaxValue);
            _privilegedConnection = new ManagedConnection(string.Empty, _sharedTokenBucketMiddleware, _sharedWebCache, _sharedRenderCache, TimeSpan.MaxValue);
        }
Exemplo n.º 12
0
        public IEnumerable<ProjectionUsage> InitializeEventStoreInDatabase(bool overwrite = false)
        {
            var js = SchemaBuilder.GetJavascript(_options, "mt_transforms");

            using (var connection = new ManagedConnection(_connectionFactory))
            {
                connection.Execute(cmd =>
                {
                    var table = modulesTable();
                    var sql = $"delete from {table} where name = :name;" +
                              $"insert into {table} (name, definition) values (:name, :definition)";

                    cmd.WithText(sql)
                        .With("name", "mt_transforms")
                        .With("definition", js)
                        .ExecuteNonQuery();
                });

                connection.Execute(cmd =>
                {
                    cmd.CallsSproc(qualifyName("mt_initialize_projections")).With("overwrite", overwrite).ExecuteNonQuery();
                });
            }

            return ProjectionUsages();
        }
Exemplo n.º 13
0
        public void CompletelyRemove(Type documentType)
        {
            var mapping = _schema.MappingFor(documentType);

            using (var connection = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
            {
                mapping.RemoveSchemaObjects(connection);
            }
        }
Exemplo n.º 14
0
 public void DeleteAllEventData()
 {
     using (var connection = new ManagedConnection(_factory, CommandRunnerMode.Transactional))
     {
         connection.Execute($"truncate table {_schema.Events.DatabaseSchemaName}.mt_events cascade;" +
                            $"truncate table {_schema.Events.DatabaseSchemaName}.mt_streams cascade");
         connection.Commit();
     }
 }
Exemplo n.º 15
0
        // ctor
        public RequestContext(ManagedConnection connection, int?id, ControllerMethodMeta method, object[] args, bool isJsonRpc)
        {
            Debug.Assert(method != null);

            Context          = connection;
            Id               = id;
            ControllerMethod = method;
            Args             = args;
            IsJsonRpc        = isJsonRpc;
        }
Exemplo n.º 16
0
        public void log_execute_success_1()
        {
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                connection.Execute(c => c.CommandText = "do something");

                logger.LastCommand.CommandText.ShouldBe("do something");
            }
        }
Exemplo n.º 17
0
        public void CompletelyRemove(Type documentType)
        {
            var mapping = _schema.MappingFor(documentType);

            using (var connection = new ManagedConnection(_factory, CommandRunnerMode.Transactional))
            {
                mapping.SchemaObjects.RemoveSchemaObjects(connection);
                connection.Commit();
            }
        }
Exemplo n.º 18
0
        // TODO -- Really need to add some QueryHandlers for all this stuff to eliminate the duplication
        public SchemaObjects FindSchemaObjects(DocumentMapping mapping)
        {
            using (var connection = new ManagedConnection(_factory))
            {
                return(connection.Execute(cmd =>
                {
                    cmd.CommandText = SchemaObjectsSQL;
                    cmd.AddParameter("schema", mapping.Table.Schema);
                    cmd.AddParameter("table_name", mapping.Table.Name);
                    cmd.AddParameter("function", mapping.UpsertFunction.Name);
                    cmd.AddParameter("qualified_name", mapping.Table.OwnerName);

                    var reader = cmd.ExecuteReader();

                    var columns = new List <TableColumn>();
                    while (reader.Read())
                    {
                        var column = new TableColumn(reader.GetString(0), reader.GetString(1));
                        columns.Add(column);
                    }

                    var pks = new List <string>();
                    reader.NextResult();
                    while (reader.Read())
                    {
                        pks.Add(reader.GetString(0));
                    }

                    reader.NextResult();
                    var upsertDefinition = reader.Read() ? reader.GetString(0) : null;

                    var indices = new List <ActualIndex>();
                    reader.NextResult();
                    while (reader.Read())
                    {
                        var index = new ActualIndex(mapping.Table, reader.GetString(3),
                                                    reader.GetString(4));

                        indices.Add(index);
                    }

                    var table = columns.Any() ? new TableDefinition(mapping.Table, pks.FirstOrDefault(), columns) : null;

                    reader.NextResult();
                    var drops = new List <string>();
                    while (reader.Read())
                    {
                        drops.Add(reader.GetString(0));
                    }

                    FunctionBody functionBody = upsertDefinition.IsEmpty() ? null : new FunctionBody(mapping.UpsertFunction, drops.ToArray(), upsertDefinition);
                    return new SchemaObjects(mapping.DocumentType, table, indices.ToArray(), functionBody);
                }));
            }
        }
Exemplo n.º 19
0
        private Marten.V4Internals.Sessions.QuerySession BuildQuerySession()
        {
            using var database =
                      new ManagedConnection(new ConnectionFactory(ConnectionSource.ConnectionString), new NulloRetryPolicy());

            var persistence = new PersistenceGraph(theStore.Options);
            var newSession  = new Marten.V4Internals.Sessions.QuerySession(theStore, database, new JsonNetSerializer(),
                                                                           Substitute.For <ITenant>(), persistence, theStore.Options);

            return(newSession);
        }
Exemplo n.º 20
0
        private IDocumentSession openSession(DocumentTracking tracking, ManagedConnection connection)
        {
            var map     = createMap(tracking);
            var session = new DocumentSession(this, _options, Schema, _serializer, connection, _parser, map);

            connection.BeginSession();

            session.Logger = _logger.StartSession(session);

            return(session);
        }
Exemplo n.º 21
0
        public IEnumerable <ProjectionUsage> ProjectionUsages()
        {
            string json = null;

            using (var connection = new ManagedConnection(_connectionFactory))
            {
                json = connection.Execute(cmd => cmd.CallsSproc("mt_get_projection_usage").ExecuteScalar().As <string>());
            }

            return(_serializer.FromJson <ProjectionUsage[]>(json));
        }
Exemplo n.º 22
0
 public void DeleteAllDocuments()
 {
     using (var conn = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
     {
         _schema.DocumentTables().Each(tableName =>
         {
             var sql = "truncate {0} cascade".ToFormat(tableName);
             conn.Execute(sql);
         });
     }
 }
Exemplo n.º 23
0
 public void DeleteAllDocuments()
 {
     using (var conn = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
     {
         _schema.DocumentTables().Each(tableName =>
         {
             var sql = "truncate {0} cascade".ToFormat(tableName);
             conn.Execute(sql);
         });
     }
 }
Exemplo n.º 24
0
        public void CompletelyRemoveAll()
        {
            using (var connection = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
            {
                _schema.SchemaTableNames()
                    .Each(tableName => { connection.Execute($"DROP TABLE IF EXISTS {tableName} CASCADE;"); });

                var drops = connection.GetStringList(DropAllFunctionSql);
                drops.Each(drop => connection.Execute(drop));
            }
        }
Exemplo n.º 25
0
 internal SqlRdfBox(ManagedConnection connection, object box, bool is_complete, short rtype, short lang, long ro_id)
 {
     Debug.WriteLineIf(CLI.FnTrace.Enabled, "SqlRdfBox.ctor (connection, box, is_complete, rtype, lang, ro_id)");
     this.connection     = connection;
     this.rb_box         = box;
     this.rb_type        = rtype;
     this.rb_lang        = lang;
     this.rb_is_complete = is_complete;
     this.rb_ro_id       = ro_id;
     this.rb_is_outlined = false;
     this.rb_chksum_tail = false;
 }
Exemplo n.º 26
0
        public void CompletelyRemoveAll()
        {
            using (var connection = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
            {
                _schema.SchemaTableNames()
                .Each(tableName => { connection.Execute($"DROP TABLE IF EXISTS {tableName} CASCADE;"); });


                var drops = connection.GetStringList(DropAllFunctionSql);
                drops.Each(drop => connection.Execute(drop));
            }
        }
Exemplo n.º 27
0
 public void DeleteDocumentsExcept(params Type[] documentTypes)
 {
     var exemptedTables = documentTypes.Select(x => _schema.MappingFor(x).TableName).ToArray();
     using (var conn = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
     {
         _schema.DocumentTables().Where(x => !exemptedTables.Contains(x)).Each(tableName =>
         {
             var sql = "truncate {0} cascade".ToFormat(tableName);
             conn.Execute(sql);
         });
     }
 }
      internal SqlRdfBox (ManagedConnection connection, object box, bool is_complete, short rtype, short lang, long ro_id)
      {
	Debug.WriteLineIf (CLI.FnTrace.Enabled, "SqlRdfBox.ctor (connection, box, is_complete, rtype, lang, ro_id)");
	this.connection = connection;
	this.rb_box = box;
	this.rb_type = rtype;
	this.rb_lang = lang;
	this.rb_is_complete = is_complete;
	this.rb_ro_id = ro_id;
	this.rb_is_outlined = false;
	this.rb_chksum_tail = false;
      }
Exemplo n.º 29
0
        public void ResetTheRollingBufferSize(int size)
        {
            var functionName = new FunctionName(_options.Events.DatabaseSchemaName, "mt_reset_rolling_buffer_size");

            using (var conn = new ManagedConnection(_connectionFactory))
            {
                conn.Execute(cmd =>
                {
                    cmd.CallsSproc(functionName).AddParameter("size", size);
                });
            }
        }
Exemplo n.º 30
0
        public IEnumerable <ProjectionUsage> InitializeEventStoreInDatabase()
        {
            using (var connection = new ManagedConnection(_connectionFactory))
            {
                connection.Execute(cmd =>
                {
                    cmd.CallsSproc("mt_initialize_projections").ExecuteNonQuery();
                });
            }

            return(ProjectionUsages());
        }
Exemplo n.º 31
0
        public void DeleteDocumentsExcept(params Type[] documentTypes)
        {
            var exemptedTables = documentTypes.Select(x => _schema.MappingFor(x).TableName).ToArray();

            using (var conn = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
            {
                _schema.DocumentTables().Where(x => !exemptedTables.Contains(x)).Each(tableName =>
                {
                    var sql = "truncate {0} cascade".ToFormat(tableName);
                    conn.Execute(sql);
                });
            }
        }
Exemplo n.º 32
0
        private IDocumentSession openSession(DocumentTracking tracking, ManagedConnection connection, IList <IDocumentSessionListener> localListeners)
        {
            var sessionPool = CreateWriterPool();
            var map         = createMap(tracking, sessionPool, localListeners);

            var session = new DocumentSession(this, _options, Schema, _serializer, connection, _parser, map, sessionPool, localListeners);

            connection.BeginSession();

            session.Logger = _logger.StartSession(session);

            return(session);
        }
Exemplo n.º 33
0
        private void RenewSubtoken()
        {
            // Default to anonymous if permissions aren't requested
            // and while we wait for subtoken response.
            _connection = GameService.Gw2WebApi.AnonymousConnection;

            if (_permissions == null || !_permissions.Any())
            {
                return;
            }

            GameService.Gw2WebApi.RequestPrivilegedSubtoken(_permissions, SUBTOKEN_LIFETIME)
            .ContinueWith((subtokenTask) => _connection.SetApiKey(subtokenTask.Result));
        }
Exemplo n.º 34
0
        internal static IMarshal CreateExplicitString(string s, BoxTag tag, ManagedConnection connection)
        {
            switch (tag)
            {
            case BoxTag.DV_WIDE:
            case BoxTag.DV_LONG_WIDE:
            case BoxTag.DV_BLOB_WIDE:
            {
                byte[] bytes = Encoding.UTF8.GetBytes(s);
                return((bytes.Length < 256)
                                        ? (IMarshal) new ShortWideString(bytes)
                                        : (IMarshal) new LongWideString(bytes));
            }

            case BoxTag.DV_STRING:
            case BoxTag.DV_SHORT_STRING_SERIAL:
            case BoxTag.DV_STRICT_STRING:
            case BoxTag.DV_C_STRING:
            case BoxTag.DV_BLOB:
            {
                byte[] bytes;
                if (connection.charset_utf8)
                {
                    bytes = Encoding.UTF8.GetBytes(s);
                }
                else
                {
                    bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(s);
                }
                return((bytes.Length < 256)
                                        ? (IMarshal) new ShortString(bytes)
                                        : (IMarshal) new LongString(bytes));
            }

            case BoxTag.DV_BIN:
            case BoxTag.DV_BLOB_BIN:
            {
                byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(s);
                return((bytes.Length < 256)
                                        ? (IMarshal) new ShortString(bytes)
                                        : (IMarshal) new LongString(bytes));
            }

            default:
                // TODO:
                break;
            }

            return(null);
        }
Exemplo n.º 35
0
        public async Task log_execute_success_1_async()
        {
            var logger = new RecordingLogger();

            using (var connection = new ManagedConnection(new ConnectionSource())
            {
                Logger = logger
            })
            {
                connection.ExecuteAsync(async(c, tkn) => c.CommandText = "do something");

                logger.LastCommand.CommandText.ShouldBe("do something");
            }
        }
Exemplo n.º 36
0
        public void InitializeTheRollingBuffer()
        {
            runScript("mt_rolling_buffer");

            var functionName = new FunctionName(_options.Events.DatabaseSchemaName, "mt_seed_rolling_buffer");

            using (var conn = new ManagedConnection(_connectionFactory))
            {
                conn.Execute(cmd =>
                {
                    cmd.CallsSproc(functionName);
                });
            }
        }
Exemplo n.º 37
0
        internal TcpSession(ManagedConnection connection, Socket socket)
        {
            this.connection = connection;
            this.socket     = socket;

#if DEBUG_IO
            tcp_stream = new TcpStream(socket);
            stream     = new DebugStream(tcp_stream);
#else
            stream = new TcpStream(socket);
#endif
            written = false;
            broken  = false;
        }
Exemplo n.º 38
0
        public void CompletelyRemoveAll()
        {
            using (var connection = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
            {
                var schemaTables = _schema.DbObjects.SchemaTables();
                schemaTables
                    .Each(tableName => { connection.Execute($"DROP TABLE IF EXISTS {tableName} CASCADE;"); });

                var drops = connection.GetStringList(DropAllFunctionSql, new object[] { _schema.AllSchemaNames() });
                drops.Each(drop => connection.Execute(drop));

                _schema.ResetSchemaExistenceChecks();
            }
        }
      internal SqlRdfBox (ManagedConnection connection, object box, string rtype, string lang)
      {
	Debug.WriteLineIf (CLI.FnTrace.Enabled, "SqlRdfBox.ctor (connection, box, rtype, lang)");
	long ro_id;
	this.connection = connection;
	this.rb_box = box;
	ro_id = rdfMakeObj (box, rtype, lang);
	this.rb_type = GetTypeKey (rtype);
	this.rb_lang = GetLangKey (lang);
	this.rb_is_complete = false;
	this.rb_ro_id = ro_id;
	this.rb_is_outlined = false;
	this.rb_chksum_tail = false;
      }
Exemplo n.º 40
0
        public void log_execute_success_1()
        {
            var logger = new RecordingLogger();

            using (var connection = new ManagedConnection(new ConnectionSource(), new NulloRetryPolicy())
            {
                Logger = logger
            })
            {
                connection.Execute(c => c.CommandText = "do something");

                logger.LastCommand.CommandText.ShouldBe("do something");
            }
        }
Exemplo n.º 41
0
        public void CompletelyRemove(Type documentType)
        {
            var mapping = _schema.MappingFor(documentType);


            using (var connection = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
            {
                connection.Execute($"DROP TABLE IF EXISTS {mapping.TableName} CASCADE;");

                var dropTargets = _dropFunctionSql.ToFormat(mapping.UpsertName);

                var drops = connection.GetStringList(dropTargets);
                drops.Each(drop => connection.Execute(drop));
            }
        }
Exemplo n.º 42
0
        public void log_execute_failure_1()
        {
            var ex = new DivideByZeroException();
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                Exception<DivideByZeroException>.ShouldBeThrownBy(() =>
                {
                    connection.Execute(c =>
                    {
                        c.CommandText = "do something";
                        throw ex;
                    });
                });



                logger.LastCommand.CommandText.ShouldBe("do something");
                logger.LastException.ShouldBe(ex);
            }
        }
Exemplo n.º 43
0
        public void LoadProjections(string directory)
        {
            var files = new FileSystem();

            using (var connection = new ManagedConnection(_connectionFactory))
            {
                files.FindFiles(directory, FileSet.Deep("*.js")).Each(file =>
                {
                    var body = files.ReadStringFromFile(file);
                    var name = Path.GetFileNameWithoutExtension(file);

                    connection.Execute(cmd =>
                    {
                        cmd.CallsSproc(qualifyName("mt_load_projection_body"))
                            .With("proj_name", name)
                            .With("body", body)
                            .ExecuteNonQuery();

                    });
                });
            }
        }
Exemplo n.º 44
0
        public void log_execute_success_2()
        {
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                var cmd = new NpgsqlCommand();
                connection.Execute(cmd, c => c.CommandText = "do something");

                logger.LastCommand.ShouldBeSameAs(cmd);
            }
        }
		internal static object Unmarshal (Stream stream, ManagedConnection connection)
		{
		        string table = connection == null ? null : connection.charsetTable;
			Debug.WriteLineIf (CLI.FnTrace.Enabled, "Marshaler.Unmarshal ()");

			BoxTag tag = (BoxTag) ReadByte (stream);
			Debug.WriteLineIf (marshalSwitch.Enabled, "tag: " + tag);

			switch (tag)
			{
			case BoxTag.DV_NULL:
#if false
				return null;
#else
				return 0;
#endif

			case BoxTag.DV_DB_NULL:
				return DBNull.Value;

			case BoxTag.DV_ARRAY_OF_POINTER:
			case BoxTag.DV_LIST_OF_POINTER:
			{
				int n = UnmarshalInt (stream);
				object[] array = new object[n];
				Debug.WriteLineIf (marshalSwitch.Enabled, "array start [" + n + "] {");
				for (int i = 0; i < n; i++)
					array[i] = Unmarshal (stream, connection);
				Debug.WriteLineIf (marshalSwitch.Enabled, "array end");
				return array;
			}

			case BoxTag.DV_ARRAY_OF_LONG:
			{
				int n = UnmarshalInt (stream);
				int[] array = new int[n];
				Debug.WriteLineIf (marshalSwitch.Enabled, "array start [" + n + "] {");
				for (int i = 0; i < n; i++)
					array[i] = UnmarshalLongInt (stream);
				Debug.WriteLineIf (marshalSwitch.Enabled, "array end");
				return array;
			}

			case BoxTag.DV_ARRAY_OF_LONG_PACKED:
			{
				int n = UnmarshalInt (stream);
				int[] array = new int[n];
				Debug.WriteLineIf (marshalSwitch.Enabled, "array start [" + n + "] {");
				for (int i = 0; i < n; i++)
					array[i] = UnmarshalLongInt (stream);
				Debug.WriteLineIf (marshalSwitch.Enabled, "array end");
				return array;
			}

			case BoxTag.DV_ARRAY_OF_FLOAT:
			{
				int n = UnmarshalInt (stream);
				float[] array = new float[n];
				Debug.WriteLineIf (marshalSwitch.Enabled, "array start [" + n + "] {");
				for (int i = 0; i < n; i++)
					array[i] = UnmarshalSingle (stream);
				Debug.WriteLineIf (marshalSwitch.Enabled, "array end");
				return array;
			}

			case BoxTag.DV_ARRAY_OF_DOUBLE:
			{
				int n = UnmarshalInt (stream);
				double[] array = new double[n];
				Debug.WriteLineIf (marshalSwitch.Enabled, "array start [" + n + "] {");
				for (int i = 0; i < n; i++)
					array[i] = UnmarshalDouble (stream);
				Debug.WriteLineIf (marshalSwitch.Enabled, "array end");
				return array;
			}

			case BoxTag.DV_LONG_WIDE:
			{
				int i = 0, n = UnmarshalLongInt (stream);
				byte[] bytes = new byte[n];
				while (i < n)
					i += stream.Read (bytes, i, n - i);
				return Encoding.UTF8.GetString (bytes);
			}

			case BoxTag.DV_WIDE:
			{
				int i = 0, n = UnmarshalShortInt (stream);
				byte[] bytes = new byte[n];
				while (i < n)
					i += stream.Read (bytes, i, n - i);
				return Encoding.UTF8.GetString (bytes);
			}

			case BoxTag.DV_C_STRING:
			case BoxTag.DV_STRING:
			case BoxTag.DV_LONG_CONT_STRING:
			{
				int i = 0, n = UnmarshalLongInt (stream);
				byte[] bytes = new byte[n];
				while (i < n)
					i += stream.Read (bytes, i, n - i);
#if IGNORE_ENCODING
				return Encoding.GetEncoding("iso-8859-1").GetString (bytes);
#else
				if (connection.charset_utf8)
                                  return Encoding.UTF8.GetString (bytes);
				else
				  return Decode (table, bytes);
#endif
			}

			case BoxTag.DV_BOX_FLAGS:
			{
				int flags = UnmarshalLongInt (stream);
				object str = Unmarshal (stream, connection);
				return new SqlExtendedString(str.ToString(), flags);
			}

			case BoxTag.DV_RDF:
			{
      				int flags = ReadByte (stream);
				object box;
      				short type;
      				short lang;
      				bool is_complete = false;
      				long ro_id = 0L;

      				if (0 != (flags & (int)SqlRdfBoxFlags.RBS_CHKSUM))
				    throw new SystemException ("Invalid rdf box received.");

      				box = Unmarshal (stream, connection);
      				if (0 != (flags & (int)SqlRdfBoxFlags.RBS_OUTLINED))
      				  {
				    if (0 != (flags & (int)SqlRdfBoxFlags.RBS_64))
	  				ro_id = UnmarshalInt64 (stream);
				    else
	  				ro_id = UnmarshalLongInt (stream);
      				  }

      				if (0 != (flags & (int)SqlRdfBoxFlags.RBS_COMPLETE))
				    is_complete = true; 

      				if (0 != (flags & (int)SqlRdfBoxFlags.RBS_HAS_TYPE))
				    type = UnmarshalShort (stream);
      				else 
				    type = SqlRdfBox.DEFAULT_TYPE;

      				if (0 != (flags & (int)SqlRdfBoxFlags.RBS_HAS_LANG))
				    lang = UnmarshalShort (stream);
      				else 
				    lang = SqlRdfBox.DEFAULT_LANG;
      				return new SqlRdfBox (connection, box, is_complete, type, lang, ro_id);
			}

			case BoxTag.DV_C_SHORT:
			case BoxTag.DV_SHORT_STRING_SERIAL:
			case BoxTag.DV_SHORT_CONT_STRING:
			{
				int i = 0, n = UnmarshalShortInt (stream);
				byte[] bytes = new byte[n];
				while (i < n)
					i += stream.Read (bytes, i, n - i);
#if IGNORE_ENCODING
				return Encoding.GetEncoding("iso-8859-1").GetString (bytes);
#else
				if (connection.charset_utf8)
                                  return Encoding.UTF8.GetString (bytes);
				else
				  return Decode (table, bytes);
#endif
			}

			case BoxTag.DV_LONG_BIN:
			{
				int i = 0, n = UnmarshalLongInt (stream);
				byte[] bytes = new byte[n];
				while (i < n)
					i += stream.Read (bytes, i, n - i);
				return bytes;
			}

			case BoxTag.DV_BIN:
			{
				int i = 0, n = UnmarshalShortInt (stream);
				byte[] bytes = new byte[n];
				while (i < n)
					i += stream.Read (bytes, i, n - i);
				return bytes;
			}

			case BoxTag.DV_SINGLE_FLOAT:
				return UnmarshalSingle (stream);

			case BoxTag.DV_IRI_ID:
				return UnmarshalLongInt (stream);

			case BoxTag.DV_IRI_ID_8:
			case BoxTag.DV_INT64:
				return UnmarshalInt64 (stream);

			case BoxTag.DV_DOUBLE_FLOAT:
				return UnmarshalDouble (stream);

			case BoxTag.DV_SHORT_INT:
			{
				int i = UnmarshalShortInt (stream);
				if (i > 127)
					i -= 256;
				return i;
			}

			case BoxTag.DV_LONG_INT:
				return UnmarshalLongInt (stream);

			case BoxTag.DV_DATETIME:
			case BoxTag.DV_DATE:
			case BoxTag.DV_TIME:
			case BoxTag.DV_TIMESTAMP:
			case BoxTag.DV_TIMESTAMP_OBJ:
				return DateTimeMarshaler.UnmarshalDate (stream);

			case BoxTag.DV_NUMERIC:
				return UnmarshalNumeric (stream);

			case BoxTag.DV_BLOB_HANDLE:
			case BoxTag.DV_BLOB_WIDE_HANDLE:
				return UnmarshalBlobHandle (stream, tag);

			case BoxTag.DV_OBJECT:
				return UnmarshalObject (stream);

			case BoxTag.DV_STRING_SESSION:
				return UnmarshalStrses (stream);

			default:
				throw new SystemException ("Unknown data type " + tag + ".");
			}
		}
Exemplo n.º 46
0
        // TODO -- Really need to add some QueryHandlers for all this stuff to eliminate the duplication
        public SchemaObjects FindSchemaObjects(DocumentMapping mapping)
        {
            using (var connection = new ManagedConnection(_factory))
            {
                return connection.Execute(cmd =>
                {
                    cmd.CommandText = SchemaObjectsSQL;
                    cmd.AddParameter("schema", mapping.Table.Schema);
                    cmd.AddParameter("table_name", mapping.Table.Name);
                    cmd.AddParameter("function", mapping.UpsertFunction.Name);
                    cmd.AddParameter("qualified_name", mapping.Table.OwnerName);

                    var reader = cmd.ExecuteReader();

                    var columns = new List<TableColumn>();
                    while (reader.Read())
                    {
                        var column = new TableColumn(reader.GetString(0), reader.GetString(1));
                        columns.Add(column);
                    }

                    var pks = new List<string>();
                    reader.NextResult();
                    while (reader.Read())
                    {
                        pks.Add(reader.GetString(0));
                    }

                    reader.NextResult();
                    var upsertDefinition = reader.Read() ? reader.GetString(0) : null;

                    var indices = new List<ActualIndex>();
                    reader.NextResult();
                    while (reader.Read())
                    {
                        var index = new ActualIndex(mapping.Table, reader.GetString(3),
                            reader.GetString(4));

                        indices.Add(index);
                    }

                    var table = columns.Any() ? new TableDefinition(mapping.Table, pks.FirstOrDefault(), columns) : null;

                    reader.NextResult();
                    var drops = new List<string>();
                    while (reader.Read())
                    {
                        drops.Add(reader.GetString(0));
                    }

                    FunctionBody functionBody = upsertDefinition.IsEmpty() ? null : new FunctionBody(mapping.UpsertFunction, drops.ToArray(), upsertDefinition);
                    return new SchemaObjects(mapping.DocumentType, table, indices.ToArray(), functionBody);
                });
            }
        }
Exemplo n.º 47
0
        public void RebuildEventStoreSchema()
        {
            runScript("mt_stream");
            runScript("mt_initialize_projections");
            runScript("mt_apply_transform");
            runScript("mt_apply_aggregation");

            var js = SchemaBuilder.GetJavascript(_options, "mt_transforms");

            using (var connection = new ManagedConnection(_connectionFactory))
            {
                connection.Execute(cmd =>
                {
                    cmd.WithText($"insert into {modulesTable()} (name, definition) values (:name, :definition)")
                        .With("name", "mt_transforms")
                        .With("definition", js)
                        .ExecuteNonQuery();
                });
            }
        }
Exemplo n.º 48
0
        public IEnumerable<ProjectionUsage> ProjectionUsages()
        {
            string json = null;
            using (var connection = new ManagedConnection(_connectionFactory))
            {
                json = connection.Execute(cmd => cmd.CallsSproc(qualifyName("mt_get_projection_usage"))
                    .ExecuteScalar().As<string>());
            }

            return _serializer.FromJson<ProjectionUsage[]>(json);
        }
Exemplo n.º 49
0
 static ConnectionManager()
 {
     unsharedInstance = null;
     sharedInstances = new Dictionary<string, ManagedConnection>();
     connectionLock = new Object();
 }
Exemplo n.º 50
0
        public async Task log_execute_success_2_async()
        {
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                var cmd = new NpgsqlCommand();
                await connection.ExecuteAsync(cmd, async (c, tkn) => c.CommandText = "do something");

                logger.LastCommand.ShouldBeSameAs(cmd);
            }
        }
		internal static IMarshal CreateExplicitString (string s, BoxTag tag, ManagedConnection connection)
		{
			switch (tag)
			{
			case BoxTag.DV_WIDE:
			case BoxTag.DV_LONG_WIDE:
			case BoxTag.DV_BLOB_WIDE:
			{
				byte[] bytes = Encoding.UTF8.GetBytes (s);
				return ((bytes.Length < 256)
					? (IMarshal) new ShortWideString (bytes)
					: (IMarshal) new LongWideString (bytes));
			}

			case BoxTag.DV_STRING:
			case BoxTag.DV_SHORT_STRING_SERIAL:
			case BoxTag.DV_STRICT_STRING:
			case BoxTag.DV_C_STRING:
			case BoxTag.DV_BLOB:
			{
				byte[] bytes;
				if (connection.charset_utf8) 
					bytes = Encoding.UTF8.GetBytes (s);
				else
					bytes = Encoding.GetEncoding ("iso-8859-1").GetBytes (s);
				return ((bytes.Length < 256)
					? (IMarshal) new ShortString (bytes)
					: (IMarshal) new LongString (bytes));
			}

			case BoxTag.DV_BIN:
			case BoxTag.DV_BLOB_BIN:
			{
				byte[] bytes = Encoding.GetEncoding ("iso-8859-1").GetBytes (s);
				return ((bytes.Length < 256)
					? (IMarshal) new ShortString (bytes)
					: (IMarshal) new LongString (bytes));
			}

			default:
				// TODO:
				break;
			}

			return null;
		}
		internal static IMarshal CreateExecString (ManagedConnection connection, string value)
		{
			Debug.WriteLineIf (Marshaler.marshalSwitch.Enabled, "ExplicitString (" + value + ")");
            		byte[] bytes;
			if (connection.charset_utf8) 
			  bytes = WideToUTF8 (value);
			else
			  bytes = connection.utf8Execs
				? WideToUTF8 ("\n--utf8_execs=yes\n"+value)
				: WideToEscaped (connection.charsetMap, value);

			return ((bytes.Length < 256)
				? (IMarshal) new ShortString (bytes)
				: (IMarshal) new LongString (bytes));
		}
Exemplo n.º 53
0
        public async Task log_execute_success_with_answer_2_async()
        {
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                var cmd = new NpgsqlCommand();
                await connection.ExecuteAsync(cmd, async (c, tkn) =>
                {
                    await Task.CompletedTask;
                    return "something";
                });

                logger.LastCommand.ShouldBeSameAs(cmd);
            }
        }
Exemplo n.º 54
0
 private static ManagedConnection GetManagedConnection(AmqpChannelProperties channelProperties, bool connectionSharing)
 {
     if (connectionSharing)
     {
         string key = MakeKey(channelProperties);
         lock (connectionLock)
         {
             ManagedConnection mc = null;
             if (!sharedInstances.TryGetValue(key, out mc))
             {
                 mc = new ManagedConnection(true);
                 sharedInstances.Add(key, mc);
             }
             return mc;
         }
     }
     else
     {
         lock (connectionLock)
         {
             if (unsharedInstance == null)
             {
                 unsharedInstance = new ManagedConnection(false);
             }
             return unsharedInstance;
         }
     }
 }
Exemplo n.º 55
0
        public async Task log_execute_success_with_answer_1_async()
        {
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                await connection.Execute(async c =>
                {
                    await Task.CompletedTask;
                    c.CommandText = "do something";
                    return "something";
                });

                logger.LastCommand.CommandText.ShouldBe("do something");
            }
        }
Exemplo n.º 56
0
        public async Task log_execute_success_1_async()
        {
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                connection.ExecuteAsync(async (c, tkn) => c.CommandText = "do something");

                logger.LastCommand.CommandText.ShouldBe("do something");
            }
        }
Exemplo n.º 57
0
 public void DeleteAllEventData()
 {
     using (var connection = new ManagedConnection(_factory, CommandRunnerMode.ReadOnly))
     {
         connection.Execute($"truncate table {_schema.StoreOptions.DatabaseSchemaName}.mt_events cascade;" +
                            $"truncate table {_schema.StoreOptions.DatabaseSchemaName}.mt_streams cascade");
     }
 }
Exemplo n.º 58
0
        public void log_execute_with_answer_failure_2()
        {
            var ex = new DivideByZeroException();
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                var cmd = new NpgsqlCommand();

                Exception<DivideByZeroException>.ShouldBeThrownBy(() =>
                {
                    connection.Execute<string>(cmd, c =>
                    {
                        throw ex;
                    });
                });



                logger.LastCommand.ShouldBe(cmd);
                logger.LastException.ShouldBe(ex);
            }
        }
Exemplo n.º 59
0
        public async Task log_execute_with_answer_failure_1_async()
        {
            var ex = new DivideByZeroException();
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                await Exception<DivideByZeroException>.ShouldBeThrownByAsync(async () =>
                {
                    await connection.ExecuteAsync<string>(async (c, tkn) =>
                    {
                        await Task.CompletedTask;
                        c.CommandText = "do something";
                        throw ex;
                    });
                });



                logger.LastCommand.CommandText.ShouldBe("do something");
                logger.LastException.ShouldBe(ex);
            }
        }
Exemplo n.º 60
0
        public async Task log_execute_with_answer_failure_2_asycn()
        {
            var ex = new DivideByZeroException();
            var logger = new RecordingLogger();
            using (var connection = new ManagedConnection(new ConnectionSource()) {Logger = logger})
            {
                var cmd = new NpgsqlCommand();

                await Exception<DivideByZeroException>.ShouldBeThrownByAsync(async () =>
                {
                    await connection.ExecuteAsync<string>(cmd, async (c, tkn) =>
                    {
                        await Task.CompletedTask;
                        throw ex;
                    }
                )
                    ;
                });



                logger.LastCommand.ShouldBe(cmd);
                logger.LastException.ShouldBe(ex);
            }
        }