Scoped properties for Application Insights - asp.net-core

I would like to know if there is an elegant way to add scoped properties to Application Insights, something similar to Serilog:
var yearEnricher = new PropertyEnricher("Year", year);
using (LogContext.PushProperties(yearEnricher))
{
// ...
}
In the previous example every log created within the using block will have the property Year stamped on it.
I figured out how to do this when I want the property to be present within the whole request pipeline:
var requestTelemetry = context.Features.Get<RequestTelemetry>();
requestTelemetry?.Properties.Add(propertyName, propertyValue.ToString());
Sometimes I want to create a logging scope in code that is not related to the web context so it doesn't make sense to rely on the IHttpContextAccessor. I acknowledge I could leverage OperationTelemetry and TelemetryClient.StartOperation to achieve my goal but it is cumbersome as I've to implement a few properties in which I've no interest (such as Name, Success, Duration...).
Is there a better way than relying on OperationTelemetry?

If you don't want to use OperationTelemetry, you might want to look into implementing your own ITelemetryInitializer (see documentation here).
It should be fairly easy to implement a stack-like global structure to hold the properties you want to push, and pop the stack on your Dispose method.
Note that you'll probably need to utilize CallContext in order for your stacks to be thread safe.

Related

How to read the result of Flow in Android Compose #Composable function for non-GUI consumption (e.g. for writing in repository)

I am introducing DataStore in my Android Compose app for storing user preferences. While I am not happy about keeping the DataStore instance as a attribute of Context instance - because the Context is accessible from the #Composable only (and not in, e.g. repository) - I am still going for it.
Lets assume (following the references tutorial), that getEmail is the function that reads the DataStore key-value pair and that returns the Flow instance.
My intention is to put the following (approxiamte) code into one of my top-level #Composable, which has AppContainer as an argument - such composables are very top level:
var email = getEmail.collectAsState("") //or should I use single()?
appContainer.salesOrderRespository.setEmail(email)
But I am afraid to do this in this very crude way in which I have wrote this above. E.g. I am concerned about the following things:
should I put this code in some scope (because its collectAsState can block the GUI thread), like:
val scope = rememberCoroutineScope()
scope.launch {
var email = getEmail.collectAsState("") //or should I use single()?
appContainer.salesOrderRespository.setEmail(email)
}
Can I use construction var email = getEmail.collectAsState("") - email can not be accessible immediately, it is assigned asynchronously. That is why I may need something like this (just imagination):
getEmail.collectAsState("").onReadingDone( it - > { appContainer.salesOrderRespository.setEmail(it) })
And, of course, I am eager to execute this code as early as possible. Almost of my repositories are in need of configuration data and if application is starting and going ahead while still reading the configuration data from the DataStore, then the app will not work as expected.
So - I am trying to to just one thing - read DataStore (1. as attribute of the Context, because there is no other proper global instance to whom I can create such attribute; 2. inside #Composable, because Context can be accessed from the #Composable only) and assigne the read value to the attributes of one or more repositories. But I observed that this operation is very complex and involved many concerns. I listed them. That is my question is quite long and complex, but it effectively tries to tackle one simple thing only - reading+assigning.
You don't have to use the Context helper. Instead, I would look into integrating Hilt and injecting your data store into your repository.
Here is a blog about the technique.
https://medium.com/androiddevelopers/datastore-and-dependency-injection-ea32b95704e3

How to organize endpoints when using FeathersJS's seemingly restrictive api methods?

I'm trying to figure out if FeathersJS suits my needs. I have looked at several examples and use cases. FeathersJS uses a set of request methods : find, get, create, update, patch and delete. No other methods let alone custom methods can be implemented and used, as confirmed on this other SO post..
Let's imagine this application where users can save their app settings. Careless of following method conventions, I would create an endpoint describing the action that is performed by the user. In this case, we could have, for instance: /saveSettings. Knowing there won't be any setting-finding, -creation, -updating (only some -patching) or -deleting. I might also need a /getSettings route.
My question is: can every action be reduced down to these request methods? To me, these actions are strongly bound to a specific collection/model. Sometimes, we need to create actions that are not bound to a single collection and could potentially interact with more than one collection/model.
For this example, I'm guessing it would be translated in FeathersJS with a service named Setting which would hold two methods: get() and a patch().
If that is the correct approach, it looks to me as if this solution is more server-oriented than client-oriented in the sense that we have to know, client-side, what underlying collection is going to get changed or affected. It feels like we are losing some level of freedom by not having some kind of routing between endpoints and services (like we have in vanilla ExpressJS).
Here's another example: I have a game character that can skill-up. When the user decides to skill-up a particular skill, a request is sent to the server. This endpoint can look like POST: /skillUp What would it be in FeathersJS? by implementing SkillUpService#create?
I hope you get the issue I'm trying to highlight here. Do you have some ideas to share or recommendations on how to organize the API in this particular framework?
I'm not an expert of featherJs, but if you build your database and models with a good logic,
these methods are all you need :
for the settings example, saveSettings corresponds to setting.patch({options}) so to the route settings/:id?options (method PATCH) since the user already has some default settings (created whith the user). getSetting would correspond to setting.find(query)
To create the user AND the settings, I guess you have a method to call setting.create({defaultOptions}) when the user CREATE route is called. This would be the right way.
for the skillUp route, depends on the conception of your database, but I guess it would be something like a table that gives you the level/skills/character, so you need a service for this specific table and to call skillLevel.patch({character, level})
In addition to the correct answer that #gui3 has already given, it is probably worth pointing out that Feathers is intentionally restricting in order to help you create RESTful APIs which focus on resources (data) and a known set of methods you can execute on them.
Aside from the answer you linked, this is also explained in more detail in the FAQ and an introduction to REST API design and why Feathers does what it does can be found in this article: Design patterns for modern web APIs. These are best practises that helped scale the internet (specifically the HTTP protocol) to what it is today and can work really well for creating APIs. If you still want to use the routes you are suggesting (which a not RESTful) then Feathers is not the right tool for the job.
One strategy you may want to consider is using a request parameter in a POST body such as { "action": "type" } and use a switch statement to conditionally perform the desired action. An example of this strategy is discussed in this tutorial.

Serve a seaside page/component without creating a session

We have a Seaside Application in place that creates a session and handles user login etc. So we're happy with that.
But we'd like to have the ability to serve a few pages using a fixed url. This is not a problem using #initialRequest: and delegating to a certain component depending on the url. What I'd like to avoid, however, is that some of these pages create a new session and start up all the machinery that's coming with it.
Any ideas?
Seaside 2
You could create a WASession (or WAMain) subclass which will be used if the request was static. Then in that session (or main) you could override those methods that do too much for your liking.
Seaside 3
You could use the new filter mechanism. If I recall correctly you can take control of the request pretty much at any time. That should give you enough leverage to do what you want.
Or if you don't need session state, just subclass WARequestHandler and register an instance somewhere in your handler tree (presumably in a WADispatcher).
There's some messiness currently if you want to use a Canvas for rendering but there should be some examples in the image.

Is it possible to use Bukkit for Minecraft to define a new kind of mob?

I'd like to write a Minecraft mod which adds a new type of mob. Is that possible? I see that, in Bukkit, EntityType is a predefined enum, which leads me to believe there may not be a way to add a new type of entity. I'm hoping that's wrong.
Yes, you can!
I'd direct you to some tutorials on the Bukkit forums. Specifically:
Creating a Meteor Entity
Modifying the Behavior of a Mob or Entity
Disclaimer: the first is written by me.
You cannot truly add an entirely new mob just via Bukkit. You'd have to use Spout to give it a different skin. However, in the case you simply want a mob, and are content with sharing a skin of another entity, then it can be done.
The idea is injecting the EntityType values via Java's Reflection API. It would look something like this:
public static void load() {
try {
Method a = EntityTypes.class.getDeclaredMethod("a", Class.class, String.class, int.class);
a.setAccessible(true);
a.invoke(a, YourEntityClass.class, "Your identifier, can be anything", id_map);
} catch (Exception e) {
//Insert handling code here
}
}
I think the above is fairly straightforward. We get a handle to the private method, make it public, and invoke its registration method.id_map contains the entity id to map your entity to. 12 is that of a fireball. The mapping can be found in EntityType.class. Note that these ids should not be confused with their packet designations. The two are completely different.
Lastly, you actually need to spawn your entity. MC will continue spawning the default entity, since we haven't removed it from the map. But its just a matter of calling the net.minecraft.server.spawnEntity(your_entity, SpawnReason.CUSTOM).
If you need a skin, I suggest you look into SpoutPlugin. It does require running the Spout client to join to such a server, but the possibilities at that point are literally infinite.
It would only be possible with client-side mods as well, sadly. You could look into Spout, (http://www.spout.org/) which is a client mod which provides an API for server-side plugins to do more on the client, but without doing something client side, this is impossible.
It's not possible to add new entities, but it is possible to edit entity behaviors for example one time, I made it so that you could tame iron golems and they followed you around.
Also you can sort of achieve custom looking human entities by accessing player entities and tweaking network packets
It's expensive as you need to create a player account to achieve this that then gets used to act as a mob. You then spawn a named entity and give it the same behaviour AI as you would with an existing mob. Keep in mind however you will need to write the AI yourself (you could borrow code straight from craftbukkit/bukkit) and you will need to push the movement and events of this mob to players within sight .. As technically speaking all your doing is pushing packets to the client from the serve on what's actually happening but if your outside that push list nothing will happen as other players will see you being knocked around by invisible something :) it's a bit of a mental leap :)
I'm using this concept to create Npc that act as friendly and factional armies. I've also used mobs themselves as friendly entities (if you belong to a dark faction)
I'd like to personally see future server API that can push model instructions to the client for server specific cache as well as the ability to tell a client where to download mob skins ..
It's doable today but I'd have to create a plugin for the client to achieve this which is then back to a game of annoyance especially when mojang push out a new release and all the plugins take forever to rise with its tide
In all honesty this entire ecosystem could be managed more strategically but right now I think it's just really ad hoc product management (speaking as a former product manager of .net I'd love to work on this strategy it would be such a fun gig)

Unloading a data reference in Entity Framework

Currently I am struggling with a Entity Framework issue. I have a wcf service that sits on top of the ef framework, and allows queries to the framework. At some point the user is able to request a file from the framework. The files are referenced by solution entries, so when you request a file from a solution, the reference is loaded to gain access to the file store.
That all works fine, but from that point onward, whenever you do another query that returns that solution entry, the whole file gets attached to the return result. I need some way of detaching or unloading the reference, such that the result entries will only contain an unloaded reference to the file store again.
I have tried to create a new context and query that context to retrieve information from, but when I do that, the entity in the original context is also changed.
I have tried to detach the entity from the original context and then query from the new context. That does not work either.
I have found one way of doing this. For all the non file-download queries, I detach the result entity, and send that over the wire. I am not sure if that is the best way to go about it though.
I hope someone might be able to provide some insight, thanks for the effort.
The issue you are experiencing is probably do to Change Tracking, which is on by default.
Possible Solution:
Disable Change Tracking with MergeOption.NoTracking
using (MyEntities _context = new MyEntities())
{
_context.Widgets.MergeOption = MergeOption.NoTracking;
return _context.Widgets.ToList();
}
This article may help to point you in the right direction on how to handle this issue if the solution above does not work.
I struggled with a similar issue recently. The problem was the result of the context maintaining a reference to the object I was using (obviously). Every time I made a change to an object of the same type, even when obtained with a new context (so I thought), the object was being changed.
With help from one of my peers, we determined the context was hanging around due to the way I was registering it with my IoC container (lifestyle per web request). When I changed the lifestyle to transient (which definitively provided a new instance) then changes to objects of the same type were unaffected.
Hope this helps.