Fetch Single Document from Firestore - kotlin

I switched my database data from the Real-time Database to Firestore because I need more defined querying when it comes to my apps that I'm building. However, I'm needing a little bit of help because I'm trying to assign the values to the currentCustomer variable, but instead of putting snapshot.child()..., what do I need to do with document? Thank you!
My Firestore Document
MyUtil.kt
var currentCustomer: Customer? = null
fun fetchCurrentCustomer() {
val uid = FirebaseAuth.getInstance().uid
val ref = FirebaseFirestore.getInstance().collection("/$REF_CUSTOMERS/$uid")
ref.get().addOnSuccessListener { document ->
if (document != null) {
currentCustomer = Customer(
document.documents.,
snapshot.child("fullname").getValue(String::class.java)!!,
snapshot.child("username").getValue(String::class.java)!!,
snapshot.child("email").getValue(String::class.java)!!,
"",
snapshot.child("profileImageUrl").getValue(String::class.java)!!
)
}
}
}

Try this to fetch a single document from firestore collection
val reference = FirebaseFirestore.getInstance()
.collection("REF_CUSTOMERS")
.document($uid)
reference.get().addOnSuccessListener { document ->
if (document != null) {
currentCustomer = document.toObject(Customer::class.java
}
}

Related

Why does the author add key(task) for the items function in LazyColumn?

The Code A is from the offical sample project.
I don't understand why the author need to add key(task) for the items function in LazyColumn, could you tell me?
I think the Code B can work well and it's simple.
Code A
val allTasks = stringArrayResource(R.array.tasks)
val tasks = remember { mutableStateListOf(*allTasks) }
...
items(count = tasks.size) { i ->
val task = tasks.getOrNull(i)
if (task != null) {
key(task) {
TaskRow(
task = task,
onRemove = { tasks.remove(task) }
)
}
}
}
Code B
...
items(tasks) { task ->
TaskRow(
task = task,
onRemove = { tasks.remove(task) }
)
}
Keys in general are used to avoid unnecessary recompositions. If you have a list of items, and some items are reordered, Compose will find existing components in the composition based on their key and reorder them accordingly instead of recomposing all of them.
That said, items() already supports a key parameter. So code A could indeed be simplified this way if the tasks in the list are non-nullable:
items(tasks, key = { it }) { task ->
TaskRow(
task = task,
onRemove = { tasks.remove(task) },
)
}
But code B would use the items' positions instead of the items themselves as key by default, which is not desirable.
Disclaimer: I'm no expert in JetPack Compose

In Ktor how do I get the sessionId within a get() {}?

install(Sessions) {
header<MySession>("MY_SESSION", SessionStorageMemory())
}
get("/session/increment") {
val session = call.sessions.get<MySession>() ?: throw AuthorizationException()
call.sessions.set(session.copy(count = session.count + 1))
// insert code here to get sessionId ?
call.respondText("Counter is ${session.count}. Refresh to increment.")
}
I've been trying to get it out of the attributes but it seems the framework has made all those data structures private to prevent me from getting the sessionId and have no working solution yet.
val attributeKey = call.attributes.allKeys.map{
val x = it as AttributeKey<Any>
call.attributes.get(x)
}
// AttributeKey<SessionData>("SessionKey")
SessionData is private so I can't get access to data structure that holds sessionId

Kotlin: mapNotNull but log what caused null elements

When translating Java to Kotlin code, I encountered the following:
List<Content> getContent(List<Node> nodes, Map<String, Content> content) {
List<Content> result = new ArrayList<>(nodes.size());
for (Node node : nodes) {
Content content = content.get(node.getId());
if (content == null) {
logger.atSevere().log("Content %s was not found", node.getId());
continue;
}
result.add(content);
}
return result;
}
In Kotlin, this can be easily translated if we drop the logger call:
fun getContent(items: List<Node>, content: Map<String, Content): List<Content> {
val contentIds = items.mapNotNull { it.id }
return contentIds.mapNotNull { contentMap[it] }
}
I'm thinking a sequence builder might be nice here. It's also possible to separate out contentIds into two separate collections, one made up of the contentIds that were not present in contentMap, the other made up of the Content mapped to successfully. I bet there is also a better way to get a set of items in a map from a set of keys, but I haven't found the right function.
Please try the following:
fun check(items: List<Node>, content: Map<String, Content?>): List<Content>{
return items.filter{
if (content[it.id] == null){
print("content " + it.id + "was not found")
}
content[it.id] != null
}.map{content[it.id]!!}
}

Wit.ai How to Get an whole sentence in an entity

I would like to store an entire sentence an user said and store it.
This his how I did but I can't get the sentence from A to Z an an whole entity, just few parts knows as "number", "location", ....
merge(request) {
return new Promise(function(resolve, reject) {
var entities = request.entities;
var context = request.context;
var message = request.message;
var sessionId = request.sessionId;
var intent = firstEntityValue(entities, 'intent');
if (intent == "write_free_text") {
context.free_text = request["text"];
}
if (intent == "choose_city") {
var city = firstEntityValue(entities, 'location');
context.city = city;
}
return resolve(context);
});
}
How can I do that and store the whole sentence with merge function ? Thank you
If you want the whole sentence, maybe you don't needs a entity, just get the message sent:
// Merge action
function merge(request) {
context.freetext = request["text"];
return context;
}
Bot: https://wit.ai/Godoy/bottest/stories/4da2840f-513e-42ed-a494-c5516c07242e
Fiddle with code: https://wit-ai.github.io/witty-fiddle/?id=e4c16a624c87d37f9c0c29d8299ca5fc
if you want to get the whole phrase, use the wit/phrase_to_translate built-in entity
a snapshot of the uunderstanding tab
you just have to train the bot, once or twice.
It will pick up all the free text later.

MS Dynamics CRM. Get users who current record shared with

I have a entity record which is shared with or more users. I would like to unshare this record when Deactivate it. I want to do that in Plugin. But I can't understand how to get all users from sharing list who have access to this record. How to do that?
Here is my code snippet:
protected void ExecutePostPersonSetStateDynamicEntity(LocalPluginContext localContext)
{
if (localContext == null)
{
throw new ArgumentNullException("localContext");
}
var context = localContext.PluginExecutionContext;
var targetEntity = (Entity)context.InputParameters["EntityMoniker"];
var state = (OptionSetValue)context.InputParameters["State"];
var columns = new ColumnSet(new[] { "statecode" });
var retrivedEntity = localContext.OrganizationService.Retrieve(targetEntity.LogicalName, targetEntity.Id, columns);
if (state.Value == 1)
{
RevokeAccessRequest revokeRequest = new RevokeAccessRequest()
{
Target = new EntityReference(personEntity.LogicalName, personEntity.Id),
Revokee = new EntityReference(neededEntity.LogicalName, needed.Id)
};
// Execute the request.
}
}
As you can see, I need an entity "neededEntity", I don't know how to get it from "targetEntity" or "retrievedEntity".
You need to use a RetrieveSharedPrincipalsAndAccessRequest
http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.retrievesharedprincipalsandaccessrequest.aspx
You can start from the included example, basically inside the foreach you call your RevokeAcessRequest