public void Should_execute_and_dispose_release_operations_with_different_partition_key_distinct_when_not_completed()
        {
            var fakeContainer    = new FakeContainer();
            var fakeCosmosClient = new FakeCosmosClient(fakeContainer);
            var containerHolderHolderResolver = new ContainerHolderResolver(new FakeProvider(fakeCosmosClient),
                                                                            new ContainerInformation("fakeContainer", new PartitionKeyPath("/deep/down")), "fakeDatabase");

            var storageSession        = new StorageSession(containerHolderHolderResolver, new ContextBag(), true);
            var firstReleaseOperation = new ReleaseLockOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(firstReleaseOperation);

            var secondReleaseOperation = new ReleaseLockOperation
            {
                PartitionKey = new PartitionKey("PartitionKey2")
            };

            storageSession.AddOperation(secondReleaseOperation);

            storageSession.Dispose();

            Assert.That(firstReleaseOperation.WasApplied, Is.True);
            Assert.That(secondReleaseOperation.WasApplied, Is.True);
            Assert.That(firstReleaseOperation.WasDisposed, Is.True);
            Assert.That(secondReleaseOperation.WasDisposed, Is.True);
            Assert.That(firstReleaseOperation.AppliedBatch, Is.Not.EqualTo(secondReleaseOperation.AppliedBatch), "Release operations with the different partition keys must be in different batches.");
        }
        public void Should_execute_and_dispose_release_operations_as_best_effort()
        {
            var fakeContainer = new FakeContainer
            {
                TransactionalBatchFactory = () => new ThrowsOnExecuteAsyncTransactionalBatch()
            };
            var fakeCosmosClient = new FakeCosmosClient(fakeContainer);
            var containerHolderHolderResolver = new ContainerHolderResolver(new FakeProvider(fakeCosmosClient),
                                                                            new ContainerInformation("fakeContainer", new PartitionKeyPath("/deep/down")), "fakeDatabase");

            var storageSession        = new StorageSession(containerHolderHolderResolver, new ContextBag(), true);
            var firstReleaseOperation = new ReleaseLockOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(firstReleaseOperation);

            var secondReleaseOperation = new ReleaseLockOperation
            {
                PartitionKey = new PartitionKey("PartitionKey2")
            };

            storageSession.AddOperation(secondReleaseOperation);

            Assert.DoesNotThrow(() => storageSession.Dispose());

            Assert.That(firstReleaseOperation.WasApplied, Is.True);
            Assert.That(secondReleaseOperation.WasApplied, Is.True);
            Assert.That(firstReleaseOperation.WasDisposed, Is.True);
            Assert.That(secondReleaseOperation.WasDisposed, Is.True);
        }
        public async Task Should_execute_operations_with_same_partition_key_together()
        {
            var fakeContainer    = new FakeContainer();
            var fakeCosmosClient = new FakeCosmosClient(fakeContainer);
            var containerHolderHolderResolver = new ContainerHolderResolver(new FakeProvider(fakeCosmosClient),
                                                                            new ContainerInformation("fakeContainer", new PartitionKeyPath("/deep/down")), "fakeDatabase");

            var storageSession = new StorageSession(containerHolderHolderResolver, new ContextBag(), true);
            var firstOperation = new FakeOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(firstOperation);
            var secondOperation = new FakeOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(secondOperation);

            await((ICompletableSynchronizedStorageSession)storageSession).CompleteAsync();

            Assert.That(firstOperation.WasApplied, Is.True);
            Assert.That(secondOperation.WasApplied, Is.True);
            Assert.That(firstOperation.AppliedBatch, Is.EqualTo(secondOperation.AppliedBatch), "Operations with the same partition key must be in the same batch");
        }
        public async Task Should_not_dispose_release_operations_when_operations_not_successful()
        {
            var fakeContainer    = new FakeContainer();
            var fakeCosmosClient = new FakeCosmosClient(fakeContainer);
            var containerHolderHolderResolver = new ContainerHolderResolver(new FakeProvider(fakeCosmosClient),
                                                                            new ContainerInformation("fakeContainer", new PartitionKeyPath("/deep/down")), "fakeDatabase");

            var storageSession = new StorageSession(containerHolderHolderResolver, new ContextBag(), true);
            var operation      = new ThrowOnApplyOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(operation);
            var releaseOperation = new ReleaseLockOperation
            {
                PartitionKey = new PartitionKey("PartitionKey1")
            };

            storageSession.AddOperation(releaseOperation);

            try
            {
                await((ICompletableSynchronizedStorageSession)storageSession).CompleteAsync();
            }
            catch
            {
                // ignored
            }

            Assert.That(releaseOperation.WasApplied, Is.False);
            Assert.That(releaseOperation.WasDisposed, Is.False);
        }
Example #5
0
        // Codigo de colision del trigger del area de salida:
        private void OnCollisionExitZone(Body b, Vector2 force, float direction)
        {
            if ((string)b.Tag == "player")
            {
                Manager.Scene.FindByName("player").Enabled = false;
                b.Fixed = true;

                Manager.Vars["currentLevel"] = (int)Manager.Vars["currentLevel"] + 1;

                if ((int)Manager.Vars["currentLevel"] > (int)Manager.Vars["lastLevel"])
                {
                    Manager.Vars["lastLevel"] = (int)Manager.Vars["currentLevel"];
                }

                Manager.Vars["score"]          = (int)Manager.Vars["score"] + 100;
                Manager.Vars["prev_CMYK_Ammo"] = (int)Manager.Vars["CMYK_Ammo"];
                Manager.Vars["exitLevel"]      = true;

                // Guardamos los progresos:
                Session.GameProgress.CurrentLevel    = (int)Manager.Vars["lastLevel"];
                Session.GameProgress.CurrentCMYKAmmo = (int)Manager.Vars["CMYK_Ammo"];
                Session.GameProgress.CurrentScore    = (int)Manager.Vars["score"];

                if (!Guide.IsTrialMode)
                {
                    StorageSession.SaveData(Session.SaveGameFilename, Session.GameProgress);
                }

                Kill();
            }
        }
Example #6
0
        public override void Update(GameTime gameTime)
        {
            // Si el dispositivo esta listo:
            if (StorageSession.IsDeviceInitialize && storageRequest)
            {
                storageRequest = false;

                // Cargamos el progreso del jugador:
                if (!Guide.IsTrialMode && StorageSession.FileExists(Session.SaveGameFilename))
                {
                    Session.GameProgress = StorageSession.LoadData <GameDefinitions.SaveGame>(Session.SaveGameFilename);
                }
                else // Si no hubiera archivo de progresos creamos progresos nuevos para el usuario:
                {
                    Session.GameProgress = new GameDefinitions.SaveGame();
                }

                // Cargamos la configuracion del usuario:
                if (StorageSession.FileExists(Session.SettingsFilename))
                {
                    Session.Settings = StorageSession.LoadData <GameDefinitions.GameSettings>(Session.SettingsFilename);
                }
                else
                {
                    Session.Settings = new GameDefinitions.GameSettings();
                }

                // Aplicamos la configuracion y restauramos progresos:
                Session.Apply();

                SetParams();
            }
        }
    public void UpdateWithTransitional()
    {
        var endpointName = nameof(UpdateWithTransitional);
        var definition   = new SagaDefinition(
            tableSuffix: "CorrAndTransitionalSaga",
            name: "CorrAndTransitionalSaga",
            correlationProperty: new CorrelationProperty
            (
                name: "CorrelationProperty",
                type: CorrelationPropertyType.String
            ),
            transitionalCorrelationProperty: new CorrelationProperty
            (
                name: "TransitionalCorrelationProperty",
                type: CorrelationPropertyType.String
            )
            );

        DropAndCreate(definition, endpointName, schema);
        var id        = Guid.NewGuid();
        var sagaData1 = new CorrAndTransitionalSaga.SagaData
        {
            Id = id,
            CorrelationProperty             = "theCorrelationProperty",
            TransitionalCorrelationProperty = "theTransitionalCorrelationProperty",
            OriginalMessageId = "theOriginalMessageId",
            Originator        = "theOriginator",
            SimpleProperty    = "PropertyValue"
        };

        var persister = SetUp(endpointName, schema);

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    persister.Save(sagaData1, storageSession, "theProperty").GetAwaiter().GetResult();
                    storageSession.CompleteAsync().GetAwaiter().GetResult();
                }

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    var sagaData = persister.Get <CorrAndTransitionalSaga.SagaData>(id, storageSession).GetAwaiter().GetResult();
                    sagaData.Data.SimpleProperty = "UpdatedValue";
                    persister.Update(sagaData.Data, storageSession, sagaData.Version).GetAwaiter().GetResult();
                    storageSession.CompleteAsync().GetAwaiter().GetResult();
                }

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    var sagaData = persister.Get <CorrAndTransitionalSaga.SagaData>(id, storageSession).GetAwaiter().GetResult();
                    Assert.IsNotNull(sagaData);
                    Approver.Verify(sagaData, s => s.Replace(id.ToString(), "theSagaId"));
                    Assert.AreEqual(2, sagaData.Version);
                }
    }
Example #8
0
 public IObservable<StorageObject> SubscribeObjects(StorageSession session, String param, IDictionary<String, String> args)
 {
     return Observable.FromEventPattern<StorageObjectEventArgs>(session.Parent, "Created")
         .SelectMany(e => e.EventArgs.Objects)
         .AsQbservable()
         .If(_ => args.ContainsKey("filter"), _ => _.Where(TriDQL.ParseLambda<StorageObject, Boolean>(args["filter"]).Compile()));
 }
 public MasterPageItemViewModel()
 {
     this.session = new StorageSession();
     Task.Run(async() => {
         await this.CargarMenu();
         await this.CargarNombreUsuario();
     });
 }
        protected void GetMBResult(IAsyncResult r)
        {
            int?b = Guide.EndShowMessageBox(r);

            Manager.Vars["showMessagePause"] = false;
            StorageSession.Release();
            Manager.GameStates.ChangeState("gametitle");
        }
Example #11
0
        public App()
        {
            InitializeComponent();
            this.session = new StorageSession();


            OnStart();
        }
 public ProductListsViewModel()
 {
     this.session = new StorageSession();
     this.repo    = new RepositoryProductList();
     Task.Run(async() =>
     {
         await this.CargarLista();
     });
 }
    public async Task CallbackThrows()
    {
        var exceptionThrown = false;
        var id       = Guid.NewGuid();
        var sagaData = new SagaWithCorrelation.SagaData
        {
            Id = id,
            OriginalMessageId   = "theOriginalMessageId",
            Originator          = "theOriginator",
            SimpleProperty      = "PropertyValue",
            CorrelationProperty = "theCorrelationProperty"
        };

        var persister  = SetUp(nameof(CallbackThrows), schema);
        var definition = new SagaDefinition(
            tableSuffix: "SagaWithCorrelation",
            name: "SagaWithCorrelation",
            correlationProperty: new CorrelationProperty
            (
                name: "CorrelationProperty",
                type: CorrelationPropertyType.String
            )
            );

        DropAndCreate(definition, nameof(CallbackThrows), schema);

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    await persister.Save(sagaData, storageSession, "theProperty").ConfigureAwait(false);

                    storageSession.OnSaveChanges(s =>
                    {
                        throw new Exception("Simulated");
                    });
                    try
                    {
                        await storageSession.CompleteAsync();
                    }
                    catch (Exception)
                    {
                        exceptionThrown = true;
                    }
                }

        Assert.IsTrue(exceptionThrown);

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    var savedEntity = await persister.Get <SagaWithCorrelation.SagaData>(id, storageSession).ConfigureAwait(false);

                    Assert.IsNull(savedEntity.Data);
                }
    }
Example #14
0
    public async Task <CompletableSynchronizedStorageSession> OpenSession(ContextBag contextBag)
    {
        var connection = await connectionManager.OpenConnection(contextBag.GetIncomingMessage()).ConfigureAwait(false);

        var transaction = connection.BeginTransaction();
        var session     = new StorageSession(connection, transaction, true, infoCache);

        currentSessionHolder.SetCurrentSession(session);
        return(session);
    }
 public Task<CompletableSynchronizedStorageSession> TryAdapt(OutboxTransaction transaction, ContextBag context)
 {
     var outboxTransaction = transaction as SqlOutboxTransaction;
     if (outboxTransaction != null)
     {
         CompletableSynchronizedStorageSession session = new StorageSession(outboxTransaction.Connection, outboxTransaction.Transaction, false);
         return Task.FromResult(session);
     }
     return EmptyResult;
 }
    public Task <CompletableSynchronizedStorageSession> TryAdapt(OutboxTransaction transaction, ContextBag context)
    {
        if (!(transaction is SqlOutboxTransaction outboxTransaction))
        {
            return(EmptyResultTask);
        }
        CompletableSynchronizedStorageSession session = new StorageSession(outboxTransaction.Connection, outboxTransaction.Transaction, false, infoCache);

        return(Task.FromResult(session));
    }
Example #17
0
        private void OnExitState(ButtonGroup group)
        {
            // Al salir del estado guardamos los cambios de configuracion si los hubiera:
            if (hasChanges)
            {
                hasChanges = false;
                StorageSession.SaveData(Session.SettingsFilename, Session.Settings);
            }

            Manager.GameStates.ChangeState("menu");
        }
    public async Task SaveDuplicateShouldThrow()
    {
        var endpointName = nameof(SaveDuplicateShouldThrow);

        var definition = new SagaDefinition(
            tableSuffix: "SagaWithCorrelation",
            name: "SagaWithCorrelation",
            correlationProperty: new CorrelationProperty
            (
                name: "CorrelationProperty",
                type: CorrelationPropertyType.String
            )
            );

        DropAndCreate(definition, endpointName, schema);
        var persister = SetUp(endpointName, schema);

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    var data = new SagaWithCorrelation.SagaData
                    {
                        Id = Guid.NewGuid(),
                        OriginalMessageId   = "theOriginalMessageId",
                        Originator          = "theOriginator",
                        CorrelationProperty = "theCorrelationProperty",
                        SimpleProperty      = "theSimpleProperty"
                    };
                    await persister.Save(data, storageSession, "theCorrelationProperty").ConfigureAwait(false);

                    await storageSession.CompleteAsync().ConfigureAwait(false);
                }
        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    var data = new SagaWithCorrelation.SagaData
                    {
                        Id = Guid.NewGuid(),
                        OriginalMessageId   = "theOriginalMessageId",
                        Originator          = "theOriginator",
                        CorrelationProperty = "theCorrelationProperty",
                        SimpleProperty      = "theSimpleProperty"
                    };
                    var throwsAsync = Assert.ThrowsAsync <Exception>(async() =>
                    {
                        await persister.Save(data, storageSession, "theCorrelationProperty").ConfigureAwait(false);
                        await storageSession.CompleteAsync().ConfigureAwait(false);
                    });
                    var innerException = throwsAsync.InnerException;
                    Assert.IsTrue(IsConcurrencyException(innerException));
                }
    }
    public Task <CompletableSynchronizedStorageSession> TryAdapt(OutboxTransaction transaction, ContextBag context, CancellationToken cancellationToken = default)
    {
        if (!(transaction is ISqlOutboxTransaction outboxTransaction))
        {
            return(EmptyResultTask);
        }
        var session = new StorageSession(outboxTransaction.Connection, outboxTransaction.Transaction, false, infoCache);

        currentSessionHolder?.SetCurrentSession(session);

        return(Task.FromResult <CompletableSynchronizedStorageSession>(session));
    }
 public Task<CompletableSynchronizedStorageSession> TryAdapt(TransportTransaction transportTransaction, ContextBag context)
 {
     SqlConnection existingSqlConnection;
     SqlTransaction existingSqlTransaction;
     //SQL server transport in native TX mode
     if (transportTransaction.TryGet(out existingSqlConnection) && transportTransaction.TryGet(out existingSqlTransaction))
     {
         CompletableSynchronizedStorageSession session = new StorageSession(existingSqlConnection, existingSqlTransaction, false);
         return Task.FromResult(session);
     }
     //Other modes handled by creating a new session.
     return EmptyResult;
 }
        public void Should_throw_when_no_container_available()
        {
            var fakeCosmosClient = new FakeCosmosClient(null);
            var containerHolderHolderResolver = new ContainerHolderResolver(new FakeProvider(fakeCosmosClient), null, "fakeDatabase");

            var storageSession = new StorageSession(containerHolderHolderResolver, new ContextBag(), true);
            var operation      = new FakeOperation();

            storageSession.AddOperation(operation);

            var exception = Assert.ThrowsAsync <Exception>(async() => await((ICompletableSynchronizedStorageSession)storageSession).CompleteAsync());

            Assert.That(exception.Message, Is.EqualTo("Unable to retrieve the container name and the partition key during processing. Make sure that either `persistence.Container()` is used or the relevant container information is available on the message handling pipeline."));
        }
    public async Task UpdateWithWrongVersion()
    {
        var wrongVersion = 666;
        var endpointName = nameof(UpdateWithWrongVersion);

        var definition = new SagaDefinition(
            tableSuffix: "SagaWithCorrelation",
            name: "SagaWithCorrelation",
            correlationProperty: new CorrelationProperty
            (
                name: "CorrelationProperty",
                type: CorrelationPropertyType.String
            )
            );

        DropAndCreate(definition, endpointName, schema);
        var id        = Guid.NewGuid();
        var sagaData1 = new SagaWithCorrelation.SagaData
        {
            Id = id,
            OriginalMessageId = "theOriginalMessageId",
            Originator        = "theOriginator",
            SimpleProperty    = "PropertyValue"
        };

        var persister = SetUp(endpointName, schema);

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    await persister.Save(sagaData1, storageSession, "theProperty").ConfigureAwait(false);

                    await storageSession.CompleteAsync().ConfigureAwait(false);
                }

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    var sagaData = await persister.Get <SagaWithCorrelation.SagaData>(id, storageSession).ConfigureAwait(false);

                    sagaData.Data.SimpleProperty = "UpdatedValue";

                    var exception = Assert.ThrowsAsync <Exception>(() => persister.Update(sagaData.Data, storageSession, wrongVersion));
                    Assert.IsTrue(exception.Message.Contains("Optimistic concurrency violation"));
                }
    }
    public async Task CallbackIsInvoked()
    {
        var callbackInvoked = false;

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    storageSession.OnSaveChanges(s =>
                    {
                        callbackInvoked = true;
                        return(Task.FromResult(0));
                    });
                    await storageSession.CompleteAsync();
                }
        Assert.IsTrue(callbackInvoked);
    }
    public async Task UseConfiguredSchema()
    {
        if (!SupportsSchemas())
        {
            Assert.Ignore();
        }


        var endpointName = nameof(SaveWithNoCorrelation);
        var definition   = new SagaDefinition(
            tableSuffix: "SagaWithNoCorrelation",
            name: "SagaWithNoCorrelation"
            );

        DropAndCreate(definition, endpointName, null);
        DropAndCreate(definition, endpointName, schema);

        var id = Guid.NewGuid();

        var schemaPersister        = SetUp(endpointName, schema);
        var defaultSchemaPersister = SetUp(endpointName, null);

        var sagaData = new SagaWithNoCorrelation.SagaData
        {
            Id = id,
            OriginalMessageId = "theOriginalMessageId",
            Originator        = "theOriginator",
            SimpleProperty    = "PropertyValue",
        };

        using (var connection = GetConnection()(null))
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, false, null))
                {
                    await defaultSchemaPersister.Save(sagaData, storageSession, null).ConfigureAwait(false);
                }

        using (var connection = GetConnection()(schema))
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, false, null))
                {
                    var result = (await schemaPersister.Get <SagaWithNoCorrelation.SagaData>(id, storageSession).ConfigureAwait(false)).Data;
                    Assert.IsNull(result);
                }
    }
Example #25
0
        public void OnEnterLevel(GridButtonGroup group)
        {
            if (group.Selected.Level == 1)
            {
                Manager.GameStates.ChangeState("intro");
            }
            else
            {
                Session.GameProgress = StorageSession.LoadData <GameDefinitions.SaveGame>(Session.SaveGameFilename);

                Manager.Vars["currentLevel"] = group.Selected.Level;
                Manager.Vars["CMYK_Ammo"]    = Session.GameProgress.CurrentCMYKAmmo;
                Manager.Vars["score"]        = Session.GameProgress.CurrentScore;
                ResetLevel reset = new ResetLevel();
                Manager.Scene.AddEntity(reset);
                reset.Inmediate = true;
            }
        }
Example #26
0
        public void SessionOpened(StorageSession session)
        {
            game.AppendStatusLine("Created.");

            var path = session.GetFullPathName("Test.txt");

            if (File.Exists(path) == true)
            {
                text.Length = 0;
                using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    var reader = new StreamReader(stream);
                    text.Append(reader.ReadToEnd());
                }
            }

            game.AppendStatusLine("Done.");
            game.ContainerSessionFinished();
        }
Example #27
0
 public IEnumerable<Activity> FetchArchive(StorageSession session, String param, IDictionary<String, String> args)
 {
     Account account = session.Query(StorageObjectExpressionQuery.Activity(
         new ActivityTuple
         {
             Name = "ScreenName",
             Value = args["target"],
         }
     ))
         .OrderByDescending(a => a)
         .First()
         .Account;
     DateTime date = args.ContainsKey("date") ? DateTime.ParseExact(args["date"], "yyMMdd", null) : DateTime.Now;
     return new StringReader("<_>" +
         new StringReader("<html>" + new WebClient()
             .Dispose(c => Encoding.UTF8.GetString(c.DownloadData(
                 String.Format(
                     "http://twilog.org/source.cgi?id={0}&date={1}&order=asc&word={2}&cate=&filter=&type=div",
                     args["target"],
                     args["date"],
                     args.ContainsKey("word") ? args["word"] : ""
                 )
             ))) + "</html>"
         )
             .Dispose(sr => XmlReader.Create(sr)
                 .Dispose(xr => xr
                     .Apply(_ => _.ReadToFollowing("textarea"))
                     .ReadElementContentAsString()
                 )
             ) + "</_>"
     )
         .Dispose(sr => XmlReader.Create(sr)
             .Dispose(xr => XDocument.Load(xr))
         )
         .Descendants("div")
         .Select(xe => account.Act(
             "Status",
             Int64.Parse(xe.XPathEvaluate<String>("substring-after(p[@class='tl-posted']/a/@href,'status/')")),
             date + TimeSpan.ParseExact(xe.XPathEvaluate<String>("string(p[@class='tl-posted']/a)"), @"hh\:mm\:ss", null),
             a => a.Act("Body", xe.XPathEvaluate<String>("string(p[@class='tl-text'])"))
         ))
         .ToArray();
 }
    async Task <NonStringCorrelationSaga.SagaData> GetByNonStringMappingAsync(Guid id, string endpointName)
    {
        var sagaData = new NonStringCorrelationSaga.SagaData
        {
            Id = id,
            OriginalMessageId   = "theOriginalMessageId",
            Originator          = "theOriginator",
            CorrelationProperty = 10
        };
        var persister = SetUp(endpointName, schema);

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    await persister.Save(sagaData, storageSession, 666).ConfigureAwait(false);

                    return((await persister.Get <NonStringCorrelationSaga.SagaData>("CorrelationProperty", 666, storageSession).ConfigureAwait(false)).Data);
                }
    }
    async Task <SagaWithStringCorrelation.SagaData> GetByStringMappingAsync(Guid id, string endpointName, CancellationToken cancellationToken = default)
    {
        var sagaData = new SagaWithStringCorrelation.SagaData
        {
            Id = id,
            OriginalMessageId   = "theOriginalMessageId",
            Originator          = "theOriginator",
            CorrelationProperty = "theCorrelationProperty"
        };
        var persister = SetUp(endpointName, schema);

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    await persister.Save(sagaData, storageSession, "theCorrelationProperty", cancellationToken).ConfigureAwait(false);

                    return((await persister.Get <SagaWithStringCorrelation.SagaData>("CorrelationProperty", "theCorrelationProperty", storageSession, cancellationToken).ConfigureAwait(false)).Data);
                }
    }
        public void Should_dispose_operations()
        {
            var fakeCosmosClient = new FakeCosmosClient(null);
            var containerHolderHolderResolver = new ContainerHolderResolver(new FakeProvider(fakeCosmosClient), null, "fakeDatabase");

            var storageSession = new StorageSession(containerHolderHolderResolver, new ContextBag(), true);
            var firstOperation = new FakeOperation();

            storageSession.AddOperation(firstOperation);
            var secondOperation = new FakeOperation();

            storageSession.AddOperation(secondOperation);

            storageSession.Dispose();

            Assert.That(firstOperation.WasDisposed, Is.True);
            Assert.That(firstOperation.WasApplied, Is.False);
            Assert.That(secondOperation.WasDisposed, Is.True);
            Assert.That(secondOperation.WasApplied, Is.False);
        }
    public async Task Complete()
    {
        var endpointName = nameof(Complete);
        var definition   = new SagaDefinition(
            tableSuffix: "SagaWithCorrelation",
            name: "SagaWithCorrelation",
            correlationProperty: new CorrelationProperty
            (
                name: "CorrelationProperty",
                type: CorrelationPropertyType.String
            ),
            transitionalCorrelationProperty: new CorrelationProperty
            (
                name: "TransitionalCorrelationProperty",
                type: CorrelationPropertyType.String
            )
            );

        DropAndCreate(definition, endpointName, schema);
        var id       = Guid.NewGuid();
        var sagaData = new SagaWithCorrelation.SagaData
        {
            Id = id,
            OriginalMessageId   = "theOriginalMessageId",
            Originator          = "theOriginator",
            CorrelationProperty = "theCorrelationProperty"
        };

        var persister = SetUp(endpointName, schema);

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    await persister.Save(sagaData, storageSession, "theProperty").ConfigureAwait(false);

                    await persister.Complete(sagaData, storageSession, 1).ConfigureAwait(false);

                    Assert.IsNull((await persister.Get <SagaWithCorrelation.SagaData>(id, storageSession).ConfigureAwait(false)).Data);
                }
    }
    async Task <SagaWithSpaceInName.SagaData> SaveWithSpaceAsync(Guid id, string endpointName)
    {
        var sagaData = new SagaWithSpaceInName.SagaData
        {
            Id = id,
            OriginalMessageId = "original message id",
            Originator        = "the originator",
            SimpleProperty    = "property value"
        };

        var persister = SetUp(endpointName, schema);

        using (var connection = dbConnection())
            using (var transaction = connection.BeginTransaction())
                using (var storageSession = new StorageSession(connection, transaction, true, null))
                {
                    await persister.Save(sagaData, storageSession, "property value").ConfigureAwait(false);

                    return((await persister.Get <SagaWithSpaceInName.SagaData>(id, storageSession).ConfigureAwait(false)).Data);
                }
    }
Example #33
0
        public void SessionOpened(StorageSession session)
        {
            game.AppendStatusLine("Created.");

            var path = session.GetFullPathName("Test.txt");

            if (File.Exists(path) == true)
            {
                File.Delete(path);
            }

            using (var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write))
            {
                var writer = new StreamWriter(stream);
                writer.Write(text);
                writer.Close();
            }

            game.AppendStatusLine("Done.");
            game.ContainerSessionFinished();
        }
Example #34
0
        private async void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var  item = (MasterPageItem)e.SelectedItem;
            Type page = item.PaginaHija;

            if (item.Titulo == "Cerrar sesión")
            {
                StorageSession session = new StorageSession();
                session.RemoveAllStorage();
                Application.Current.MainPage = new LoginView();
                IsPresented = false;
            }
            else
            {
                Detail = new NavigationPage((Page)Activator.CreateInstance(page))
                {
                    BarBackgroundColor = Color.ForestGreen
                };
                IsPresented = false;
            }
        }
Example #35
0
 public Object OutputAsIs(Object input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return args.ContainsKey("code")
         ? TriDQL.ParseLambda(input.GetType(), typeof(Object), args["code"])
               .Compile()
               .DynamicInvoke(input)
         : input;
 }
Example #36
0
 public String OutputFlowInterfacesAsTableXml(IEnumerable<FlowInterfaceInfo> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return this.OutputFlowInterfacesAsTable(input, session, param, args)
         .XmlObjectSerializeToString<IList<IList<String>>, DataContractSerializer>();
 }
 public Account GetAccount(StorageSession context)
 {
     return this._account != null && this._account.Context == context
         ? this._account
         : this._account = context.Load(this._accountId);
 }
Example #38
0
 public IObservable<String> OutputStorageObjectAsXmlStream(IObservable<StorageObject> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     DataContractSerializer serializer = new DataContractSerializer(
         typeof(StorageObject),
         null,
         Int32.MaxValue,
         true,
         false,
         new StorageObjectIdConverter()
     );
     return input.Select(o => o.XmlObjectSerializeToString(serializer));
 }
Example #39
0
 public IEnumerable<StorageObject> OutputStorageObjects(IEnumerable<StorageObject> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return input.OrderByDescending(o => o).Remotable();
 }
Example #40
0
 public IObservable<String> OutputStorageObjectsAsCustomJsonStream(IObservable<StorageObject> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     IDisposable _ = session.SuppressDispose();
     return input
         .Select(o => JObject.FromObject(TriDQL.ParseLambda<StorageObject, Object>(args["code"]).Compile()(o))
             .ToString(args.Contains("oneline", "true") ? Formatting.None : Formatting.Indented) + "\r\n"
         )
         .Catch((Exception ex) => Observable.Return(ex.ToString()))
         .Finally(_.Dispose);
 }
Example #41
0
 public String OutputJson(Object input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return JObject.FromObject(input).ToString(args.Contains("oneline", "true") ? Formatting.None : Formatting.Indented);
 }
Example #42
0
        public String OutputStorageObjectsAsJson(IEnumerable<StorageObject> input, StorageSession session, String param, IDictionary<String, String> args)
        {
            return new StringWriter().Apply(_ => _.Dispose(w => JsonSerializer.Create(new JsonSerializerSettings()
            {
                Converters = new JsonConverter[] { new StorageObjectIdConverter(), },
                DefaultValueHandling = DefaultValueHandling.Ignore,
                NullValueHandling = NullValueHandling.Ignore,
                PreserveReferencesHandling = PreserveReferencesHandling.None,
                TypeNameHandling = TypeNameHandling.None,
            }).Serialize(w, input.OrderByDescending(o => o).ToArray()))).ToString();

        }
Example #43
0
 public IList<IList<String>> OutputStoredRequestAsTable(IEnumerable<StoredRequest> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return (args.Contains("sign", "true")
         ? Make.Sequence(Make.Array("Name", "Description", "Signature"))
               .Concat(input.OfType<StoredRequest>().Select(s => Make.Array(
                   s.Name,
                   s.Description,
                   "[" +
                       s.Parameters.Values
                           .Select(d => "{" + d.Select(p => String.Format("\"{0}\":\"{1}\"", p.Key, p.Value)).Join(",") + "}")
                           .Join(",") +
                   "]"
               )))
         : Make.Sequence(Make.Array("Name", "Description", "Parameters"))
               .Concat(input.OfType<StoredRequest>().Select(s => Make.Array(
                   s.Name,
                   s.Description,
                   s.Parameters.Values.Select(e => e["name"]).Join(", ")
               )))
     ).ToArray();
 }
Example #44
0
 public IList<IList<String>> OutputModuleObjectsAsTable(IEnumerable<IModule> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return Make.Sequence(Make.Array("Name", "Kind", "Type", "DomainID", "State"))
         .Concat(input.OfType<IModule>().Select(m => Make.Array(
             m.Name,
             GetKind(m),
             m.GetType().Name,
             m.Domain.AppDomain.Id.ToString(),
             m is ServantModule
                 ? ((ServantModule) m).IsStarted
                       ? "Start"
                       : "Stop"
                 : "-"
         )))
         .ToArray();
 }
Example #45
0
 public IEnumerable<Advertisement> GetAdvertisements(StorageSession session, String param, IDictionary<String, String> args)
 {
     return session.Query(StorageObjectDynamicQuery.Advertisement(args.GetValueOrDefault("query")));
 }
Example #46
0
 public String OutputStoredRequestAsTableJson(IEnumerable<StoredRequest> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return this.OutputStoredRequestAsTable(input, session, param, args)
         .XmlObjectSerializeToString<IList<IList<String>>, DataContractJsonSerializer>();
 }
Example #47
0
 public IEnumerable<StorageObject> NullInput(StorageSession session, String param, IDictionary<String, String> args)
 {
     return Enumerable.Empty<StorageObject>();
 }
Example #48
0
 public IList<IList<String>> OutputFlowInterfacesAsTable(IEnumerable<FlowInterfaceInfo> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return Make.Sequence(Make.Array("ID", "Summary", "Remarks", "Input", "Output", "Flags"))
         .Concat(input.OfType<FlowInterfaceInfo>().Select(i => Make.Array(
             i.Id,
             i.Summary ?? "(null)",
             i.Remarks ?? "(null)",
             i.InputType != null
                 ? i.InputType.ToString().Substring(i.InputType.Namespace.Length + 1)
                 : "-",
             i.OutputType.ToString().Substring(i.OutputType.Namespace.Length + 1),
             String.Concat(
                 i.RequiresInput ? "<tt title='Requires input'>I</tt>" : "<tt title='Not requires input'>-</tt>",
                 i.HandlesVariables ? "<tt title='Handles variables'>V</tt>" : "<tt title='Not handles variables'>-</tt>"
             )
         )))
         .ToArray();
 }
Example #49
0
 public IEnumerable<Activity> GetActivities(StorageSession session, String param, IDictionary<String, String> args)
 {
     return session.Query(StorageObjectDynamicQuery.Activity(args.GetValueOrDefault("query")));
 }
Example #50
0
 public IObservable<String> OutputJson(IObservable<Object> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return input
         .Select(_ => JObject.FromObject(_).ToString(args.Contains("oneline", "true") ? Formatting.None : Formatting.Indented));
 }
Example #51
0
 public String OutputModuleDomainsAsTableXml(IEnumerable<IModuleDomain> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return this.OutputModuleDomainsAsTable(input, session, param, args)
         .XmlObjectSerializeToString<IList<IList<String>>, DataContractSerializer>();
 }
 public Activity GetActivity(StorageSession context)
 {
     return this._activity != null && this._activity.Context == context
         ? this._activity
         : this._activity = context.Load(this._activityId);
 }
Example #53
0
 public Byte[] OutputBinaryData(IEnumerable<StorageObject> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return input.OfType<Activity>().SingleOrDefault(a => a.GetValue() is IEnumerable<Byte>)
         .GetValue<Byte[]>();
 }
Example #54
0
 public IObservable<String> OutputStorageObjectAsJsonStream(IObservable<StorageObject> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings()
     {
         Converters = new JsonConverter[] { new StorageObjectIdConverter(), },
         DefaultValueHandling = DefaultValueHandling.Ignore,
         NullValueHandling = NullValueHandling.Ignore,
         PreserveReferencesHandling = PreserveReferencesHandling.None,
         TypeNameHandling = TypeNameHandling.None,
     });
     return input.Select(o => new StringWriter().Apply(_ => _.Dispose(w => serializer.Serialize(w, o))).ToString());
 }
Example #55
0
 public IList<IList<String>> OutputModuleDomainsAsTable(IEnumerable<IModuleDomain> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return Make.Sequence(Make.Array("Name", "DomainID", "DomainName", "ModuleCount"))
         .Concat(input.OfType<IModuleDomain>().Select(d => Make.Array(
             d.Key,
             d.AppDomain.Id.ToString(),
             d.AppDomain.FriendlyName,
             d.Modules.Count.ToString()
         )))
         .ToArray();
 }
Example #56
0
 public String OutputStorageObjectsAsXml(IEnumerable<StorageObject> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     DataContractSerializer serializer = new DataContractSerializer(
         typeof(IEnumerable<StorageObject>),
         null,
         Int32.MaxValue,
         true,
         false,
         new StorageObjectIdConverter()
     );
     return input
         .OrderByDescending(o => o)
         .ToArray()
         .XmlObjectSerializeToString(serializer);
 }
Example #57
0
 public String OutputStorageObjectsAsCustomText(IEnumerable<StorageObject> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return String.Concat(input
         .OrderByDescending(o => o)
         .ToArray()
         .Select(TriDQL.ParseLambda<StorageObject, String>(args["code"]).Compile())
     );
 }
 /// <summary>
 /// フロー インターフェイスを呼び出します。
 /// </summary>
 /// <param name="module">呼び出しに用いるモジュール オブジェクト。</param>
 /// <param name="input">フィルタ処理の入力として与えるストレージ オブジェクトのシーケンス。</param>
 /// <param name="session">ストレージ オブジェクトの入出力先として使用するストレージ セッション。</param>
 /// <param name="parameter">処理のパラメータ。</param>
 /// <param name="arguments">処理の引数のディクショナリ。</param>
 /// <param name="variables">リクエスト間で受け渡される変数のディクショナリ。</param>
 /// <returns>処理の結果。</returns>
 public Object Invoke(
     FlowModule module,
     Object input = null,
     StorageSession session = null,
     String parameter = null,
     IDictionary<String, String> arguments = null,
     IDictionary<String, Object> variables = null
 )
 {
     LinkedList<Object> args = new LinkedList<Object>();
     if(this.RequiresInput)
     {
         args.AddLast(input);
     }
     if(this.RequiresSession)
     {
         args.AddLast(session);
     }
     if(this.RequiresParameter)
     {
         args.AddLast(parameter ?? "");
     }
     if(this.RequiresArguments)
     {
         args.AddLast(arguments ?? new Dictionary<String, String>());
     }
     if(this.HandlesVariables)
     {
         args.AddLast(variables ?? new Dictionary<String, Object>());
     }
     Object output = this._method.Invoke(module, args.ToArray());
     if (session != null)
     {
         session.Update();
     }
     return output;
 }
Example #59
0
 public IList<IList<String>> OutputStorageObjectsAsTable(IEnumerable<StorageObject> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     switch (input.First().ObjectType)
     {
         case StorageObjectTypes.Account:
             return Make.Sequence(Make.Array("Id", "Realm", "Seed"))
                 .Concat(input.OfType<Account>().Select(a => Make.Array(
                     a.Id.ToString(),
                     a.Realm,
                     a.Seed
                 )))
                 .ToArray();
         case StorageObjectTypes.Activity:
             return Make.Sequence(Make.Array("Id", "Account", "Parent", "Name", "Value"))
                 .Concat(input.OfType<Activity>().Select(a => Make.Array(
                     a.Id.ToString(),
                     a.Account.ToString(),
                     a.Depth > 0 ? a.Ancestors.First().ToString() : "",
                     a.Name,
                     a.GetValue<String>()
                 )))
                 .ToArray();
         default: // case StorageObjectTypes.Advertisement:
             return Make.Sequence(Make.Array("Id", "Activity", "Timestamp", "Flags"))
                 .Concat(input.OfType<Advertisement>().Select(a => Make.Array(
                     a.Id.ToString(),
                     a.Activity.ToString(),
                     a.Timestamp.ToString("s"),
                     a.Flags.ToString()
                 )))
                 .ToArray();
     }
 }
Example #60
0
 public IList<IList<String>> OutputRequestTasksAsTable(IEnumerable<IRequestTask> input, StorageSession session, String param, IDictionary<String, String> args)
 {
     return Make.Sequence(Make.Array("Id", "State", "StartedAt", "ExitedAt", "Elapsed", "Step", "Request", "OutputType"))
         .Concat(input.OfType<IRequestTask>().Select(t => Make.Array(
             t.Id.ToString(),
             t.State.ToString(),
             t.StartTime != null ? t.StartTime.Value.ToString("r") : "-",
             t.ExitTime != null ? t.ExitTime.Value.ToString("r") : "-",
             t.ElapsedTime.ToString(),
             t.StepCount.ToString(),
             t.Request.ToString(),
             t.OutputType != null ? t.OutputType.Name : "-"
         )))
         .ToArray();
 }