How to get users first and last name? - google-app-maker

#user.email seems to instantly print email address of a user that is using the app on any widget.
Is there a way to get User Name (First Last) in a similar way?

The solution I usually use involves using the directory model. Follow these steps:
1.) Enable the directory model by creating it, I usually name it directory
2.) Next, go to the DATASOURCES section of the directoy model you just created and click on the ADD DATASOURCE button. I usually name this datasource activeUser.
3.) Add the following to any server script:
function getActiveUser() {
var dirQuery = app.models.directory.newQuery();
dirQuery.filters.PrimaryEmail._equals = Session.getActiveUser().getEmail();
var userResult = dirQuery.run();
return userResult;
}
4.) Go back to the activeUser datasource. Add the following to the Server Script Query:
return getActiveUser();
And change the query page size to 1.
5.) Now all you have to make sure is that the widget where you will print the user name has the datasource activeUser either directly or inherited. Then you simply bind it to the FullName property.

Related

can't insert any data to database using controller [EF Core]

I am working on my Uni project that uses database with two tables: Role and User.
Users.RoleId is a foreign key referring to Role.Id
I generated Controllers for each table/model classes using Scaffolding template "MVC Model with views using Entity Framework", so RolesControler.cs and UsersControler.cs are almost the same.
I can create, edit or delete roles using different views which can be seen here.
As you can see, new role is inserted into the database.
While trying to do the exact thing using views specified for UsersController.cs I can't add or modify a user. I fill all the inputs but submitting won't give any results, page is not refreshing (not redirecting to index.cshtml), no data is added to the database, just nothing happens, I can click "Create" button forever.
I tried adding users manually using SQL query in SQL Server Object Explorer and they appear on the list. What's interesting I can delete them using Delete method. The button reacts, redirect me to main page and deletes record from database.
Also while trying to create new User I can only select Roles that already exists - which is intended - but that suggests that the referrence between User.RoleId and Role.Id is done properly.
Here is code for Create method in UsersControler.cs:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Surname,DateOfBirth,Login,RoleId,IsDeleted")] User user)
{
if (ModelState.IsValid)
{
_context.Add(user);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["RoleId"] = new SelectList(_context.Roles, "Id", "Id", user.RoleId);
return View(user);
}
I don't really know why everything is fine for Role table/model, but when it comes to User I can only delete records that already exist in database.
EDIT:
I tried inserting new user using invalid date (year 32121) and validation error occurs, which for me indicates that the submit button reacts and validates input data, but if it's valid, it doesn't insert the record to database and doesn't redirect into index page.
May I ask what your model classes for Role and User look like? I suspect that your data types are not matching. I have a nearly similar problem as you, only that I cannot even enter the foreign key

UserManager.FindByNameAsync() doesn't return anything at all

I need to get the user with some username but the function call seemingly does nothing. I'm using the exact same call in a different controller and it's working just fine.
This is the line:
var user = await _userManager.FindByNameAsync(username);
When I put a break point on this line and the line below it, the debugger stops on this line, and when I try to go to the next line it just pauses for a bit and skips the rest of the function. As a result the controller function also doesn't return anything. Both controllers where I use call this function have the exact same declarations for _userManager and use it in the same way. Only difference is that the one that works gets its parameter from a passed objects property, whereas the other one just uses a string.
Please help I'm starting to lose my hair.
Ensure that you initially create the user using the CreateAsync method of a Microsoft.AspNetCore.Identity.UserManager instance. If you create the user by adding it directly using Entity Framework, you won't be able to find it using FindByNameAsync.
Note: Anybody facing this issue because they couldn't create users using "CreateAsync" or they have an already existing set of users, apply this solution.
Make sure the users in your database who where not created using the "CreateAsync" method of the user manager pass through the following.
//Get the corresponding user by id
var usr2 = _userManager.FindByIdAsync("youruserid").Result;
//Apply the following updates to the user model in the database
var res = await _userManager.UpdateSecurityStampAsync(usr2);
await _userManager.UpdateNormalizedEmailAsync(usr2);
await _userManager.UpdateNormalizedUserNameAsync(usr2);
await _userManager.SetLockoutEnabledAsync(usr2, true);
Apply the above code to every user in your database that was not created using "CreateAsync".
After these steps, you'll now be able to Find your user by username and email.
Note: If your users weren't assigned claims, don't forget to assign claims in the Database.

Multiple datasources for searchbox

I have integrated a 'Header' pagefragment that contains a searchbox into my review app. The searchbox allows me to search for employees in the Directory model, but I would also like to search in the reviews.
The query builder in the Review model goes like this
FamilyName contains? :SearchText or
GivenName contains? :SearchText or
EmployeeEmail contains? :SearchText or
CostCenter contains? :SearchText or
Location contains? :SearchText
When I am on the Review dashboard, I would like the datasource of the searchbox switch from the Directory model to the Review model. I have therefore created the following binding:
(#currentPage == #pages.Dashboard) ?
#datasources.Reviews.query.parameters.SearchText :
#datasource.query.keywords
But when I access the page in the preview the console returns an 'invalid binding' message. How can I fix that?
I don't think that App Maker is smart enough to digest such type of binding for an input widget. I would recommend you to follow the pattern used in Training Hub template:
set some arbitrary datasource for the header page fragment
bind search box to #datasource.query.parameters.SearchText
override datasource for the page fragment on every page where you need it
Your particular use case will require slightly more fancy leg movements. Since for actual search you need different things from the query, you'll need to
Switch your Directory datasource to query script mode
Introduce SearchText query parameter
Add this query script to the datasource
query.keywords = query.parameters.SearchText;
return query.run();
With such adjustments all your datasources will expose the same interface and could have different implementations.

asp.net Entity Framework is it possible to change client values by post method

I'm working on a project using asp.net MVC with Entity Framework.
I was requested to combine the Create page and Edit page together.By another word, if no record , create it, otherwise, edit it. But it brings a problem:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{
if (ModelState.IsValid)
{
if(movie.ID ==0)
{
db.Movies.Add(movie);
}
else
{
db.Entry(movie).State = EntityState.Modified;
}
db.SaveChanges();
}
return View(movie);
}
From above code, you can see that I check the property "id" in DBcontext to know whether it's a new record or existed one.
But during test, I found that If I create a record without close the webpage,and change some values, press the "save" button in browser again, a new record will be created instead of modify the record just created.
I have traced the whole workflow and found that:
When I click the Save button first time to create the record, the "id" of movie object does changed after Savechanges function.
When the browser reload the page after creation, the id property of Model in the webpage is really changed to non-zero.
But finally the display result of ID on webpage is still zero~!!! So at the second time, the controller get the value from webpage's form element with 0.
4.No matter I use hiddenfor , hidden, editFor in webpage, the result is the same.
5.Since the validation error message shows on webpage is also changed via post method, I think there maybe some internal settings of EF to prevent value change. But even if I deleted AntiForgery attribute from both controller and webpage side, the result is also the same...
Is there anyone who can help?

Is there a way to grant access to a table without creating security privileges?

I have a custom temporary table that is used for a simple custom dialog form. Users receive an error:
You are not authorized to access table ‘TmpAddressEntryPrompt’ (TmpAddressEntryPrompt). Contact your system administrator.
I can resolve it if I create a privilege and add the table under Permissions or if I instead call the form with a custom menu item, and add that menu item to a privilege. This is extra overhead that I don't want to add for a temporary table. I've also discovered AllowCheck = No on the form datasource, but this just checks after the form is open, so it still doesn't have access.
Is there a way to just make the temporary table unrestricted for all??
I call the form like this:
args = new Args();
args.name(formStr(AddressEntryPrompt));
args.record(prompt);
promptForm = classFactory.formRunClass(args);
promptForm.init();
promptForm.run();
promptForm.wait(true);
if (promptForm.closedOk())
{
return true;
}
The right way is to add the TmpAddressEntryPrompt table to your form AddressEntryPrompt DataSources (with AllowCreate/AllowEdit).
Little less recommended way is to add this table to the form Permissions - Tables (and set Manual to ManagedMy).

Resources