EventStore only showing hexadecimal string in Payload column - neventstore

As far as I can tell I should have JSON showing in Payload column in my SQL database Commits table, however I have a long hexadecimal string.
My wireup code is as per the sample with the following edits:
private static IStoreEvents WireupEventStore()
{
return Wireup.Init()
.LogToOutputWindow()
.UsingInMemoryPersistence()
.UsingSqlPersistence("EventStore") // Connection string is in app.config
.WithDialect(new MsSqlDialect())
.EnlistInAmbientTransaction() // two-phase commit
.InitializeStorageEngine()
.UsingJsonSerialization()
.HookIntoPipelineUsing(new[] { new AuthorizationPipelineHook() })
.UsingSynchronousDispatchScheduler()
.DispatchTo(new DelegateMessageDispatcher(DispatchCommit))
.Build();
}
Any idea how to get JSON and make debugging easier?

Just create the following view:
CREATE VIEW [dbo].[DeserializedCommits]
AS
SELECT
[StreamId]
,[StreamRevision]
,[Items]
,[CommitId]
,[CommitSequence]
,[CommitStamp]
,[Dispatched]
,CAST([Headers] AS VARCHAR(MAX)) AS [Headers]
,CAST([Payload] AS VARCHAR(MAX)) AS [Payload]
FROM [dbo].[Commits]
You can than query your event store for specific events using LIKE on Payload column.

A query similar to this one will get you the string content of the Payload column:
Commits
.Select(c => System.Text.Encoding.UTF8.GetString(c.Payload.ToArray()))
.ToList();

Related

AWS Java SDK DynamoDB, how to get attribute values from ExecuteStatementRequest response?

I'm using Java AWS SDK to query a DynamoDB table using ExecuteStatementRequest, but I'm don't know how to fetch the returned attribute values from the response.
Given I have the following query:
var response2 = client.executeStatement(ExecuteStatementRequest.builder()
.statement("""
UPDATE "my-table"
SET thresholdValue= thresholdValue + 12.5
WHERE assignmentId='item1#123#item2#456#item3#789'
RETURNING ALL NEW *
""")
.build());
System.out.println(response2.toString());
System.out.println(response2.getValueForField("Items", Collections.class)); // Doesn't cast to
This query executes fine and returns as part of the response attributes, however I can't find a way to get these values out of the response object using Java.
How can I do that?
I have found how to do that, however I'm not sure it this is the indicated way as the documentation doesn't provide any examples.
List items = response2.getValueForField("Items", List.class).get();
for (Object item : items) {
var values = (Map<String, AttributeValue>) item;
System.out.println(values.get("assignmentId").s());
System.out.println(values.get("thresholdValue").n());
}

Concurrent insert in SQL Server 2012

I have written an api in ASP.NET which uses Entity Framework 6.
Here is the code
cr = context.Responses.FirstOrDefault(s => s.RegistrationId ==registrationId);
if (cr == null)
{
cr = new Responses()
{
Answer = answer,
RegistrationId = registrationId,
CreationTime = DateTime.Now
};
context.Responses.Add(cr);
}
else
{
cr.Answer = answer;
}
context.SaveChanges();
This is my result in database
But while doing the database inserts, it inserts the same data twice with same creation time which happens often. Why is this so? What is the best way to avoid these duplicate inserts?
first of all it should be
cr = context.Responses.FirstOrDefault(s => s.RegistrationId == registrationId );
This is possible this error originates from the UI. suppose you are filling out responses by form, and somebody presses the submit twice, then you would have two lines in the db representing the same response. The correct way to resolve this is to have the form (via javascript and such) generate the guid, and immediately disable the submit button after the click. Another way is to declare in the database that the combinations of result columns are unique, thus no two "same" lines can exist by defintion.

How to update nested object of firebase data in (angularfire2 / Ionic), and also i want to update with given value not with key

I was integrate firebase with ionic3 angularjs, adding data successfully like
var fireData =
{
userid : '1122233',
questionId : '18022',
answerId : '25633',
points : '2'
}
//Add
this.sample.list('paperCode').push(fireData);
Now I want to update like below mentioned image
If you don't know the key, first query the data with the field you know then iterate through the result and get the key. Then you can perform update.
Try
updateFunction(questionId){
this.sample.list('/paperCode', ref => ref.orderByChild('questionId').equalTo(questionId)).snapshotChanges()
.subscribe(actions => {
actions.forEach(action => {
// here you get the key
console.log(action.key);
this.sample.list('/paperCode').update(action.key, { points: 10 });
});
});
}
I hope your question id is unique, otherwise it will override all queried results.
You need to set a path to that object and update the field you would like. In this example...
firebase.database().ref(1710172911409/L5F4BEuePS8qxUqDNoF/questionId).update("NEWQUESTIONID);
If you don't know the unique id of the pushed object, you can query for it. Learn more here

How to use startAt() in Firebase query?

Let's suppose above firebase database schema.
What I want to is retrieve messages which after "15039996197" timestamp. Each of message object has a createdAt property.
How can I get messages only after specific timestamp? In this case, last two messages are what I want to retrieve.
I tried firebaseb.database().ref(`/rooms/$roomKey/messages`).startAt('15039996197') but failed. It return 0. How can I do this?
The case with your query is that it's expecting that the message node should have a number value to start with, in that case you want a child node with the name createdAt. So in that case you must specify that you want to order by createdAt, thus you need to do this
firebase.database().ref(`/rooms/$roomKey/messages`).orderByChild('createdAt').startAt('15039996197').on(//code);
This way it'll return all nodes inside message that has a child named createdAt an it starts at 15039996197. Ordering your query may be a little bad for performance, for that i sugest taking a look at .indexOn rule.
For more information take a look here.
Hope this helps.
Firebase Data Retrieval works node by node.
So whatever data you want to get, the entire node is traversed.
So in your case to get any message your complexity would be O(number of messages).
You would want to restructure the way you are storing the data and put createdAt in Node instead of Child.
If your database structure looks like that, you can use:
firebase.database()
.ref(`/rooms/$roomKey/messages`)
.orderByChild('createdAt')
.startAt('15039996197').on('value', snapshot => { /* your code here */ });
But if you work with a lot of data entries, you can also name the item key with the timestamp, instead of storing the timestamp in your data. This saves a little data on your database.
firebase.database().ref(`${rooms}/${roomKey}/${timestamp}`).set("value");
To retrieve the data in that case instead of orderByChild('createdAt'), you'll use orderByKey(). Because firebase keys are of the string type, you need to make shure to parse the timestamp in the .startAt() to a string.
It will then look something like this:
firebase.database()
.ref(`/rooms/$roomKey/messages`)
.orderByKey()
.startAt(`${15039996197}`).on('value', snapshot => { /* your code here */ });
You can do something like that:
firebase.database().ref('/rooms/$roomKey/messages')
.orderByChild('createdAt')
.startAt('150399')
.endAt('1503999\uf8ff')
.on('value', function (snapshot) {
var key = snapshot.key,
data = snapshot.val();
console.log(key + ': ' + JSON.stringify(data))
});
Be sure to set endAt().

Cannot update a timestamp column after .Attach

I have this ASP.Net code and I was getting an error when running it. The error was:
Server: Msg 272, Level 16, State 1, Line 1 Cannot update a timestamp
column.
Here's the mapping for this table that I already have:
Property(x =>
x.Version).HasColumnName(#"Version").IsOptional().HasColumnType("timestamp").HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Computed);
Note that I do have a version column in my table.
public async Task<IHttpActionResult> Put([FromBody]WordForm wordForm)
{
// SampleSentences -> s
var oldsObj = db.SampleSentences
.Where(w => w.WordFormId == wordForm.WordFormId)
.AsNoTracking()
.ToList();
var newsObj = wordForm.SampleSentences.ToList();
// There is other code here to modify SampleSentences
//
//
// db.WordForms.Attach(wordForm);
// db.Entry(wordForm).State = EntityState.Modified;
wordForm.StatusId = (int)EStatus.Saved;
await db.SaveChangesAsync(User, DateTime.UtcNow);
return Ok(wordForm);
}
I was able to fix the error by adding comments to the two lines in the method. But could someone explain why I am getting the error if I don't comment out those lines. Should I not be able to Attach the wordForm and mark as Modified?
Your table probably has a rowversion or timestamp field which is used for optimistic concurrency. rowversion fields can't be set or updated at all. They are a value that gets incremented automatically each time a row is modified.
To avoid the problem, mark your rowversion property with the TimeStamp attribute:
[TimeStamp]
public byte[] RowVersion { get; set; }
In fact, timestamp is the deprecated name of the type which causes a bit of confusion
From the docs:
The timestamp syntax is deprecated. This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

Resources