Dynamics 365 incidents and contacts deep insert - microsoft-dynamics

I am trying the deep insert for incidents and contacts entities using the OData Web API. When I create these records separately (of course association is needed), there is no issue.
When I tried deep insert it didn't work.
This way of separate insertion has no issue.
JObject contact = new JObject{
{ "firstname", "Yvonne" },
{ "lastname", "McKay (sample)" },
{ "jobtitle", "Coffee Master" },
{ "annualincome", 45000 }
};
Uri contact1Uri = svc.PostCreate("contacts", contact);
JObject incident1 = new JObject
{
{ "title", "Sithu Test case" },
{ "description", "case" },
{ "customerid_contact#odata.bind", "/contacts(7c8742cd-86c4-ec11-a7b5-002248567570)" },
};
Uri incident1Uri = svc.PostCreate("incidents", incident1);
When I tried like following
JObject incident = new JObject{
{ "title","Case 1 for Susanna Stubberod"},
{ "description","Task 1 for Susanna Stubberod description"},
{ "customerid_contact", new JObject{
{ "firstname","Susanna"},
{ "lastname","Stubberod (sample)"},
{ "jobtitle","Senior Purchaser"},
{ "annualincome", 52000},
}
}};
Uri incident1Uri = svc.PostCreate("incidents", incident);
It returned the error:
You should specify a contact or account.
Please help me find the issue.

I suspect the error is a combination of two factors:
Dynamics enforces that all incident records must have a primary account or contact. This is enforced at the application level, I don't believe there is any way around this.
I suspect when performing a deep insert, Dynamics creates the outer object first and then creates the inner, deeper, objects.
This means Dynamics attempts to create the incident first, without a contact, which causes an error. I'm not sure there is anything you can do about this, apart from not doing a deep insert.

Related

GCP Video Intelligence - batchPredict error

Following this documentation, when requesting a batchPredict I run into this error via API
{
"error": {
"code": 13
"message": "internal",
}
}
Additionally, here's a screenshot screenshot of the error I see when I try to use the "Test & Use" tab. Neither of which are descriptive, so I'm not sure where the error lies.
In the request, I include the path to my CSV file in the Google Storage, which links to a video in the same bucket. Here's the contents of the CSV:
gs://XXXXXXXXXXXX/movie1.mov,0,inf
gs://XXXXXXXXXXXX/movie2.mov,0,inf
I also include the path to a /Results folder (in the same bucket) to save the predictions.
Code making the call:
const client = new PredictionServiceClient();
async function batchPredict() {
const request = {
name: client.modelPath('project-id-xxxxxx', 'us-central1', 'VOTxxxxxxxxxx'),
inputConfig: {
gcsSource: {
inputUris: ['gs://XXXXXXXXXXXX/apitest.csv'],
},
},
outputConfig: {
gcsDestination: {
outputUriPrefix: 'gs://XXXXXXXXXXXX/results/',
},
},
};
Please let me know if I need to provide any more detail.
The possible root cause is one of those two:
There is an issue somewhere in your code. So, if your code is not the same as below, I suggest that you try it out (changing the appropriate variables of course).
There is something wrong with your model, which is the most probable root cause (as per the error message itself).
So, if it is not your code, you should create a private issue report on issue-tracker explaining your issue and giving as much details as possible on it as well as your use case and impact.
As it is private, only Googlers and you will have access to it so feel free to share your project and model IDs.
Here is what I did to try to reproduce your issue (be sure to follow the before you begin guide):
I have trained a model on gs://YOUR_BUCKET/TRAINING.csv
TRAIN,gs://automl-video-demo-data/traffic_videos/traffic_videos_train.csv
TEST,gs://automl-video-demo-data/traffic_videos/traffic_videos_test.csv
Predicted on a couple of images on gs://YOUR_BUCKET/VIDEOS_TO_ANNOTATE.csv (inputUri):
gs://automl-video-demo-data/traffic_videos/highway_078.mp4, 0,inf
gs://automl-video-demo-data/traffic_videos/highway_079.mp4,10.00000,15.50000
using the Node.js predict example from the tutorial:
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
const projectId = 'YOUR_PROJECT';
const location = 'us-central1';
const modelId = 'VOTXXXXXXXXXXXXXXXXXX';
const inputUri = 'gs://YOUR_BUCKET/VIDEOS_TO_ANNOTATE.csv';
const outputUri = 'gs://YOUR_BUCKET/outputs/';
// Imports the Google Cloud AutoML library
const {PredictionServiceClient} = require('#google-cloud/automl').v1beta1;
// Instantiates a client
const client = new PredictionServiceClient();
async function batchPredict() {
// Construct request
const request = {
name: client.modelPath(projectId, location, modelId),
inputConfig: {
gcsSource: {
inputUris: [inputUri],
},
},
outputConfig: {
gcsDestination: {
outputUriPrefix: outputUri,
},
},
};
const [operation] = await client.batchPredict(request);
console.log('Waiting for operation to complete...');
// Wait for operation to complete.
const [response] = await operation.promise();
console.log(
`Batch Prediction results saved to Cloud Storage bucket. ${response}`
);
}
batchPredict();
Note that I have also tried the REST & CMD LINE predict example.
And in both cases, it worked well and I received a correct response:
Nodejs prediction's response:
Waiting for operation to complete...
Batch Prediction results saved to Cloud Storage bucket. [object Object]
REST & CMD LINE prediction's response:
{
"name": "projects/XXXXXXXXXX/locations/us-central1/operations/VOTXXXXXXXXXXXXXXX",
"metadata": {
"#type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
"createTime": "2021-04-16T08:09:52.102270Z",
"updateTime": "2021-04-16T08:09:52.102270Z",
"batchPredictDetails": {
"inputConfig": {
"gcsSource": {
"inputUris": [
"gs://MY_BUCKET/VIDEOS_TO_ANNOTATE.csv"
]
}
}
}
}
}

Flutter - Best way to store a List of Objects every time I close the application?

The situation:
I'm very new to Flutter and mobile development, thus I don't know much about Dart; And I've read some solutions from people with similar problems but didn't manage to work these solutions to my own thing.
The problem:
I have a to-do app that has 2 Lists of Objects, and I want to store those Lists for whenever the user re-open the app.
I know its simple stuff but I feel like I'm storming towards this problem due to the lack of experience... And so I decided to come asking for some light.
What I've tried:
I have come across different solutions for this problem and all of them seemed way too complex to this case (compared to what I'm used to do when saving lists to the archive), including: encoding the list to a map and converting to a string before using SharedPreferences, using SQlite database (every tutorial I've come across made me feel like I'd be using a war tank to kill an ant, I'd say the same about firebase).
Structure of the problem:
ToDo screen with a ListView.builder calling 2 arrays: ongoing tasks and done tasks each of which I want to write to the phone whenever the user makes a change. IDK if I should only try to save those arrays from within the class from which they belong by calling some packages methods, or if I should try to store the entire application if such thing is possible.
Conclusion:
Is there a way to solve this in a simple way or I should use something robust like firebase just for that? even though I'm not used to work with firestore, and so I'm in the dark not knowing how to apply such thing to save data.
How my lists are structured:
List<Task> _tasks = [
Task(
name: "do something",
description: "try to do it fast!!!",
),
];
List<Task> _doneTasks = [
Task(
name: "task marked as done",
description: "something",
),
];
2022 Update with null safety
My original code example was more verbose than necessary. Using Darts factory constructor this can be done with way less code. This is also updated for null safety and using Hive instead of GetStorage.
First, add a toMap method which converts the object to a Map, then a fromMap constructor which returns a Task object from a Map that was saved in storage.
class Task {
final String name;
final String description;
Task({required this.name, required this.description});
Map<String, dynamic> toMap() {
return {'name': this.name, 'description': this.description};
}
factory Task.fromMap(Map map) {
return Task(
name: map['name'],
description: map['description'],
);
}
String toString() {
return 'name: $name description: $description';
}
}
Updated Demo Page
class StorageDemo extends StatefulWidget {
#override
_StorageDemoState createState() => _StorageDemoState();
}
class _StorageDemoState extends State<StorageDemo> {
List<Task> _tasks = [];
final box = Hive.box('taskBox');
// separate list for storing maps/ restoreTask function
//populates _tasks from this list on initState
List storageList = [];
void addAndStoreTask(Task task) {
_tasks.add(task);
storageList.add(task.toMap()); // adding temp map to storageList
box.put('tasks', storageList); // adding list of maps to storage
}
void restoreTasks() {
storageList = box.get('tasks') ?? []; // initializing list from storage
// looping through the storage list to parse out Task objects from maps
for (final map in storageList) {
_tasks
.add(Task.fromMap(map)); // adding Tasks back to your normal Task list
}
}
// looping through your list to see whats inside
void printTasks() {
for (final task in _tasks) {
log(task.toString());
}
}
void clearTasks() {
_tasks.clear();
storageList.clear();
box.clear();
}
#override
void initState() {
super.initState();
restoreTasks(); // restore list from storing in initState
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Container(),
),
TextButton(
onPressed: () {
final task =
Task(description: 'test description', name: 'test name');
addAndStoreTask(task);
},
child: Text('Add Task'),
),
TextButton(
onPressed: () {
printTasks();
},
child: Text('Print Storage'),
),
TextButton(
onPressed: () {
clearTasks();
},
child: Text('Clear Tasks'),
),
],
),
);
}
}
Updated Storage Init
void main() async {
await Hive.initFlutter();
await Hive.openBox('taskBox');
runApp(MyApp());
}
Original Answer
So generally speaking, once you want to store anything other than a primitive type ie. String int etc... things get a bit more complex because they have to converted to something that's readable by any storage solution.
So despite Tasks being a basic object with a couple strings, SharedPreferences or anything else doesn't know what a Task is or what to do with it.
I suggest in general reading about json serialization, as you'll need to know about it either way. This is a good place to start and here is another good article about it.
All that being said, it can also be done without json by converting your task to a Map (which is what json serialization does anyway) and storing it to a list of maps. I'll show you an example of doing this manually without json. But again, its in your best interest to buckle down and spend some time learning it.
This example will use Get Storage, which is like SharedPreferences but easier because you don't need separate methods for different data types, just read and write.
I don't know how you're adding tasks in your app, but this is just a basic example of storing a list of Task objects. Any solution that doesn't involve online storage requires storing locally, and retrieving from storage on app start.
So let's say here is your Task object.
class Task {
final String name;
final String description;
Task({this.name, this.description});
}
Put this in your main method before running your app
await GetStorage.init();
You'll need to add async to your main, so if you're not familiar with how that works it looks like this.
void main() async {
await GetStorage.init();
runApp(MyApp());
}
Normally I would NEVER do all this logic inside a stateful widget, but instead implement a state management solution and do it in a class outside of the UI, but that's a whole different discussion. I also recommend checking out GetX, Riverpod, or Provider reading about them and seeing which one strikes you as the easiest to learn. GetX gets my vote for simplicity and functionality.
But since you're just starting out I'll omit that part of it and just put all these functions in the UI page for now.
Also instead of only storing when app closes, which can also be done, its easier to just store anytime there is a change to the list.
Here's a page with some buttons to add, clear, and print storage so you can see exactly whats in your list after app restart.
If you understand whats going on here you should be able to do this in your app, or study up on json and do it that way. Either way, you need to wrap your head around Maps and how local storage works with any of the available solutions.
class StorageDemo extends StatefulWidget {
#override
_StorageDemoState createState() => _StorageDemoState();
}
class _StorageDemoState extends State<StorageDemo> {
List<Task> _tasks = [];
final box = GetStorage(); // list of maps gets stored here
// separate list for storing maps/ restoreTask function
//populates _tasks from this list on initState
List storageList = [];
void addAndStoreTask(Task task) {
_tasks.add(task);
final storageMap = {}; // temporary map that gets added to storage
final index = _tasks.length; // for unique map keys
final nameKey = 'name$index';
final descriptionKey = 'description$index';
// adding task properties to temporary map
storageMap[nameKey] = task.name;
storageMap[descriptionKey] = task.description;
storageList.add(storageMap); // adding temp map to storageList
box.write('tasks', storageList); // adding list of maps to storage
}
void restoreTasks() {
storageList = box.read('tasks'); // initializing list from storage
String nameKey, descriptionKey;
// looping through the storage list to parse out Task objects from maps
for (int i = 0; i < storageList.length; i++) {
final map = storageList[i];
// index for retreival keys accounting for index starting at 0
final index = i + 1;
nameKey = 'name$index';
descriptionKey = 'description$index';
// recreating Task objects from storage
final task = Task(name: map[nameKey], description: map[descriptionKey]);
_tasks.add(task); // adding Tasks back to your normal Task list
}
}
// looping through you list to see whats inside
void printTasks() {
for (int i = 0; i < _tasks.length; i++) {
debugPrint(
'Task ${i + 1} name ${_tasks[i].name} description: ${_tasks[i].description}');
}
}
void clearTasks() {
_tasks.clear();
storageList.clear();
box.erase();
}
#override
void initState() {
super.initState();
restoreTasks(); // restore list from storing in initState
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Container(),
),
TextButton(
onPressed: () {
final task =
Task(description: 'test description', name: 'test name');
addAndStoreTask(task);
},
child: Text('Add Task'),
),
TextButton(
onPressed: () {
printTasks();
},
child: Text('Print Storage'),
),
TextButton(
onPressed: () {
clearTasks();
},
child: Text('Clear Tasks'),
),
],
),
);
}
}
Welcome to Flutter and Dart! Things might seem daunting in the start, but rewarding later on. Think of it logically, how is data to be stored outside the state of the app?
It has to be fetched from some data storage, this can either from the devices storage, or from a remote database.
For the device storage, you have the two options you mentioned, but SQlite would be an overkill for this task, however sharedPreferences isn't daunting as it seems, and very easy to use once you get the hang of it.
It's basically storing data on the device in the form of a string, along with a uniquekey to retrieve that data later on. This key is also a string.
For your app, you only need two keys: 'tasks' & 'completedTasks'.
Where are you facing trouble? encoding the data as a string? Or converting it to a map first then encoding it?
You're other option would be a remote database, that you send data over the internet, Firebase is only one of the possible solutions, besides building your own server, API and database, which is definitely an overkill for this situation as well.
However, since you are still getting the hang of things, this would be a good project to start with shared preferences, then in phase two, look into firebase, so your ToDo list items can be synced across multiple devices. This also comes with the added benefit you will gain from learning firebase, I strongly advise you look into it.
Every new language is daunting in the start, but expecting things to be 1+1=2 form the start will not get you where you want to be, and I'm certain you did not start learning Flutter to only make todo apps, but what you learn from this app will prepare you for what the future holds.
My advise, get comfortable with being uncomfortable, and remember why you started this journey, and whatever help you need, the community will never disappoint, just meet us or meet yourself half way.

how to get data from {} in graphql

I want to get data about user addinfo(bool value).
when i do console.log(data.user), i can get data.user referred to below picture.
if when i do console.log(data.user.user), it shows that user is undefined referred to below picture.
{
user(token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImI3ZTA5YmVhOTAzNzQ3ODQiLCJleHAiOjE1NjM4OTcxNzksIm9yaWdJYXQiOjE1NjM4OTY4Nzl9.QFB58dAvqIC9RBBohN1b3TdR542dBZEcXOG1MSTqAQQ") {
user {
id
addinfo
}
}
}
this code show that
{
"data": {
"user": {
"user": {
"id": "4",
"addinfo": false
}
}
}
}
I can't see the rest of your code, but if the code is fetching your users, there is a time before the request comes back where your user has not been fetched yet. It looks like your screenshot shows this. There is an undefined before the successful object.
You need to ensure that the data has come back first be checking if the data prop is truthy or some other way to check if the promise has completed yet.
ie
if (!data.user) return 'Loading...';
return (
<Switch>
...
In GraphQL I'm getting user info using e.g. below code:
async getUser(id) {
const result = await this.api.query({
query: gql(getUser),
variables: {
id,
},
});
return result.data.getUser || null;
}
I'm invoking it by:
const user = await userService.getUser(id);
and I do have access to user properties.
Maybe you're trying to get user data before they are retrieved and available?

How do you find an item in a repository by something other than id

If I have a repository with many properties and I want to find something by the non-id property, do I just find all and then return the data after a boolean comparison, or is there a better way to find by a property that's not the ID?
In loopback4, you need to use repository for this purpose. Do as below.
For case where you know there will be just one entry with value. (Unique columns)
const user = await this.userRepository.findOne({
where: {
username: 'test_admin'
}
});
For case where there can be multiple.
const user = await this.userRepository.find({
where: {
firstName: 'test admin'
}
});
For Loopback 3, here you find the documentation for querying data: https://loopback.io/doc/en/lb3/Querying-data.html
Basically, use a query filter like this:
const objects = await app.models.ModelName.find(
{
where: {
propertyName: value
}
}
)
Don't forget to define an index for the property you want to query because otherwise, the database engine will perform a full table scan.
"properties": {
"propertyName": {
"type": "string",
"index": {
"unique": true
}
},
...
}

How do I resolve data for a schema type that implement an interface in GraphQL?

I’m trying to develop a spring boot graphQl service using graphql-java-8 library. I’m fetching data from a web-service, the response I get from the service is a bit like dynamic for which I have to introduce graphQl interface in my response graphQl schema.
extend type Query {
search(
name: String,
category: String
): [ResultOne]
}
interface ResultOne {
name: String
content: String
}
type Fish implements ResultOne {
name: String
content: String
weight: Float
}
type Fruit implements ResultOne {
name: String
content: String
Color: String
}
type Toy implements ResultOne {
name: String
content: String
description: String
}
To wiring my model with graphQl framework,
return RuntimeWiring.newRuntimeWiring()
.wiringFactory(new WiringFactory() {})
.type(
TypeRuntimeWiring.newTypeWiring("ResultOne")
.typeResolver(env -> {
if(env.getObject() instanceof Map) {
Map object = env.getObject();
if (object.containsKey("name") && object.get("name").equals("fish")) {
return (GraphQLObjectType) env.getSchema().getType("Fish");
} else if (object.containsKey("name") && object.get("name").equals("fruit")) {
return (GraphQLObjectType) env.getSchema().getType("Fruit");
} else if(object.containsKey("name") && object.get("name").equals("toy")) {
return (GraphQLObjectType) env.getSchema().getType("Toy");
} else {
return null;
}
} else {
return null;
}
})
)
.build();
So, type resolving issue is also fix a way, not sure it’s ideal or not. For data binding I’m not sure how do I do that in graphQl’s recommended way. I would like to add that, I’ve a single End-Point and single fetcher for the whole API. Data are fetched in a single request and don't want to call twice as I already have whole response. I had to resolve the type at runtime and wire the data for implemented model. So far data are fetched perfectly and the values are also coming till the interface against my query, but appeared null for interface implemented model part e.g: Fish, Fruit & Toy in this example. My question is how do I manupulate dynamically resolved type data for the java library?
Feel free to ask me any question regarding this issue.
Sample query:
{
search() {
ResultOne {
name
content
... on Fish {
weight
}
}
}
}
Corresponding response that I'm currently getting:
{
"data": {
"search": [
{
"resultOne": [
{
"name": "Salmon",
"content": "Frozen Food",
"weight": null
}
]
}
]
},
"extensions": {
"Total-ResponseTime": 23020,
"resultOne-Time": 22683
}
}