protected override async Task AddTransaction(long transactionId, byte[] mutationHash, Mutation mutation) { foreach (Record record in mutation.Records) { RecordKey key = RecordKey.Parse(record.Key); await ExecuteAsync(@" UPDATE Records SET Type = @type, Name = @name WHERE Key = @key", new Dictionary<string, object>() { ["@key"] = record.Key.ToByteArray(), ["@type"] = (int)key.RecordType, ["@name"] = key.Name }); await ExecuteAsync(@" INSERT INTO RecordMutations (RecordKey, TransactionId, MutationHash) VALUES (@recordKey, @transactionId, @mutationHash)", new Dictionary<string, object>() { ["@recordKey"] = record.Key.ToByteArray(), ["@transactionId"] = transactionId, ["@mutationHash"] = mutationHash }); } }
public void Mutation_Success() { Mutation mutation = new Mutation( binaryData[0], new[] { new Record(binaryData[1], binaryData[2], binaryData[3]), new Record(binaryData[4], null, binaryData[5]), }, binaryData[6]); byte[] result = MessageSerializer.SerializeMutation(mutation); Mutation finalMutation = MessageSerializer.DeserializeMutation(new ByteString(result)); Assert.Equal(244, result.Length); Assert.Equal(mutation.Records.Count, finalMutation.Records.Count); Assert.Equal(mutation.Records[0].Key, finalMutation.Records[0].Key); Assert.Equal(mutation.Records[0].Value, finalMutation.Records[0].Value); Assert.Equal(mutation.Records[0].Version, finalMutation.Records[0].Version); Assert.Equal(mutation.Records[1].Key, finalMutation.Records[1].Key); Assert.Equal(mutation.Records[1].Value, finalMutation.Records[1].Value); Assert.Equal(mutation.Records[1].Version, finalMutation.Records[1].Version); Assert.Equal(mutation.Namespace, finalMutation.Namespace); Assert.Equal(mutation.Metadata, finalMutation.Metadata); }
protected override IMutation PreSpawnMutation() { Mutation result = new Mutation(); result.AddGeneticModifier(new Blur(Set.ALL, new Set(new [] {"scale"}), 0.5F)); result.AddGeneticModifier(new SingleBlur(new Set(new [] {"root"}),new Set(new [] {"lifeduration"}), 100.0F)); result.AddGeneticModifier(new SingleBlur(new Set(new [] {"root"}), new Set(new [] {"speed"}), 0.2F)); return result; }
public void notifyInitialized(Mutation mutation) { //mutations[initializedMutations++] = mutation; initializedMutations++; if(initializedMutations==totalMutations){ curHealth = maxHealth; } }
protected override IMutation PreSpawnMutation() { Mutation result = new Mutation(); result.AddGeneticModifier(new Blur(Set.ALL, new Set(new [] {"scale"}), 0.2F)); // It won't have much effect since the joints force to be aligned. result.AddGeneticModifier(new Blur(Set.ALL, new Set(new[] { "rotation" }), 10)); result.AddGeneticModifier(new SingleBlur(new Set(new [] {"root"}),new Set(new [] {"lifeduration"}), 500)); return result; }
public void Ctor_assigns_property_Description() { // Arrange var someString = "any string"; // Act var sut = new Mutation<ClassToTest>(someString, d => d.IntProperty = 2); // Assert Assert.Equal(someString, sut.Description); }
public void Apply_calls_mutationToApply_on_argument() { // Arrange var initialValue = 4; var initial = new ClassToTest(initialValue); var sut = new Mutation<ClassToTest>("some string", d => d.IntProperty += 2); // Act sut.Apply(initial); // Assert Assert.Equal(initialValue + 2, initial.IntProperty); }
public async Task PostTransaction_EmptyMutation() { Dictionary<string, long> accounts = new Dictionary<string, long>(); TransactionValidator validator = CreateValidator(accounts); Mutation mutation = new Mutation( validNamespace, new Record[0], ByteString.Empty); TransactionInvalidException exception = await Assert.ThrowsAsync<TransactionInvalidException>( () => validator.PostTransaction(new ByteString(MessageSerializer.SerializeMutation(mutation)), new SignatureEvidence[0])); Assert.Equal("InvalidMutation", exception.Reason); }
public static ParsedMutation Parse(Mutation mutation) { List<AccountStatus> accountMutations = new List<AccountStatus>(); List<KeyValuePair<RecordKey, ByteString>> dataRecords = new List<KeyValuePair<RecordKey, ByteString>>(); foreach (Record record in mutation.Records) { // This is used for optimistic concurrency and does not participate in the validation if (record.Value == null) continue; try { RecordKey key = RecordKey.Parse(record.Key); switch (key.RecordType) { case RecordType.Account: accountMutations.Add(AccountStatus.FromRecord(key, record)); break; case RecordType.Data: dataRecords.Add(new KeyValuePair<RecordKey, ByteString>(key, record.Value)); break; } } catch (ArgumentOutOfRangeException ex) when (ex.ParamName == "keyData") { // Deserializing and re-serializing the record gives a different result throw new TransactionInvalidException("NonCanonicalSerialization"); } catch (ArgumentOutOfRangeException ex) when (ex.ParamName == "path") { // The path is invalid throw new TransactionInvalidException("InvalidPath"); } catch (ArgumentOutOfRangeException ex) when (ex.ParamName == "recordType") { // The specified record type is unknown throw new TransactionInvalidException("InvalidRecord"); } catch (ArgumentOutOfRangeException ex) when (ex.ParamName == "record") { // The value of an ACC record could not be deserialized throw new TransactionInvalidException("InvalidRecord"); } } return new ParsedMutation(accountMutations, dataRecords); }
public void ClearTextReporter_ShouldPrintGreenAboveThresholdHigh() { string output = ""; var chalkMock = new Mock <IChalk>(MockBehavior.Strict); chalkMock.Setup(x => x.Default(It.IsAny <string>())).Callback((string text) => { output += text; }); chalkMock.Setup(x => x.Green(It.IsAny <string>())).Callback((string text) => { output += text; }); var tree = CSharpSyntaxTree.ParseText("void M(){ int i = 0 + 8; }"); var originalNode = tree.GetRoot().DescendantNodes().OfType <BinaryExpressionSyntax>().First(); var mutation = new Mutation() { OriginalNode = originalNode, ReplacementNode = SyntaxFactory.BinaryExpression(SyntaxKind.SubtractExpression, originalNode.Left, originalNode.Right), DisplayName = "This name should display", Type = Mutator.Arithmetic }; var target = new ClearTextReporter(new StrykerOptions(), chalkMock.Object); var folder = new FolderComposite() { Name = "RootFolder", RelativePath = "RootFolder", FullPath = "C://RootFolder", }; folder.Add(new FileLeaf() { Name = "SomeFile.cs", RelativePath = "RootFolder/SomeFile.cs", RelativePathToProjectFile = "SomeFile.cs", FullPath = "C://RootFolder/SomeFile.cs", Mutants = new Collection <Mutant>() { new Mutant() { ResultStatus = MutantStatus.Killed, Mutation = mutation }, } }); target.OnAllMutantsTested(folder); chalkMock.Verify(x => x.Green(It.IsAny <string>()), Times.Exactly(2)); }
static T Get <T>(uint id) { T ret = default(T); // prevent string decryptors from invoking this method if (!Equals(Assembly.GetCallingAssembly(), Assembly.GetExecutingAssembly()) || new StackTrace().GetFrame(1).GetMethod().DeclaringType == typeof(RuntimeMethodHandle)) { return(ret); } // demutate the id id = (uint)Mutation.Placeholder((int)id); // get the type uint type = id >> 30; // get actual id id &= 0x3fffffff; id <<= 2; if (type == Mutation.KeyI0) { // read a string preceded by a 32bit length int int len = buffer[id++] | (buffer[id++] << 8) | (buffer[id++] << 16) | (buffer[id++] << 24); ret = (T)(object)string.Intern(Encoding.UTF8.GetString(buffer, (int)id, len)); } // NOTE: Assume little-endian else if (type == Mutation.KeyI1) { //read an int var v = new T[1]; Buffer.BlockCopy(buffer, (int)id, v, 0, Mutation.Value <int>()); ret = v[0]; } else if (type == Mutation.KeyI2) { // read an array int structLength = buffer[id++] | (buffer[id++] << 8) | (buffer[id++] << 16) | (buffer[id++] << 24); int arrayLength = buffer[id++] | (buffer[id++] << 8) | (buffer[id++] << 16) | (buffer[id++] << 24); Array v = Array.CreateInstance(typeof(T).GetElementType(), arrayLength); Buffer.BlockCopy(buffer, (int)id, v, 0, structLength - 4); ret = (T)(object)v; } return(ret); }
public override void DeleteCells(string table, string rowKey, bool writeToWal, List <string> columns, Dictionary <string, string> attributes) { byte[] tableName = Encode(table); byte[] row = Encode(rowKey); Dictionary <byte[], byte[]> encodedAttributes = EncodeAttributes(attributes); List <Mutation> mutations = new List <Mutation>(); foreach (string column in columns) { Mutation mutation = new Mutation(); mutation.IsDelete = true; mutation.WriteToWAL = writeToWal; mutation.Column = Encode(column); mutations.Add(mutation); } client.mutateRow(tableName, row, mutations, encodedAttributes); }
private async Task AddRecords(params string[] keys) { Mutation mutation = new Mutation( ByteString.Empty, keys.Select(key => new Record( new ByteString(Encoding.UTF8.GetBytes(key)), ByteString.Empty, ByteString.Empty)), ByteString.Empty); Transaction transaction = new Transaction( new ByteString(MessageSerializer.SerializeMutation(mutation)), new DateTime(), ByteString.Empty); await store.AddTransactions(new[] { new ByteString(MessageSerializer.SerializeTransaction(transaction)) }); }
/// <summary>Snippet for MutateRowAsync</summary> public async Task MutateRow2Async() { // Snippet: MutateRowAsync(string, ByteString, IEnumerable<Mutation>, string, CallSettings) // Additional: MutateRowAsync(string, ByteString, IEnumerable<Mutation>, string, CancellationToken) // Create client BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync(); // Initialize request argument(s) string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]"; ByteString rowKey = ByteString.Empty; IEnumerable <Mutation> mutations = new Mutation[] { new Mutation(), }; string appProfileId = ""; // Make the request MutateRowResponse response = await bigtableServiceApiClient.MutateRowAsync(tableName, rowKey, mutations, appProfileId); // End snippet }
/// <summary>Snippet for CommitAsync</summary> public async Task Commit2Async() { // Snippet: CommitAsync(string, CommitRequest.Types.Mode, IEnumerable<Mutation>, CallSettings) // Additional: CommitAsync(string, CommitRequest.Types.Mode, IEnumerable<Mutation>, CancellationToken) // Create client DatastoreClient datastoreClient = await DatastoreClient.CreateAsync(); // Initialize request argument(s) string projectId = ""; CommitRequest.Types.Mode mode = CommitRequest.Types.Mode.Unspecified; IEnumerable <Mutation> mutations = new Mutation[] { new Mutation(), }; // Make the request CommitResponse response = await datastoreClient.CommitAsync(projectId, mode, mutations); // End snippet }
/// <summary> /// This Funds a wallet from a External Bank Deposit. /// </summary> /// <param name="connection">ES connection</param> /// <param name="walletAccount">Account name of a wallet</param> /// <param name="CashAccount">The Cash account</param> /// <param name="amount">Transaction amount</param> /// <param name="currency">Currency ISO 3</param> /// <param name="description">Free test filed</param> /// <param name="description2">Free text field</param> public void HandleWalletDeposit(IEventStoreConnection connection, string walletAccount, string CashAccount, decimal amount, string currency, string description, string description2) { // reset the objects ResetManager(); // get the last mutations of the both Accounts walletAccountLastEvent = Mutation.FromJson(AccountManager.GetLastEvent(connection, walletAccount)); cashAccountLastEvent = Mutation.FromJson(AccountManager.GetLastEvent(connection, CashAccount)); // // TODO Must check if the CashAccount is of the type Cash and the Wallet Account of the Type Wallet. If not then do not continue. // // Create a Posting Object. posting = MutationEventManager.CreatePosting(walletAccountLastEvent, cashAccountLastEvent, Enums.MutationTypes.Deposit, Enums.MutationEntryTypes.Dr, amount, currency, description, description2); Mutation walletAccountNewEvent = posting.Mutations[0]; Mutation CashAccountNewEvent = posting.Mutations[1]; // create an eventStore Event for the 2 Postings var myEvent1 = new EventData(Guid.Parse(walletAccountNewEvent.MutationId), EventTypes.WalletFunded.ToString(), true, Encoding.UTF8.GetBytes(Mutation.ToJson(walletAccountNewEvent)), null); var myEvent2 = new EventData(Guid.Parse(CashAccountNewEvent.MutationId), EventTypes.WalletFunded.ToString(), true, Encoding.UTF8.GetBytes(Mutation.ToJson(CashAccountNewEvent)), null); // TODO validate the balance the wallet account can not be negative // TODO Calculate the fee // TODO transaction learn about it // this takes to long 165 ms.. // Events is a Array. One day need to try to experiment with this. // First Credit the Cash Account connection.AppendToStreamAsync(CashAccount, CashAccountNewEvent.PreviousEventNumber, myEvent2).Wait(); //Then Debit the Wallet Account connection.AppendToStreamAsync(walletAccount, walletAccountNewEvent.PreviousEventNumber, myEvent1).Wait(); // var st = new System.Diagnostics.Stopwatch(); // st.Start(); // st.Stop(); // System.Diagnostics.Debug.WriteLine($"Mutation created: {st.ElapsedMilliseconds} ms"); }
/// <summary> /// Sets the edges corresponding to predicates on the node with the given uid for deletion. This /// function returns a new <see cref="Mutation"/> object with the edges set. It is the caller's responsibility to /// run the mutation by calling <see cref="Transaction.MutateAsync(Mutation)"/>. /// </summary> /// <param name="mu">Mutation to add edges to</param> /// <param name="uid">uid uid of the node</param> /// <param name="predicates">predicates predicates of the edges to remove</param> /// <returns>a new Mutation object with the edges set</returns> public static Mutation CreateDeleteEdgesMutation(Mutation mu, String uid, params string[] predicates) { Mutation b = new Mutation(mu); foreach (var predicate in predicates) { b.Del.Add(new NQuad() { Subject = uid, Predicate = predicate, ObjectValue = new Value { DefaultVal = "_STAR_ALL" } }); } return(b); }
public void test_commit_after_CommitNow() { Assert.ThrowsAsync <TxnFinishedException>(async() => { using (var txn = _client.NewTransaction()) { var mut = new Mutation { SetNquads = ByteString.CopyFromUtf8("<_:bob> <name> \"Bob\" ."), CommitNow = true }; await txn.MutateAsync(mut); await txn.CommitAsync(); } }); }
public async Task test_delete() { using (var txn = _client.NewTransaction()) { var mutation = new Mutation { SetNquads = ByteString.CopyFromUtf8("<_:bob> <name> \"Bob\" .") }; var ag = await txn.MutateAsync(mutation); string bob = ag.Uids["bob"]; string query = new StringBuilder() .AppendLine("{") .AppendLine($"find_bob(func: uid({bob}))") .AppendLine("{") .AppendLine("name") .AppendLine("}") .AppendLine("}") .ToString(); var resp = await txn.QueryAsync(query); var json = JObject.Parse(resp.Json.ToStringUtf8()); var arr = json.GetValue("find_bob") as JArray; Assert.IsTrue(arr.Count > 0); mutation = new Mutation { DelNquads = ByteString.CopyFromUtf8($"<{bob}> * * .") }; await txn.MutateAsync(mutation); resp = await txn.QueryAsync(query); json = JObject.Parse(resp.Json.ToStringUtf8()); arr = json.GetValue("find_bob") as JArray; Assert.IsTrue(arr.Count == 0); await txn.CommitAsync(); } }
/// <summary>Snippet for MutateRowAsync</summary> public async Task MutateRow2ResourceNamesAsync() { // Snippet: MutateRowAsync(TableName, ByteString, IEnumerable<Mutation>, string, CallSettings) // Additional: MutateRowAsync(TableName, ByteString, IEnumerable<Mutation>, string, CancellationToken) // Create client BigtableClient bigtableClient = await BigtableClient.CreateAsync(); // Initialize request argument(s) TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"); ByteString rowKey = ByteString.Empty; IEnumerable <Mutation> mutations = new Mutation[] { new Mutation(), }; string appProfileId = ""; // Make the request MutateRowResponse response = await bigtableClient.MutateRowAsync(tableName, rowKey, mutations, appProfileId); // End snippet }
/// <inheritdoc/> public async Task <IPullRequestReviewCommentModel> PostPendingReviewComment( ILocalRepositoryModel localRepository, IAccount user, string pendingReviewId, string body, string commitId, string path, int position) { var address = HostAddress.Create(localRepository.CloneUrl.Host); var graphql = await graphqlFactory.CreateConnection(address); var comment = new AddPullRequestReviewCommentInput { Body = body, CommitOID = commitId, Path = path, Position = position, PullRequestReviewId = pendingReviewId, }; var addComment = new Mutation() .AddPullRequestReviewComment(comment) .Select(x => new PullRequestReviewCommentModel { Id = x.Comment.DatabaseId.Value, NodeId = x.Comment.Id, Body = x.Comment.Body, CommitId = x.Comment.Commit.Oid, Path = x.Comment.Path, Position = x.Comment.Position, CreatedAt = x.Comment.CreatedAt.Value, DiffHunk = x.Comment.DiffHunk, OriginalPosition = x.Comment.OriginalPosition, OriginalCommitId = x.Comment.OriginalCommit.Oid, PullRequestReviewId = x.Comment.PullRequestReview.DatabaseId.Value, User = user, IsPending = true, }); var result = await graphql.Run(addComment); await usageTracker.IncrementCounter(x => x.NumberOfPRReviewDiffViewInlineCommentPost); return(result); }
static int Main(string[] args) { var l = (uint)Mutation.KeyI0; uint[] q = Mutation.Placeholder(new uint[Mutation.KeyI0]); GCHandle h = Decrypt(q, (uint)Mutation.KeyI1); var b = (byte[])h.Target; var assemblyLoadCtx = Type.GetType("System.Runtime.Loader.AssemblyLoadContext"); if (assemblyLoadCtx != null) { var assemblyLoadCtxDef = assemblyLoadCtx.GetProperty("Default")?.GetValue(null); var assemblyLoadCtxLoad = assemblyLoadCtx.GetMethod("LoadFromStream", new Type[] { typeof(Stream) }); if (assemblyLoadCtxDef != null && assemblyLoadCtxLoad != null) { assemblyLoad = (datas) => (Assembly)assemblyLoadCtxLoad.Invoke(assemblyLoadCtxDef, new object[] { new MemoryStream(datas) }); } } Assembly a = assemblyLoad(b); Array.Clear(b, 0, b.Length); h.Free(); Array.Clear(q, 0, q.Length); var m = typeof(CompressorCompat).Module; key = m.ResolveSignature(Mutation.KeyI2); AppDomain.CurrentDomain.AssemblyResolve += Resolve; MethodBase e = a.ManifestModule.ResolveMethod(key[0] | (key[1] << 8) | (key[2] << 16) | (key[3] << 24)); var g = new object[e.GetParameters().Length]; if (g.Length != 0) { g[0] = args; } object r = e.Invoke(null, g); if (r is int) { return((int)r); } return(0); }
public async Task Move_ValidInput_CallsGameManager() { // arrange var moveInput = new MoveInput { GameId = "abcdef", Player = Player.Cross, BoardPosition = new Position(0, 0), TilePosition = new Position(0, 0) }; var gameManagerMock = new Mock <IGameManager>(); gameManagerMock .Setup(m => m.Move(It.IsAny <Move>(), CancellationToken.None)) .ReturnsAsync(new MoveResult { Move = moveInput.ToMove(), InvalidReason = null, IsValid = false, MoveFinishedGame = false, MoveFinishedBoard = false, }); var eventSenderMock = new Mock <IEventSender>(); eventSenderMock .Setup(m => m.SendAsync(It.IsAny <IEventMessage>())) .Returns(Task.CompletedTask) .Verifiable(); var mutation = new Mutation(); //act var result = await mutation.Move( moveInput, gameManagerMock.Object, eventSenderMock.Object, CancellationToken.None); //assert gameManagerMock.Verify( m => m.Move(It.IsAny <Move>(), CancellationToken.None), Times.Once); }
public static void CreateBabyMonkey(MonkeyDNA motherDNA, MonkeyDNA fatherDNA, Transform mother) { MonkeyDNA dna = new MonkeyDNA(); Mutation mutation = new Mutation(); Crossover crossover = new Crossover(); dna.speed = mutation.MutateGene(crossover.Cross(motherDNA.speed, fatherDNA.speed), DNA.SPEED_MIN, DNA.SPEED_MAX); dna.foodViewRange = mutation.MutateGene(crossover.Cross(motherDNA.foodViewRange, fatherDNA.foodViewRange), DNA.FOODVIEWRANGE_MIN, DNA.FOODVIEWRANGE_MAX); dna.waterViewRange = mutation.MutateGene(crossover.Cross(motherDNA.waterViewRange, fatherDNA.waterViewRange), DNA.WATERVIEWRANGE_MIN, DNA.FOODVIEWRANGE_MAX); dna.sex = mutation.RandomizeSex(); var monkey = Instantiate(Instance.babyMonkey, mother.position, Quaternion.identity).GetComponent <BabyMonkey>(); AnimalStatistics.Instance.AddAnimal(monkey.matureMaleMonkey); monkey.Initialize(dna); }
private static GCHandle Decrypt(uint[] data, uint seed) { var w = new uint[0x10]; var k = new uint[0x10]; ulong s = seed; for (var i = 0; i < 0x10; i++) { s = s * s % 0x143fc089; k[i] = (uint)s; w[i] = (uint)(s * s % 0x444d56fb); } Mutation.Crypt(w, k); Array.Clear(k, 0, 0x10); var b = new byte[data.Length << 2]; uint h = 0; for (var i = 0; i < data.Length; i++) { var d = data[i] ^ w[i & 0xf]; w[i & 0xf] = (w[i & 0xf] ^ d) + 0x3ddb2819; b[h + 0] = (byte)(d >> 0); b[h + 1] = (byte)(d >> 8); b[h + 2] = (byte)(d >> 16); b[h + 3] = (byte)(d >> 24); h += 4; } Array.Clear(w, 0, 0x10); var j = Lzma.Decompress(b); Array.Clear(b, 0, b.Length); var g = GCHandle.Alloc(j, GCHandleType.Pinned); var z = (uint)(s % 0x8a5cb7); for (var i = 0; i < j.Length; i++) { j[i] ^= (byte)s; if ((i & 0xff) == 0) { s = s * s % 0x8a5cb7; } } return(g); }
public void Star_And_Unstar_Project() { var viewerHasStarredQuery = new Query().Repository(Helper.Username, _repoName).Select(repository => repository.ViewerHasStarred); var viewerHasStarred = Connection.Run(viewerHasStarredQuery).Result; Assert.False(viewerHasStarred); var clientMutationId = "abc123"; var addStarQuery = new Mutation().AddStar(new AddStarInput { ClientMutationId = clientMutationId, StarrableId = _repositoryId }).Select(payload => new { payload.ClientMutationId, StarrableId = payload.Starrable.Id, payload.Starrable.ViewerHasStarred }); var addStarResult = Connection.Run(addStarQuery).Result; Assert.Equal(addStarResult.ClientMutationId, clientMutationId); Assert.Equal(addStarResult.StarrableId, _repositoryId); Assert.True(addStarResult.ViewerHasStarred); clientMutationId = "def456"; var removeStarQuery = new Mutation().RemoveStar(new RemoveStarInput() { ClientMutationId = clientMutationId, StarrableId = _repositoryId }).Select(payload => new { payload.ClientMutationId, StarrableId = payload.Starrable.Id, payload.Starrable.ViewerHasStarred }); var removeStarResult = Connection.Run(removeStarQuery).Result; Assert.Equal(removeStarResult.ClientMutationId, clientMutationId); Assert.Equal(removeStarResult.StarrableId, _repositoryId); Assert.False(removeStarResult.ViewerHasStarred); }
public async void CreateCampaign_ReturnsCreatedCampaign() { // Arrange await using var context = _tb.DatabaseContext; var campaignInput = new Campaign { Name = "New Campaign", Description = "Created in Unit Test" }; var mutation = new Mutation(); // Act var campaign = await mutation.CreateCampaign(context, "MutationTests User 2", campaignInput); // Assert Assert.True(string.Equals("MutationTests User 2", campaign.UserId)); }
public void Create_And_Delete_Project() { var projectName = "ProjectName_" + _ticks; var projectDesc = "ProjectDesc_" + _ticks; var clientMutationId = "abc123"; var createProjectQuery = new Mutation() .CreateProject(new CreateProjectInput() { Name = projectName, OwnerId = _repositoryId, //TODO: This is not required but the code fails if we leave this empty ClientMutationId = clientMutationId, Body = projectDesc }) .Select(payload => new { payload.ClientMutationId, ProjectId = payload.Project.Id, ProjectName = payload.Project.Name, ProjectOwnerId = payload.Project.Owner.Id }); var projectData = Connection.Run(createProjectQuery).Result; Assert.Equal(projectData.ClientMutationId, clientMutationId); Assert.Equal(projectData.ProjectName, projectName); Assert.Equal(projectData.ProjectOwnerId, _repositoryId); clientMutationId = "def456"; var deleteProjectQuery = new Mutation() .DeleteProject(new DeleteProjectInput() { ProjectId = projectData.ProjectId, //TODO: This is not required but the code fails if we leave this empty ClientMutationId = clientMutationId }) .Select(payload => new { ProjectOwnerId = payload.Owner.Id, payload.ClientMutationId, }); var deleteResult = Connection.Run(deleteProjectQuery).Result; Assert.Equal(deleteResult.ClientMutationId, clientMutationId); Assert.Equal(deleteResult.ProjectOwnerId, _repositoryId); }
public void Simulate(int count, int length, int min, int max, int maxGeneration) { m_Population = new Population <T>(count, length, min, max); m_Population.Evaluate(Fitness); m_Population.Save(Filename, false); if (Debug != null && (DebugMask & DebugMask.First) != 0) { Debug.Log(m_Population); } while (m_Population.Generation < maxGeneration) { m_Population.Elite(Elitism); do { IChromosome <T> parent1 = Selection.Select(m_Population); IChromosome <T> parent2 = Selection.Select(m_Population); IChromosome <T> offspring1, offspring2; Crossover.Crossover(parent1, parent2, out offspring1, out offspring2); Mutation.Mutate(ref offspring1, min, max); Mutation.Mutate(ref offspring2, min, max); m_Population.AddChromosomeInNewPopulation(offspring1); m_Population.AddChromosomeInNewPopulation(offspring2); } while (!m_Population.IsFullNewGeneration); m_Population.SwapGeneration(); m_Population.Evaluate(Fitness); m_Population.Save(Filename, true); if (Debug != null && (DebugMask & DebugMask.Step) != 0) { Debug.Log(m_Population); } } if (Debug != null && (DebugMask & DebugMask.Last) != 0) { Debug.Log(m_Population); } }
public async Task <Assigned> MutateAsync(Mutation mutation, CancellationToken cancellationToken) { if (readOnly) { throw new Exception("A Read-Only Transaction cannot be mutated"); } if (finished) { throw new Exception("A finished Transaction cannot be mutated"); } mutated = true; mutation.StartTs = context.StartTs; Assigned assigned; try { assigned = await client.MutateAsync(request : mutation, cancellationToken : cancellationToken); if (mutation.CommitNow) { finished = true; } MergeContext(assigned.Context); } catch (RpcException e) { try { await DiscardAsync(cancellationToken); } catch { // TODO Problems discarding the Transaction shouldn't go unnoticed ... } throw e; } return(assigned); }
async Task <bool> DeletePackageVersion(IConnection connection, ID versionId) { try { var input = new DeletePackageVersionInput { PackageVersionId = versionId, ClientMutationId = "GrpTool" }; var mutation = new Mutation().DeletePackageVersion(input).Select(p => p.Success).Compile(); var payload = await connection.Run(mutation); return(payload.Value); } catch (GraphQLException e) { Console.WriteLine(e.Message); return(false); } }
private string GetPayingAddress(Mutation outgoingTransaction) { try { string metadata = Encoding.UTF8.GetString(outgoingTransaction.Metadata.ToByteArray(), 0, outgoingTransaction.Metadata.Value.Count); JObject root = JObject.Parse(metadata); return(BitcoinAddress.Create((string)root["routing"], network).ToString()); } catch (JsonReaderException) { return(null); } catch (FormatException) { return(null); } }
public override void Update(string table, string rowKey, bool writeToWal, Dictionary <string, string> fieldNameValues, Dictionary <string, string> attributes) { byte[] tableName = Encode(table); byte[] row = Encode(rowKey); Dictionary <byte[], byte[]> encodedAttributes = EncodeAttributes(attributes); List <Mutation> mutations = new List <Mutation>(); foreach (KeyValuePair <String, String> pair in fieldNameValues) { Mutation mutation = new Mutation(); mutation.IsDelete = false; mutation.WriteToWAL = writeToWal; mutation.Column = Encode(pair.Key); mutation.Value = Encode(pair.Value); mutations.Add(mutation); } client.mutateRow(tableName, row, mutations, encodedAttributes); }
/// <summary>Snippet for CheckAndMutateRowAsync</summary> public async Task CheckAndMutateRow1Async() { // Snippet: CheckAndMutateRowAsync(string, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CallSettings) // Additional: CheckAndMutateRowAsync(string, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CancellationToken) // Create client BigtableServiceApiClient bigtableServiceApiClient = await BigtableServiceApiClient.CreateAsync(); // Initialize request argument(s) string tableName = "projects/[PROJECT]/instances/[INSTANCE]/tables/[TABLE]"; ByteString rowKey = ByteString.Empty; RowFilter predicateFilter = new RowFilter(); IEnumerable <Mutation> trueMutations = new Mutation[] { new Mutation(), }; IEnumerable <Mutation> falseMutations = new Mutation[] { new Mutation(), }; // Make the request CheckAndMutateRowResponse response = await bigtableServiceApiClient.CheckAndMutateRowAsync(tableName, rowKey, predicateFilter, trueMutations, falseMutations); // End snippet }
/// <inheritdoc/> public async Task CancelPendingReview( ILocalRepositoryModel localRepository, string reviewId) { var address = HostAddress.Create(localRepository.CloneUrl.Host); var graphql = await graphqlFactory.CreateConnection(address); var delete = new DeletePullRequestReviewInput { PullRequestReviewId = reviewId, }; var deleteReview = new Mutation() .DeletePullRequestReview(delete) .Select(x => x.ClientMutationId); await graphql.Run(deleteReview); }
/// <summary>Snippet for CheckAndMutateRowAsync</summary> public async Task CheckAndMutateRow1ResourceNamesAsync() { // Snippet: CheckAndMutateRowAsync(TableName, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CallSettings) // Additional: CheckAndMutateRowAsync(TableName, ByteString, RowFilter, IEnumerable<Mutation>, IEnumerable<Mutation>, CancellationToken) // Create client BigtableClient bigtableClient = await BigtableClient.CreateAsync(); // Initialize request argument(s) TableName tableName = TableName.FromProjectInstanceTable("[PROJECT]", "[INSTANCE]", "[TABLE]"); ByteString rowKey = ByteString.Empty; RowFilter predicateFilter = new RowFilter(); IEnumerable <Mutation> trueMutations = new Mutation[] { new Mutation(), }; IEnumerable <Mutation> falseMutations = new Mutation[] { new Mutation(), }; // Make the request CheckAndMutateRowResponse response = await bigtableClient.CheckAndMutateRowAsync(tableName, rowKey, predicateFilter, trueMutations, falseMutations); // End snippet }
public static Mutation CreateMutation(MutationMethod mutationMethod, MutationMethod[] mutationMethods, int[][] population, double mutationProbability, Random random) { Mutation mutation = mutationMethod switch { MutationMethod.RSM => new RSMutation(mutationProbability, population, random), MutationMethod.TWORS => new TWORSMutation(mutationProbability, population, random), MutationMethod.CIM => new CIMutation(mutationProbability, population, random), MutationMethod.THROAS => new THROASMutation(mutationProbability, population, random), MutationMethod.THRORS => new THRORSMutation(mutationProbability, population, random), MutationMethod.MAM => new MAMutation(mutationMethods, mutationProbability, population, random), MutationMethod.MRM => new MRMutation(mutationMethods, mutationProbability, population, random), _ => throw new AggregateException("Wrong mutation method name") }; return(mutation); } }
//sets up the initial GA public GeneticAlgo CreateGA(string[][] _sampleGenomes) { System.Random r = new System.Random(Time.frameCount); //specify the numbers of genes to the population. string selectType = "god mode"; string mutateType = "randomChoice"; string crossType = "OnePt"; Encoder encoder = _encode; Fitness fitness = new Fitness(""); Population population = new Population(_childCount, encoder._symbols, samplePopulation: _sampleGenomes, variableGenomeLength: true); Selection selection = new Selection(selectType); CrossOver crossover = new CrossOver(crossType); Mutation mutation = new Mutation(mutateType, _mutationRate); return(new GeneticAlgo(encoder, fitness, population, selection, crossover, mutation)); }
public override DecimalArrayChromosome FindOptimum() { var best = new DecimalArrayChromosome(Constants.ChromosomeSize) { Fitness = decimal.MaxValue }; for (var i = 0; i < IterationLimit; i++) { var nextGeneration = new Population <DecimalArrayChromosome>(PopulationSize); if (Elitism) { nextGeneration.Add(GetPopulationBest()); } while (nextGeneration.Count() < PopulationSize) { var selectedFromPopulation = Selection.Select(Population); var childChromosome = Crossover.Cross(selectedFromPopulation.First(), selectedFromPopulation[1]); childChromosome = Mutation.Mutate(childChromosome); childChromosome.Fitness = FitnessFunction.GetValue(childChromosome); nextGeneration.Add(childChromosome); } Population = nextGeneration; var populationBest = GetPopulationBest(); if (populationBest.Fitness < best.Fitness) { best = populationBest; Console.WriteLine("Iteration: " + i + ", Best fitness: " + populationBest.Fitness + ", " + best); } if (populationBest.Fitness < FitnessTerminator) { break; } } return(best); }
public async Task PostTransaction_MaxKeySize() { Dictionary<string, long> accounts = new Dictionary<string, long>(); TransactionValidator validator = CreateValidator(accounts); Mutation mutation = new Mutation( validNamespace, new Record[] { new Record( ByteString.Parse(new string('a', 513 * 2)), new ByteString(BitConverter.GetBytes(100L).Reverse()), ByteString.Empty) }, ByteString.Empty); TransactionInvalidException exception = await Assert.ThrowsAsync<TransactionInvalidException>( () => validator.PostTransaction(new ByteString(MessageSerializer.SerializeMutation(mutation)), new SignatureEvidence[0])); Assert.Equal("InvalidMutation", exception.Reason); }
public void Mutation_Success() { Mutation mutation = new Mutation( binaryData[0], new[] { new Record(binaryData[1], binaryData[2], binaryData[3]), new Record(binaryData[4], null, binaryData[5]), }, binaryData[6]); Assert.Equal(2, mutation.Records.Count); Assert.Equal(binaryData[1], mutation.Records[0].Key); Assert.Equal(binaryData[2], mutation.Records[0].Value); Assert.Equal(binaryData[3], mutation.Records[0].Version); Assert.Equal(binaryData[4], mutation.Records[1].Key); Assert.Equal(null, mutation.Records[1].Value); Assert.Equal(binaryData[5], mutation.Records[1].Version); Assert.Equal(binaryData[0], mutation.Namespace); Assert.Equal(binaryData[6], mutation.Metadata); }
/// <summary> /// Atomically checks if a row/family/qualifier value matches the expected /// value. If it does, it adds the corresponding mutation operation for put. /// /// @return true if the new put was executed, false otherwise /// </summary> /// <param name="tableName">name of table</param> /// <param name="row">row key</param> /// <param name="column">column name</param> /// <param name="value">the expected value for the column parameter, if notprovided the check is for the non-existence of thecolumn in question</param> /// <param name="mput">mutation for the put</param> /// <param name="attributes">Mutation attributes</param> public bool checkAndPut(byte[] tableName, byte[] row, byte[] column, byte[] value, Mutation mput, Dictionary<byte[], byte[]> attributes) { #if !SILVERLIGHT send_checkAndPut(tableName, row, column, value, mput, attributes); return recv_checkAndPut(); #else var asyncResult = Begin_checkAndPut(null, null, tableName, row, column, value, mput, attributes); return End_checkAndPut(asyncResult); #endif }
public void send_checkAndPut(byte[] tableName, byte[] row, byte[] column, byte[] value, Mutation mput, Dictionary<byte[], byte[]> attributes) #endif { oprot_.WriteMessageBegin(new TMessage("checkAndPut", TMessageType.Call, seqid_)); checkAndPut_args args = new checkAndPut_args(); args.TableName = tableName; args.Row = row; args.Column = column; args.Value = value; args.Mput = mput; args.Attributes = attributes; args.Write(oprot_); oprot_.WriteMessageEnd(); #if SILVERLIGHT return oprot_.Transport.BeginFlush(callback, state); #else oprot_.Transport.Flush(); #endif }
public IAsyncResult send_checkAndPut(AsyncCallback callback, object state, byte[] tableName, byte[] row, byte[] column, byte[] value, Mutation mput, Dictionary<byte[], byte[]> attributes)
public async Task MoveToRedemption(IList<OutboundTransaction> transactions, ByteString btcTransaction) { List<Record> records = new List<Record>(); foreach (OutboundTransaction transaction in transactions) { // TODO: Allow double spending records.Add(new Record( key: Encode($"/asset/{assetName}/tx/:DATA:{transaction.Version.ToString()}"), value: Encode(JObject.FromObject(new { transactions = new[] { btcTransaction.ToString() } }).ToString()), version: ByteString.Empty)); records.Add(new Record( key: transaction.RecordKey, value: ByteString.Empty, version: transaction.Version)); } HttpClient client = new HttpClient(); ByteString finalKey = Encode($"/asset/{assetName}/final/:ACC:/asset/{assetName}/"); HttpResponseMessage getValueResponse = await client.GetAsync(new Uri(openChainUri, $"record?key={finalKey.ToString()}")); string stringResponse = await getValueResponse.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); ByteString finalVersion = ByteString.Parse((string)JObject.Parse(stringResponse)["version"]); long currentValue = ParseInt(ByteString.Parse((string)JObject.Parse(stringResponse)["value"])); records.Add(new Record( key: finalKey, value: Encode(currentValue + transactions.Sum(transaction => transaction.Amount)), version: finalVersion)); Mutation mutation = new Mutation(Encode(this.openChainUri.ToString()), records, ByteString.Empty); byte[] serializedMutation = MessageSerializer.SerializeMutation(mutation); await SignAndSubmit(serializedMutation); }
private async Task TransfertInternal(string from, string to, long amount, string asset) { var lAsset = LedgerPath.Parse(asset); var aFrom = new AccountKey(LedgerPath.Parse(from), lAsset); var aTo = new AccountKey(LedgerPath.Parse(to), lAsset); var accounts = await Engine.GetAccounts(new[] { aFrom, aTo }); var adFrom = accounts[aFrom]; var adTo = accounts[aTo]; var rFrom = new Record(aFrom.Key.ToBinary(), LongToByteString(adFrom.Balance - amount), adFrom.Version); var rTo = new Record(aTo.Key.ToBinary(), LongToByteString(adTo.Balance + amount), adTo.Version); Mutation m = new Mutation(ByteString.Empty, new[] { rFrom, rTo }, ByteString.Empty); int c = System.Threading.Interlocked.Increment(ref gcounter); Transaction t = new Transaction( new ByteString(MessageSerializer.SerializeMutation(m)), DateTime.UtcNow, new ByteString(BitConverter.GetBytes(c)) ); await Engine.AddTransactions(new[] { new ByteString(MessageSerializer.SerializeTransaction(t)) }); //Output.WriteLine($"{prefix} - {from} ==> {to} Success Retry : {tryCount}"); }
//Analyze Background Worker start. use Backgroun Worker to keep UI active while analizing. private void analyzeBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { hadError = false; _mutationList = new List<Mutation>(); int i = 1; foreach (string[] s in _mutationsDetailsList) { string chrom = s[(int)XlsMinPlace.Chrom]; int position = Convert.ToInt32(s[(int)XlsMinPlace.Position]); string geneName = s[(int)XlsMinPlace.GeneName]; char refNuc = s[(int)XlsMinPlace.Ref][0]; char varNuc = s[(int)XlsMinPlace.Var][0]; try { Mutation tempMutation = MainBL.getMutationByDetails(chrom, position, refNuc, varNuc); if (tempMutation == null) { tempMutation = new Mutation(chrom, position, geneName, refNuc, varNuc); } tempMutation.NumOfShows = Convert.ToInt16(s[(int)XlsMinPlace.NumOfShows]); _mutationList.Add(tempMutation); //_analyzeBackgroundWorker.ReportProgress(_mainForm.progressBarCounter); _analyzeBackgroundWorker.ReportProgress(i); i++; } catch (Exception) { hadError = true; GeneralMethods.showErrorMessageBox("Something Went Wrong, Please try Again"); break; } } }
private async Task<ByteString> AddTransaction(params Record[] records) { Mutation mutation = new Mutation(ByteString.Parse("0123"), records, ByteString.Parse("4567")); ByteString serializedMutation = new ByteString(MessageSerializer.SerializeMutation(mutation)); Transaction transaction = new Transaction( serializedMutation, new DateTime(1, 2, 3, 4, 5, 6), ByteString.Parse("abcdef")); await this.Store.AddTransactions(new[] { new ByteString(MessageSerializer.SerializeTransaction(transaction)) }); return new ByteString(MessageSerializer.ComputeHash(serializedMutation.ToByteArray())); }
private async Task<byte[]> CreateTransaction(InboundTransaction transaction) { List<Record> records = new List<Record>(); string issuanceAccount = $"/asset/{assetName}/in/{transaction.TransactionHash}/{transaction.OutputIndex}/"; string asset = $"/asset/{assetName}/"; string toAddress = transaction.Address; HttpClient client = new HttpClient(); ByteString issuanceKey = Encode($"{issuanceAccount}:ACC:{asset}"); HttpResponseMessage getValueResponse = await client.GetAsync(new Uri(openChainUri, $"record?key={issuanceKey.ToString()}")); string stringResponse = await getValueResponse.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); ByteString issuanceVersion = ByteString.Parse((string)JObject.Parse(stringResponse)["version"]); // The transaction has already been submitted if (issuanceVersion.Value.Count != 0) return null; ByteString key = Encode($"{toAddress}:ACC:{asset}"); getValueResponse = await client.GetAsync(new Uri(openChainUri, $"record?key={key.ToString()}")); JObject toAccount = JObject.Parse(await getValueResponse.EnsureSuccessStatusCode().Content.ReadAsStringAsync()); ByteString version = ByteString.Parse((string)toAccount["version"]); long currentToBalance = ParseInt(ByteString.Parse((string)toAccount["value"])); records.Add(new Record( key: issuanceKey, value: new ByteString(BitConverter.GetBytes(-transaction.Amount).Reverse().ToArray()), version: ByteString.Empty)); records.Add(new Record( key: key, value: new ByteString(BitConverter.GetBytes(currentToBalance + transaction.Amount).Reverse().ToArray()), version: version)); Mutation mutation = new Mutation( Encode(this.openChainUri.ToString()), records, ByteString.Empty); return MessageSerializer.SerializeMutation(mutation); }
/// <summary> /// A convenience function which commits a mutation to datastore. /// Use this function to avoid a lot of boilerplate. /// </summary> /// <param name="mutation">The change to make to datastore.</param> /// <returns>The result of commiting the change.</returns> // [START commitmutation] private CommitResponse CommitMutation(Mutation mutation) { var commitRequest = new CommitRequest() { Mode = "NON_TRANSACTIONAL", Mutation = mutation }; return _datastore.Datasets.Commit(commitRequest, _projectId) .Execute(); }
private ByteString AddRecord(string key) { Mutation mutation = new Mutation( ByteString.Empty, new Record[] { new Record(new ByteString(Encoding.UTF8.GetBytes(key)), ByteString.Empty, ByteString.Empty) }, ByteString.Empty); Transaction transaction = new Transaction( new ByteString(MessageSerializer.SerializeMutation(mutation)), new DateTime(), ByteString.Empty); this.transactions.Add(new ByteString(MessageSerializer.SerializeTransaction(transaction))); return new ByteString(MessageSerializer.ComputeHash(MessageSerializer.SerializeTransaction(transaction))); }
private ByteString CreateTransaction(params string[] keys) { Mutation mutation = new Mutation( ByteString.Empty, keys.Select(key => new Record( new ByteString(Encoding.UTF8.GetBytes(key)), ByteString.Parse("ab"), ByteString.Parse("cd"))), ByteString.Empty); byte[] serializedMutation = MessageSerializer.SerializeMutation(mutation); Transaction transaction = new Transaction( new ByteString(MessageSerializer.SerializeMutation(mutation)), new DateTime(), ByteString.Empty); return new ByteString(MessageSerializer.SerializeTransaction(transaction)); }
private string GetPayingAddress(Mutation outgoingTransaction) { try { string metadata = Encoding.UTF8.GetString(outgoingTransaction.Metadata.ToByteArray(), 0, outgoingTransaction.Metadata.Value.Count); JObject root = JObject.Parse(metadata); return BitcoinAddress.Create((string)root["routing"], network).ToString(); } catch (JsonReaderException) { return null; } catch (FormatException) { return null; } }
private ByteString CreateMutation(string @namespace) { Mutation mutation = new Mutation( new ByteString(Encoding.UTF8.GetBytes(@namespace)), new Record[] { new Record( new AccountKey(LedgerPath.Parse("/account/1/"), LedgerPath.Parse("/a/")).Key.ToBinary(), new ByteString(BitConverter.GetBytes(100L).Reverse()), ByteString.Empty), new Record( new AccountKey(LedgerPath.Parse("/account/2/"), LedgerPath.Parse("/a/")).Key.ToBinary(), new ByteString(BitConverter.GetBytes(100L).Reverse()), ByteString.Empty), }, ByteString.Empty); return new ByteString(MessageSerializer.SerializeMutation(mutation)); }
public IAsyncResult Begin_checkAndPut(AsyncCallback callback, object state, byte[] tableName, byte[] row, byte[] column, byte[] value, Mutation mput, Dictionary<byte[], byte[]> attributes) { return send_checkAndPut(callback, state, tableName, row, column, value, mput, attributes); }
public void Read (TProtocol iprot) { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.String) { Row = iprot.ReadBinary(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.List) { { Mutations = new List<Mutation>(); TList _list0 = iprot.ReadListBegin(); for( int _i1 = 0; _i1 < _list0.Count; ++_i1) { Mutation _elem2 = new Mutation(); _elem2 = new Mutation(); _elem2.Read(iprot); Mutations.Add(_elem2); } iprot.ReadListEnd(); } } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); }
protected virtual Task AddTransaction(long transactionId, byte[] transactionHash, Mutation mutation) { return Task.FromResult(0); }
private async Task<ByteString> AddRecords(ByteString version, ByteString value, params string[] keys) { Mutation mutation = new Mutation( ByteString.Empty, keys.Select(key => new Record( new ByteString(Encoding.UTF8.GetBytes(key)), value, version)), ByteString.Empty); byte[] serializedMutation = MessageSerializer.SerializeMutation(mutation); Transaction transaction = new Transaction( new ByteString(MessageSerializer.SerializeMutation(mutation)), new DateTime(), ByteString.Empty); await Engine.AddTransactions(new[] { new ByteString(MessageSerializer.SerializeTransaction(transaction)) }); return new ByteString(MessageSerializer.ComputeHash(serializedMutation)); }
private async Task UpdateAccounts(Mutation mutation, byte[] transactionHash) { foreach (Record record in mutation.Records) { if (record.Value == null) { // Read the record and make sure it corresponds to the one supplied IReadOnlyList<byte[]> versions = await ExecuteAsync(@" SELECT Version FROM Records WHERE Key = @key", reader => (byte[])reader.GetValue(0), new Dictionary<string, object>() { ["@key"] = record.Key.ToByteArray() }); if (versions.Count == 0) { if (!record.Version.Equals(ByteString.Empty)) throw new ConcurrentMutationException(record); } else { if (!new ByteString(versions[0]).Equals(record.Version)) throw new ConcurrentMutationException(record); } } else { if (!record.Version.Equals(ByteString.Empty)) { // Update existing account int count = await ExecuteAsync(@" UPDATE Records SET Value = @value, Version = @version WHERE Key = @key AND Version = @currentVersion", new Dictionary<string, object>() { ["@key"] = record.Key.ToByteArray(), ["@value"] = record.Value.ToByteArray(), ["@version"] = transactionHash, ["@currentVersion"] = record.Version.ToByteArray() }); if (count == 0) throw new ConcurrentMutationException(record); } else { // Create a new record try { await ExecuteAsync(@" INSERT INTO Records (Key, Value, Version) VALUES (@key, @value, @version)", new Dictionary<string, object>() { ["@key"] = record.Key.ToByteArray(), ["@value"] = record.Value.ToByteArray(), ["@version"] = transactionHash }); } catch (SqliteException exception) when (exception.Message.Contains("UNIQUE constraint failed: Records.Key")) { throw new ConcurrentMutationException(record); } } } } }