Flutter Firestore add new document with Custom ID - dart

How to add new document with custom id using Dart and Flutter?
PS: I can add new document to collection but its id sets randomly, using this code
postRef.add(data);
which postRef is CollectionReference and data is Map<String, dynamic>

You can use set() function instead of add().
Here's full code:
final CollectionReference postsRef = Firestore.instance.collection('/posts');
var postID = 1;
Post post = new Post(postID, "title", "content");
Map<String, dynamic> postData = post.toJson();
await postsRef.doc(postID).set(postData);
I hope that help anyone.

Update 2021:
Instead of using add, use set on the document.
var collection = FirebaseFirestore.instance.collection('collection');
collection
.doc('doc_id') // <-- Document ID
.set({'age': 20}) // <-- Your data
.then((_) => print('Added'))
.catchError((error) => print('Add failed: $error'));

String uniqueCode = //Your Unique Code
DocumentReference reference = Firestore.instance.document("test/" + uniqueCode );
//Setting Data
Map<String, String> yourData;
reference.setData(yourData);

You can try this code to insert new Document with customID
DocumentReference<Map<String, dynamic>> users = FirebaseFirestore
.instance
.collection('/users')
.doc("MyCustomID");
var myJSONObj = {
"FirstName": "John",
"LastName": "Doe",
};
users
.set(myJSONObj)
.then((value) => print("User with CustomID added"))
.catchError((error) => print("Failed to add user: $error"));

Related

How would I write this query that was created in TypeORM query builder using find options

Here is what I need to convert
productsQuery = this.productsRepository.createQueryBuilder('product')
.leftJoin('product.entities', 'productEntities')
.leftJoin('productEntities.entities', 'parentEntities')
.where(qb => {
const subQuery = qb.subQuery()
.select("authUserParentEntities.id")
.from(User, "user")
.leftJoin('user.entity', 'authUserEntity')
.leftJoin('authUserEntity.entities', 'authUserParentEntities')
.where('authUserParentEntities.type = :authParentEntityType')
.andWhere('user.id = :authUserId')
.getQuery()
return "parentEntities.id IN " + subQuery;
})
.setParameter('authParentEntityType', authParentEntityType)
.setParameter('authUserId', authUserId)
.andWhere('productEntities.type NOT IN(:...entityTypes)', {entityTypes: entityTypeArray});
This is what I have using find options so far
const productRepository = getManager().getRepository(Product);
let entityId = 'entityid'
let userId = 'userid'
let result = await productRepository.find({
where: {
'entities': [
{
id: entityId
}
]
}
})
the entities inside of product
is an array of entities
I just want to get the products by entity id
using TypeORM's find options rather than the query builder
#ApiProperty({ type: (type) => Entity, isArray: true })
#ManyToMany((type) => Entity, (entity) => entity.products)
public entities: Entity[];

Update SharePoint document library item hyperlink field using using Microsoft Graph in C#

I'm trying to update a SharePoint document library item's hyperlink field using Microsoft Graph in C#.
I'm using Microsoft.Graph 4.10.0 to update the hyperlink in SharePoint. This is the code I have tried which give me an Invalid request error.
var fieldValueSet = new FieldValueSet
{
AdditionalData = new Dictionary<string, object>
{
{"OriginalImageLink", new Dictionary<string, string>{{"https://example.com/img1.jpg", "https://example.com/img1.jpg"}}}
}
};
await GraphClient.Sites["siteId"].Lists["listId"].Items["listItemId"].Fields.Request().UpdateAsync(fieldValueSet);
I can update a text field in SharePoint which works fine:
var fieldValueSet = new FieldValueSet
{
AdditionalData = new Dictionary<string, object>
{
{"Comment", "This is my comment"}
}
};
I can also update the hyperlink using HTTP:
PATCH https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items/{item-id}/fields
Content-Type: application/json
{
"OriginalImageLink": {"Url": "https://example.com/img1.jpg", "Description": "https://example.com/img1.jpg"}
}
Conclusion: I can't update a SharePoint hyperlink field using C#. But I can update a text field in SharePoint and I can update the hyperlink using HTTP.
How do I update the SharePoint hyperlink field using C#?
Update:
This feature is currently not supported. Upvote this feature
Did you try to specify Url and Description fields in fieldValueSet?
var fieldValueSet = new FieldValueSet
{
AdditionalData = new Dictionary<string, object>
{
{ "OriginalImageLink", new Dictionary<string, string>
{
{ "Url" , "https://example.com/img1.jpg" },
{ "Description", "https://example.com/img1.jpg"}
}
}
}
};
await GraphClient.Sites["siteId"].Lists["listId"].Items["listItemId"].Fields
.Request()
.UpdateAsync(fieldValueSet);
Update:
According to this answer the update of sharepoint listitem with hyperlink field is not supported.

Update list Aspnet core 2.2

I would like to update a list of items most do not know how to do, when my only method adciona new items to existing inves change.
save change
public async Task<CommandResult> ExecuteAsync(EventsCommandsHandler handler)
{
var listItens = await handler.DbContext.ListItens
.Where(f => f.Id == this.Id)
.SingleOrDefaultAsync();
listItens.SetData(
name: Name,
description: Description
);
handler.DbContext.ListItens.Update(listItens);
if (Items.Length > 0)
{
var itens = Items
.Select(p => p.ToItemList(listItens.Id))
.Where(p => p != null)
.ToArray();
await handler.DbContext.ItemsList.(itens);
}
var rows = await handler.DbContext.SaveChangesAsync();
return await Task.FromResult(new CommandResult(rows));
}
create intens
public static ItemList ToItemList(this ItemCommand command, string listId)
{
if (string.IsNullOrWhiteSpace(command.Description))
return null;
var itens = new ItemList(
id: String.IsNullOrWhiteSpace(command.Id) ? RandomId.NewId(8) : command.Id,
description: command.Description,
listId: listId
);
return itens;
}
I need a way for this method.
I have a list and this list has items, when I edit the list, I want to be able to delete, edit or add more items.
You have a To-Do list. There should be an add button.
A post request should be sent and data should be written to the database, and page - updated when you press any button like remove, edit and add.
If you want it to be async, then you should use JavaScript or Blazor.

Setting custom properties on an 365 group with GraphClient

I want to set CustomProperty5 on a 265 group. I have following code:
var extensions = await graphClient.Groups["xxx"].Extensions.Request().GetAsync();
var dictionary = new Dictionary<string, object>();
dictionary.Add("CustomAttribute5", "Works!");
await graphClient
.Groups["xxx"]
.Request()
.UpdateAsync(new Microsoft.Graph.Group()
{
AdditionalData = dictionary
});
However I get following error:
Microsoft.Graph.ServiceException: 'Code: Request_BadRequest Message:
One or more property values specified are invalid.
Any pointers how to set custom properties on a 365 group?
For existing group open extension could be updated like this via msgraph-sdk-dotnet:
//retrieve an existing group custom property
var ext = await graphClient.Groups[groupId].Extensions[extName].Request().GetAsync();
//update
ext.AdditionalData = new Dictionary<string, object>()
{
{
"status", "Closed"
}
};
await graphClient.Groups[groupId].Extensions[extName]
.Request()
.UpdateAsync(ext);
When it comes to complex type extension, it could be updated via group update endpoint. Lets assume the following type extension is registered:
{
"id":"contoso_grpstatus",
"description": "",
"targetTypes": [
"Group"
],
"properties": [
{
"name": "Status",
"type": "String"
}
]
}
Then an existing group instance with the contoso_grpstatus complex type extension defined could be updated like this:
var group = new Group
{
AdditionalData = new Dictionary<string, object>()
{
{
"contoso_grpstatus", new Dictionary<string, object>()
{
{"Status", "Closed"}
}
}
}
};
await graphClient.Groups[groupId]
.Request()
.UpdateAsync(group);

How to add drop-down list instead of a textfield

I will put a "Choose Civil Status" parameter inside a POST method in my Swagger-UI, so instead of a text fields I wanted it to be a drop down list, I'm using MVC 3, Can anyone explain how can I do that?
here is my sample code..
[HttpPost]
public string Generate(string id, Salutation Salutation)
{
//code here
}
Inside the controller put
var Users = db.TABLENAME;
List<ListItem> list = new List<ListItem> ();
list.Add(new ListItem("Please Select", "0"));
foreach (var item in Users)
{
list.Add(new ListItem(item.ColName , item.UserId.ToString()));
}
ViewBag.UserList = new SelectList(list, "ValueField", "TextField");
In View
#Html.DropDownList("SomeName", (SelectList)ViewBag.UserList , new { #class = "DropDownList W150 ", value = #ViewBag.SelectedVal })
and you will have to declare your ListItem in ModelClasses

Resources