Merging json text into single dto - servicestack

is there a mechanism in servicestack.text to merge two json strings into a single dto?
The use case is merging complex settings from multiple sources into a single settings file
i.e.
{ "blah": { "params": { "default": "bar", "misc": "0", } } }
and
{ "blah": { "params": { "value": "val", "misc": "1", } } }
becomes
{ "blah": { "params": { "default": "bar", "value": "val", "misc": "1", } } }
Thanks

Be careful of the trailing comma's as it's not valid JSON. But you can use the dynamic API of ServiceStack's JSON Serializer to do this:
var json1 = "{\"blah\":{\"params\":{\"default\":\"bar\", \"misc\": \"0\" } } }";
var json2 = "{\"blah\":{\"params\":{\"value\":\"val\", \"misc\": \"1\" } } }";
var jsonObj = JsonObject.Parse(json1);
var jsonParams =jsonObj.Object("blah").Object("params");
foreach (var entry in JsonObject.Parse(json2).Object("blah").Object("params"))
{
jsonParams[entry.Key] = entry.Value;
}
var to = new { blah = new { #params = jsonParams } };
to.ToJson().Print();
Which will output:
{"blah":{"params":{"default":"bar","misc":"1","value":"val"}}}

Well, if you don't ever going to use JsonArrays, solution above could be written in recursive way:
public static JsonObject Merge(JsonObject #this, JsonObject that) {
foreach (var entry in that) {
var exists = #this.ContainsKey (entry.Key);
if (exists) {
var otherThis = JsonObject.Parse(#this.GetUnescaped (entry.Key));
var otherThat = JsonObject.Parse(that.GetUnescaped (entry.Key));
#this [entry.Key] = Merge (otherThis, otherThat).ToJson ();
} else {
#this [entry.Key] = entry.Value;
}
}
return #this;
}

Related

writefilesync not writing all variables to a json file

I have this code:
circular = () => { //fix circular stuff for json.stringify
seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
var gameon = 1;
var fighter1 = {"userid":"97","username":"john","items":{},"ailments":{}};
var fighter2 = {"userid":"91","username":"james","items":{},"ailments":{}};
var resume = 30;
all = {gameon:gameon,fighter1:fighter1,fighter2:fighter2,resume:resume,inturn:fighter1,outturn:fighter2};
fs.writeFileSync(file,JSON.stringify(all,circular()),{encoding:'utf8',flag:'w'});
I expect to have the next output written to file:
{
"gameon":1,
"fighter1":{
"userid":"97",
"username":"john",
"items": {},
"ailments":{}
},
"fighter2":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
},
"resume":"",
"inturn":{
"userid":"97",
"username":"john",
"items":{},
"ailments":{}
},
"outturn":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
}
but this is what I get instead:
{
"gameon":1,
"fighter1":{
"userid":"97",
"username":"john",
"items":{},
"ailments":{}
},
"fighter2":{
"userid":"91",
"username":"james",
"items":{},
"ailments":{}
},
"resume":""
}
Please notice how the string truncates after "resume" like it couldn't read the variables fighter1 and fighter2 despite it could do it for the first iteration.
Why is that?
Thank you.

New-AzEventGridSubscription "The attempt to validate the provided endpoint" failed

I created an endpoint in my C# code at /events path. If the event is of type "Microsoft.EventGrid.SubscriptionValidationEvent", i extract the ValidationCode and return 200 with a json object with validationResponse. I tested this using Postman, and everything appears to work, but when using "New-AzEventGridSubscription", it fails. Any ideas?
Here's the command I used, scrubbed of course.
New-AzEventGridSubscription -ResourceGroup MyResourceGroupName -Endpoint https://requestb.in/19qlscd1/events -EventSubscriptionName EventSubscription1 -TopicName Topic1
Sample Post:
[
{
"id": "531d4a96-d4c7-43d6-8b4c-e1ff9351b869",
"topic": "scrubbed",
"subject": "",
"data": {
"validationCode": "7062AAC0-656D-4C4C-BDD6-0FA673676D95",
"validationUrl": "scrubbed"
},
"eventType": "Microsoft.EventGrid.SubscriptionValidationEvent",
"eventTime": "2020-03-30T17:46:15.1827678Z",
"metadataVersion": "1",
"dataVersion": "2"
}
]
Sample Response:
{
"validationResponse": "7062AAC0-656D-4C4C-BDD6-0FA673676D95"
}
Here is my code to handle the Event. I've tested this using Ngrok, and it appears to work.
private void HandleEvent(IApplicationBuilder app)
{
app.Run(async context =>
{
string content;
using (var reader = new StreamReader(context.Request.Body))
{
content = reader.ReadToEnd();
}
var eventGridEvents = JsonConvert.DeserializeObject<EventGridEvent[]>(content);
foreach (var eventGridEvent in eventGridEvents)
{
if (eventGridEvent.EventType == "Microsoft.EventGrid.SubscriptionValidationEvent")
{
var eventDataJson = JsonConvert.SerializeObject(eventGridEvent.Data);
var eventData = JsonConvert.DeserializeObject<SubscriptionValidationEventData>(eventDataJson);
var responseData = new SubscriptionValidationResponse()
{
ValidationResponse = eventData.ValidationCode
};
context.Response.StatusCode = 200;
await context.Response.WriteAsync(JsonConvert.SerializeObject(responseData));
}
else
{
var deserialized = JsonConvert.DeserializeObject((string)eventGridEvent.Data);
if (typeof(IEnumerable).IsAssignableFrom(deserialized.GetType()))
{
eventGridEvent.Data = (IEnumerable<object>)deserialized;
}
else
{
eventGridEvent.Data = new List<object>() { deserialized };
}
await HandleMessageListAsync(eventGridEvents.ToList());
}
}
context.Response.StatusCode = 200;
await context.Response.WriteAsync(string.Empty);
});
}
Thank you!
Turns out the issue was my API was returned as "Chunked". Microsoft applied a patch to support "Chunked" responses, and now it works. :)

How to get response body using custom middle ware?

problem
How to get response body on invoke next context using custom middle ware ??
After reach to line of await _next.Invoke(context) from debug;
not return json data from action result getusermenu
[HttpGet(Contracts.ApiRoutes.Security.GetUserMenus)]
public IActionResult GetUserMenu(string userId)
{
string strUserMenus = _SecurityService.GetUserMenus(userId);
return Ok(strUserMenus);
}
I need to get response body from action result above
header :
key : Authorization
value : ehhhheeedff .
my code i try it :
public async Task InvokeAsync(HttpContext context, DataContext dataContext)
{
// than you logic to validate token
if (!validKey)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Invalid Token");
}
//if valid than next middleware Invoke
else
{
await _next.Invoke(context);
// i need after that get result on last of thread meaning return data of usermenu
}
}
}
public static class TokenExtensions
{
public static IApplicationBuilder UseTokenAuth(this IApplicationBuilder builder)
{
return builder.UseMiddleware<TokenValidateMiddleware>();
}
}
[no return data from access token][1]
https://i.stack.imgur.com/PHUMs.png
if(validtoken)
{
continue display getusermenuaction and show result
}
when valid token it return data like below on browser googlechrom
[
{
"form_name": "FrmAddPrograms",
"title": "Adding Screens",
"url": "",
"permissions": {
"Insert": "True",
"Edit": "True",
"Read": "True",
"Delete": "True",
"Print": "True",
"Excel": "False",
"RecordList": "False"
}
},
but on my app browser return
not valid token
Try to get response body in custom middleware using below code:
public class CustomMiddleware
{
private readonly RequestDelegate next;
public CustomMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
if (!validKey)
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await context.Response.WriteAsync("Invalid Token");
}
//if valid than next middleware Invoke
else
{
Stream originalBody = context.Response.Body;
try
{
using (var memStream = new MemoryStream())
{
context.Response.Body = memStream;
await next(context);
memStream.Position = 0;
string responseBody = new StreamReader(memStream).ReadToEnd();//get response body here after next.Invoke()
memStream.Position = 0;
await memStream.CopyToAsync(originalBody);
}
}
finally
{
context.Response.Body = originalBody;
}
}
}
}

Turn json value into var

I am trying to format a read item from a DB to a simple var (node.js 6.10).
My ambition is to have a "var Value" which contains the read value (487).
This is the code now:
{
console.log("Success", data.Item);
console.log(JSON.stringify(data, null, 2));
}
This is the output:
Success { Value: { N: '487' } }
{ "Item": { "Value": { "N": "487" } } }
How can I solve this in a better way as stringify didnt work as I hoped?
var Value = data.Item.Value.N
console.log(Value)
// outputs: '487'

Array full of regex, match to string, return path

Still very much a beginner, Just editing to make a little more sense
Here is an example payload.
{
"Status":
{
"result":[
{
"LastUpdate":"2017-09-07 06:47:09",
"Type":"2",
"Value":"' s the inside temperature",
"idx":"4"
}
],
"status":"OK",
"title":"GetUserVariable"
},
"Devices":
{
"28":
{
"rid":"28",
"regex":"(the )?(AC|(Air( )?(Con)?(ditioner)?))( Power)?( )?$/i"
},
"71":
{
"rid":"71",
"regex":"(the )?inside temp/i"
}
}
}
I want to filter the "Devices" array down to entires that match Status.result[0].Value.
I have the follow code working, but it is in working in reverse, it returns the matching string, not the filtered array, just not sure how to reverse it.
var devices = msg.payload.Devices;
var request = [ msg.payload.Status.result[0].Value ];
var matches = request.filter(function (text) {
return devices.some(function (regex) {
var realregex = new RegExp(regex, "i");
return realregex.test(text);
});
});
msg = { topic:"Inputs", payload: { devices:devices, request:request } };
msg2 = { topic:"Output", payload: { matches:matches } };
return [ [ msg, msg2 ] ];
Thanks,
Wob

Resources