How to create several new records in another SQL table from one button-click - sql

I'm new here. Thanks in advance for your advice.
I’m working on an app which will ask the user how many items they made.
The user will enter a number. My app should then create that many new records in a table called 'Items_Made'.
E.g. The app asks “How many items did you make?”, the user enters “19”, the app then creates 19 new records in the 'Items_Made' table.
I've managed to pull together some code (shown below) that creates ONE new record, but I would like it to create several. I probably need some kind of loop or 'while' function but am unsure how to do so.
var ceateDatasource = app.datasources.Items_Made.modes.create;
var newItem = ceateDatasource.item;
ceateDatasource.createItem();
This code successfully creates 1 record. I would like it to be able to create several.

Creating a lot of records via client script is not recommended, especially if you loose connection or the app gets closed by mistake. In my opinion, the best way to handle this would be via server script for two things: First, It's more reliable and second, it's faster. As in the example from the official documentation, to create a record you need to do something like this:
// Assume a model called "Fruits" with a string field called "Name".
var newRecord = app.models.Fruits.newRecord();
newRecord.Name = "Kiwi"; // properties/fields can be read and written.
app.saveRecords([newRecord]); // save changes to database.
The example above is a clear example on how to create only one record. To create several records at once, you can use a for statement like this:
function createRecordsInBulk(){
var newRecords = [];
for(var i=0; i<19; i++){
var newRecord = app.models.Fruits.newRecord();
newRecord.Name = "Kiwi " + i;
newRecords.push(newRecord);
}
app.saveRecords(newRecords);
}
In the example above, you initiate newRecords, an empty array that will be responsible for holding all the new records to create at once. Then using a for statement, you generate 19 new records and push them into the newRecords. Finally, once the loop is finished, you save all the records at once by using app.saveRecords and passing the newRecords array as an argument.
Now, all this is happening on the server side. Obviously you need a way to call this from the client side. For that, you need to use the google.script.run method. So from the client side you need to do the following:
google.script.run.withSuccessHandler(function(result) {
app.datasources.Fruits.load();
}).createRecordsInBulk();
All this information is clearly documented on the app maker official documentation site. I strongly suggest you to always check there first as I believe you can get a faster resolution by reading the documentation.

I'd suggest making a dropdown or textbox where the user can select/enter the number of items they want to create and then attach the following code to your 'Create' button:
var createDatasource = app.datasources.Items_Made.modes.create;
var userinput = Number(widget.root.descendants.YourTextboxOrDropdown.value);
for (var i = 0; i <= userinput; i++) {
var newItem = createDatasource.item;
createDatasource.createItem();
}
Simple loop with your user input should get this accomplished.

Related

Microsoft Graph API not returning custom column from list

Working in VB.Net, using the Microsoft.Graph api communicate with sharepoint.
I have a list on a sharepoint site.
Lets say:
List name : ListTestName
Columns: ListColumnTest1, ListColumnTest2, ListColumnTest3
Dim queryFields As List(Of QueryOption) = New List(Of QueryOption) From {New QueryOption("$expand", "fields")}
Dim items As IListItemsCollectionPage = Await GraphClient.Sites(sharepointSessionId).Lists("ListTestName").Items.Request(queryFields).GetAsync()
This is the code I have to grab the list and trying to get all of the fields (columns) but when I look into the Fields in the "Items" variable I do not see any of the fields that I have added to the list. I only see the sharepoint fields such as "title" or "Id"
I really dont understand why this is not working.
Even when I look via the the graph-explorer site (https://developer.microsoft.com/en-us/graph/graph-explorer) using:
GET https://graph.microsoft.com/v1.0/sites/<SiteId's>/lists/ListTestName/items?expand=fields
I do not see my custom columns However if I try and filter directly to one of the columns like this :
GET https://graph.microsoft.com/v1.0/sites/<SiteId's>/lists/ListTestName/items?expand=fields(select=ListColumnTest1)
This does seem to have returned back my custom field.
Thus I tried adding to the query field {New QueryOption("$expand", "fields(select=ListColumnTest1")} this just crashed when I called the request.
Edit: I asked this question slightly wrong and will be posting a second question that is more to what I need. However, below the question is marked correct because their solution is the correct solution for what I asked. :)
Have you try this endpoint?
GET https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}?expand=columns,items(expand=fields)
I could get the custom columns with this endpoint.
Updated:
IListColumnsCollectionPage columns = graphClient.Sites["b57886ef-vvvv-4d56-ad29-27266638ac3b,b62d1450-vvvv-vvvv-84a3-f6600fd6cc14"].Lists["538191ae-7802-43b5-90ec-c566b4c954b3"].Columns.Request().GetAsync().Result;
I would avoid to create QueryOption. Try to use Expand and Select method.
Example (C#...apologise I'm not familiar with VB but I hope it will easy for you to rewrite it):
await GraphClient.client.Sites[sharepointSessionId].Lists["ListTestName"].Items.Request()
.Expand(x => new
{
ListColumnTest1 = x.Fields.AdditionalData["ListColumnTest1"],
ListColumnTest2 = x.Fields.AdditionalData["ListColumnTest2"]
})
.Select(x => new
{
ListColumnTest1 = x.Fields.AdditionalData["ListColumnTest1"],
ListColumnTest2 = x.Fields.AdditionalData["ListColumnTest2"]
})
.GetAsync();

In Parse Need to fetch nested relation data in one call

I am currently working with parse in react native.
I have a query that fetches data from a collection which has a property with relation to other collection.
Now i want to fetch all these relational data in a single call rather then calling each relation separately.
Currently i get one collection then get its relational data separately in a new call.
const data1 = await result
.get("data1")
.query()
.descending("createdAt")
.find();
const data2 = data1.relation("test");
const data3 = await data2.query().find();
Now i want to fetch the relational data along with the data1 in the very first call.
I would like to know is it even possible in parse.
If yes how?
I have been trying to fetch relational data all day but no success.
Any help would really be appreciated.
I hope you're fine :)
Using relations, you will need to fetch the data with more than a single call.
Why is it necessary?
It is required because the relation type creates a new collection on the database to store the relational data.
Please, take a look at the code below:
query.find().then(results => {
for (var i = results.length - 1; i >= 0; i--) {
let object = results[i];
object.relation("data1").query().each(function(relatedObject) {
console.log(relatedObject);
/* .... */
});
}
}).catch(console.error());
Is there another option to receive the data in a single call?
Yes, there is! To configure this option, you will need to use the pointer or array type, then you will be able to use include() method and get the column value, please read more about it below:
https://docs.parseplatform.org/js/guide/#one-to-many

Load Document and create object inside script patch

I have an event object with Payments collection. When event is cancelled I need to add those payments to the appropriate User object Refunds collection. Based on the documentation I came to the following schematic script:
_(this.Payments).forEach(function(payment) {
var user = LoadDocument(payment.UserId);
user.Refunds.push(new { EventId = this.Id, Payment = payment });
}
There are two things in this schematic script that I didn't find how to do right in the documentation:
1. Load another document by Id (line 2)
2. Create new json-object (line 3)
The LoadDocument() is correct, however the loaded document isn't automatically tracked by any Unit of Work when loaded within a Patch.
You have to tell Raven to update/store that document as well:
var user = LoadDocument(payment.UserId);
user.Refunds.push({ EventId = this.Id, Payment = payment });
PutDocument(user.UserId, user);
If you really want to do this from a patch, the above might work. However, this seems like a more domain specific operation and might be better to model the behaviour in your application code (i.e. raise an event and add the refunds to the user objects from code). Not 100% sure how Raven handles transactions within patches and so on...
Edit: For your second question: You don't need to use the 'new' keyword

Check if property exists in RavenDB

I want to add property to existing document (using clues form http://ravendb.net/docs/client-api/partial-document-updates). But before adding want to check if that property already exists in my database.
Is any "special,proper ravendB way" to achieve that?
Or just load document and check if this property is null or not?
You can do this using a set based database update. You carry it out using JavaScript, which fortunately is similar enough to C# to make it a pretty painless process for anybody. Here's an example of an update I just ran.
Note: You have to be very careful doing this because errors in your script may have undesired results. For example, in my code CustomId contains something like '1234-1'. In my first iteration of writing the script, I had:
product.Order = parseInt(product.CustomId.split('-'));
Notice I forgot the indexer after split. The result? An error, right? Nope. Order had the value of 12341! It is supposed to be 1. So be careful and be sure to test it thoroughly.
Example:
Job has a Products property (a collection) and I'm adding the new Order property to existing Products.
ravenSession.Advanced.DocumentStore.DatabaseCommands.UpdateByIndex(
"Raven/DocumentsByEntityName",
new IndexQuery { Query = "Tag:Jobs" },
new ScriptedPatchRequest { Script =
#"
this.Products.Map(function(product) {
if(product.Order == undefined)
{
product.Order = parseInt(product.CustomId.split('-')[1]);
}
return product;
});"
}
);
I referenced these pages to build it:
set based ops
partial document updates (in particular the Map section)

Add users to UserMulti field type using Client Object Model

I'm bit of a SharePoint noobie so please bear with me.
I need to be able to create a new list item in one our custom list using the client object model. I have been following the example described on the MSDN site and for the most part this has worked.
We have a list that contains several fields including a UserMulti field type. I am having problems adding users to this field. So far I have tried the following but this somehow always seems to default to the system account rather than the user specified in the field.
...
listItem["ProjectMembers"] = "1;#domain\\johndoe";
listItem.Update();
_clientContext.ExecuteQuery();
Do I need to do some type of lookup first? Any help is appreciated. Thanks.
It took a little while but I figured it out in the end. Below are two approaches you can take
Assign a Principal to the list item
var principal = _rootWeb.EnsureUser("domain\\johndoe") as Principal;
listItem["ProjectMembers"] = principal;
listItem.Update();
_clientContext.ExecuteQuery();
Assign an list of FieldUserValue if you need to assign more than one user to the field.
string[] users = { "domain\\johndoe", "domain\\peterpan" };
var projectMembers = users
.Select(loginName => FieldUserValue.FromUser(loginName))
.ToList();
listItem["ProjectMembers"] = projectMembers;
listItem.Update();
_clientContext.ExecuteQuery();
I'm sure there's better ways of doing things and you could combine the two to ensure that the users are valid before adding them to the list, but this is working so far. Hope this help someone else.
Microsoft has a wiki article, "SharePoint: A Complete Guide to Getting and Setting Fields using C#" that can help. http://social.technet.microsoft.com/wiki/contents/articles/21801.sharepoint-a-complete-guide-to-getting-and-setting-fields-using-c.aspx#Set_and_Get_a_Multi-Person_Field
It includes this sample code.
var lotsofpeople = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
var personA = web.EnsureUser("contoso\\fred");
var personAValue = new SPFieldUserValue(web, personA.ID, personA.LoginName);
var personB = web.EnsureUser("contoso\\barnie");
var personBValue = new SPFieldUserValue(web, personB.ID, personB.LoginName);
lotsofpeople.Add(personAValue);
lotsofpeople.Add(personBValue);
item["lotsofpeoplefield"] = lotsofpeople;
item.Update();