Parse Android: update ParseObject containing an array of ParseUsers throws UserCannotBeAlteredWithoutSessionError - parse-platform

im working on an Android App.
I have a custom class which has relations with TWO ParseUsers and other fields. As suggested by the docs, I used an array (with key "usersArray") to store the pointers for the two ParseUsers, because I want to be able to use "include" to include the users when i query my custom class. I can create a new object and save it successfully.
//My custom parse class:
CustomObject customObject = new CustomObject();
ArrayList<ParseUser> users = new ArrayList<ParseUser>();
users.add(ParseUser.getCurrentUser());
users.add(anotherUser);
customObject.put("usersArray", users);
//I also store other variable which i would like to update later
customObject.put("otherVariable",false);
customObject.saveInBackground();
Also, i can query successfully with:
ParseQuery<CustomObject> query = CustomObject.getQuery();
query.whereEqualTo("usersArray", ParseUser.getCurrentUser());
query.whereEqualTo("usersArray", anotherUser);
query.include("usersArray");
query.findInBackground( .... );
My problem is when trying to UPDATE one of those CustomObject.
So after retrieving the CustomObject with the previous query, if I try to change the value of the "otherVariable" to true and save the object, I am getting a UserCannotBeAlteredWithoutSessionError or java.lang.IllegalArgumentException: Cannot save a ParseUser that is not authenticated exceptions.
CustomObject customObject = customObject.get(0); //From the query
customObject.put("otherVariable", true);
customObject.saveInBackground(); // EXCEPTION
I can see this is somehow related to the fact im trying to update an object which contains a pointer to a ParseUser. But im NOT modifying the user, i just want to update one of the fields of the CustomObject.
¿There is any way to solve this problem?

Maybe late but Parse users have ACL of public read and private write so you should do users.isAuthenticated() to check if its true or false.
If false then login with the user and retry. Note: you cannot edit info on two users at the same time without logging out and relogging in.
Another thing you can do is use Roles and define an admin role by using ACL which can write over all users.

Related

extending datamodel in Microstream

I would like to extend an existing datamodel in Microstream with a new data object. E.g. I have Customers, with data records in Microstream, and I would like to add Vendors, with their own datastructure and data. As the database is not empty, I cannot start as if their is no data, however adding a list of Vendor to the dataroot doesn't seem to work. Microstream says the list is null when starting, which is correct, but I cannot add my new object to a null list. Can someone explain me how to add a vendor to my 'database' ?
You just need to add this List and store this object with the existing list again.
I received an answer from fh-ms # Microstream:
Hi, you are right, the vendors list is not present in the storage, so the field will be initialized with its default value (null).
There are several possibilities to introduce initial values to new fields.
One rather complex way would be to implement a Legacy Type Handler.
A far more simple one is just lazy initialization in your Customer type:
public List<Vendor> getVendors()
{
if(this.vendors == null)
{
this.vendors = new ArrayList<>()
}
return this.vendors;
}
And that works !

hotchocolate throws error when using UseFiltering() on a field

I have a pretty simple setyp where I'm putting graphql over an entityframework datacontext (sql server).
I'm trying to get filtering to work. I've tried adding .UseFiltering() to a field descriptor like so...
descriptor.Field(t => t.AccountName).Type<NonNullType<StringType>>().UseFiltering();
But it causes this error on startup...
HotChocolate.SchemaException: 'Unable to infer or resolve a schema
type from the type reference Input: System.Char.'
I assume I'm doing something wrong somewhere...
"UseFiltering" is supposed to be used to filter data which represents a collection of items in some way (IQueryable, IEnumerable, etc).
For instance, if you have users collection and each user has AccountName property you could filter that collection by AccountName:
[ExtendObjectType(Name = "Query")]
public class UserQuery
{
[UseFiltering]
public async Task<IEnumerable<User>> GetUsers([Service]usersRepo)
{
IQueryable<User> users = usersRepo.GetUsersQueryable();
}
}
In that example the HotChocolate implementation of filtering will generate a number of filters by user fields which you can use in the following way:
users(where: {AND: [{accountName_starts_with: "Tech"}, {accountName_not_ends_with: "Test"}]})
According to your example: the system thinks that AccountName is a collection, so tries to build filtering across the chars the AccountName consists of.

Entity being tracked despite AsNoTracking

I have an object, Client, with a navigation property that is a list of Order objects. Whenever I retrieve a Client object, I include the list of Orders, with AsNoTracking().
public new IQueryable<Client> FindByConditionNoTracking(Expression<Func<Client, bool>> expression)
{
return this.ClientContext.Set<Client>().Include(s => s.Orders)
.Where(expression).AsNoTracking();
}
In my UpdateClient repository method, I take in a Client object. I then attempt to retrieve that original client from the database (using Include to get the child Orders), map the Client param to the original, and save to the database. Over here, I do not use AsNoTracking, because I specifically want the changes to be tracked.
public new void Update(Client client)
{
var id = client.ClientId;
var original = this.ClientContext.Clients.Include(s => s.Orders).Where(s => s.ClientId == id)
.FirstOrDefault<Client>();
original = _mapper.Map(client, original);
this.ClientContext.Update(original);
}
The error I am getting is that an instance of Order with the same key value is already being tracked. A few problems with that:
Wherever the Client and the child Orders are retrieved for the purposes of display I use AsNoTracking.
The only place where I retrieve without AsNoTracking is where I get the original within this very method.
The bug isn't with the parent property. If I was improperly retrieving the Client elsewhere, wouldn't I have this error with the Client id itself? But the error seems to be only with the navigation property.
All insight is appreciated!
If anyone else runs into this: Automapper, when mapping collections, apparently recreates the entire collection. I solved the above issue by using Automapper.Collections in my mapping configuration. Thanks to Mat J for the tip!

Parse-Server prevent fields from being added automatically

Right now, if I add a field to a Parse object and then save it, the new column shows up in the Parse dashboard.
For example, after running:
let media = new Parse.Object("Media");
media.set("foo", "bar");
await media.save();
I will have a new column called foo.
Is it possible to prevent this from happening?
Yes. This can be done using class-level permissions, which allow you to prevent fields being added to classes.
Parse lets you specify what operations are allowed per class. This lets you restrict the ways in which clients can access or modify your classes.
...
Add fields: Parse classes have schemas that are inferred when objects are created. While you’re developing your app, this is great, because you can add a new field to your object without having to make any changes on the backend. But once you ship your app, it’s very rare to need to add new fields to your classes automatically. You should pretty much always turn off this permission for all of your classes when you submit your app to the public.
You would have to add a beforeSave trigger for every one of your classes, keep a schema of all your keys, iterate over the request.object's keys, and see if there are any that do not belong in your schema. You can then either un-set them and call response.success(), or you can call response.error() to block the save entirely, preferably with a message indicating the offending field(s).
const approvedFields = ["field1", "field2", "field3"];
Parse.Cloud.beforeSave("MyClass", function(request, response) {
let object = request.object;
for( var key in object.dirtyKeys() ) {
if( approviedFields.indexOf(key) == -1 ) return response.error(`Error: Attempt to save invalid field: ${key});
}
response.success();
});
Edit:
Since this got a little attention, I thought I'd add that you can get the current schema of your class. From the docs: https://docs.parseplatform.org/js/guide/#schema
// create an instance to manage your class
const mySchema = new Parse.Schema('MyClass');
// gets the current schema data
mySchema.get();
It's not clear if that's async or not (you'll have to test yourself, feel free to comment update the answer once you know!)
However, once you have the schema, it has a fields property, which is an object. Check the link for what those look like.
You could validate an object by iterating over it's keys, and seeing if the schema.fields has that property:
Parse.Cloud.beforeSave('MyClass', (request, response) => {
let object = request.object;
for( var key in object.dirtyKeys() ) {
if( !schema.fields.hasOwnProperty(key) ) < Unset or return error >
}
response.success();
}
And an obligatory note for anyone just starting with Parse-Server on the latest version ,the request scheme has changed to no longer use a response object. You just return the result. So, keep that in mind.

Entity Framework saves duplicates of one side in a one to many

I am having a problem with Entity Framework in my MVC 3 application. I have a users table, which is only ever populated with a new user row when a machine entity is created by a user that hasn't created any machines before, i.e. it only creates users it hasn't seen before. Each user belongs to a sector (division of the company) which also must be set before the user and the machine are saved. I have a default sector that new users are assigned to (so that this may be changed later on).
I have some code in my machine controller class for the creation of new machines that looks like this:
[HttpPost]
public ActionResult Create(Machine machine)
{
if (ModelState.IsValid)
{
// work out if the user exists in the database already
var users = userRepository.All.Where(u => u.Username == machine.User.Username);
if (users.Count() == 0)
{
// if the user entry doesn't exist we have to create it assigning a default sector
Sector defaultSector = null;
var defaultSectors = sectorRepository.All.Where(s => s.IsDefaultForNewUsers);
if (defaultSectors.Count() == 0)
{
// jebus! no default sector, so create one
defaultSector = new Sector() { Name = "Default", IsDefaultForNewUsers = true };
sectorRepository.InsertOrUpdate(defaultSector);
sectorRepository.Save();
}
else
{
defaultSector = defaultSectors.First();
}
machine.User.Sector = defaultSector;
}
else
{
machine.User = users.First();
}
machineRepository.InsertOrUpdate(machine);
machineRepository.Save();
return RedirectToAction("Index");
}
else
{
ViewBag.PossibleInstalledOS = installedosRepository.All;
ViewBag.PossibleLicenceTypes = licencetypeRepository.All;
ViewBag.PossibleUsers = userRepository.All;
return View();
}
}
[Edit] Here is the body of the InsertOrUpdate method from my Machine repository:
public void InsertOrUpdate(Machine machine)
{
if (machine.MachineId == default(int)) {
// New entity
context.Machines.Add(machine);
} else {
// Existing entity
context.Entry(machine).State = EntityState.Modified;
}
}
The problem I'm having with this code is that when I save the machine, it keeps creating a new user even though that user is already in the system. The line that finds the user works and retrieves the user as I would expect but entity framework doesn't seem to understand that I wish to use this user that I've found and not create a new one. So at the moment I have multiple identical users (except ID of course) in my users table. I want a one to many here so that multiple machines are owned by the same user.
Does anyone have any idea how I force entity framework to respect that there is already a user there that I want to tie the new machine to?
You didn't post the code for your InsertOrUpdate method but I suspect that that is where the problem is. I bet in that method at some point you do something equivalent to:
context.Machines.Add(machine);
When you call DbSet.Add (or change the state of an entity to Added) you are actually adding the whole graph to the context. This process will stop when it encounters an object that is being tracked by the context. So if you have a machine object that references a user object and neither of these objects are being tracked by the context, then both the machine object and the user object will be added to the context and end up in an Added state. EF will then insert them both as new rows in the database.
What you need to do, which was alluded to in the other answer, is make sure than EF knows that an existing user object does exist in the database by making sure it's state is Unchanged (or possibly Modified) and not Added when you save.
There are various ways that you could accomplish this and it's hard to know which is best for you without seeing more of how your app and repository work. One way is to make sure that the context used to query for the user is the same context as is used to save. This way EF will already be tracking the existing user object and will know not to add it when you call Add.
Another way is to let your repository know somehow whether or not the user object is new. Often people use the primary key to determine this--a zero key indicates a new object, non-zero indicates an existing object. You could also pass a flag into your repository.
You can then call Add to add the graph, but then set the state of the User object to Unchanged (or Modified if it might have been changed since it was queried) if it is an existing user. This will prevent EF from inserting a new user into the database.
Can you double check that your repositories are using the same data context? If not, you are essentially adding a new User entity to the machineRepository. Alternatively you could attach the user to the context for the machine repository, but you'll likely keep running into bugs like this.

Resources