How do you parse multi data sets through yaml file? - selenium-webdriver

Here's the yaml file :
---
email:
- John#gmail.com
- Adam#gmail.com
password:
- Test#1234
- Abcd#1234
I want my script to run two times, one with each user email and password.
Code i have tried is :
#DataProvider
public Object[][] getData() {
Object[][] data = new Object[2][2];
data[0][0] = YamlReader.getYamlValue("email");
data[0][1] = YamlReader.getYamlValue("password");
data[1][0] = YamlReader.getYamlValue("email");
data[1][1] = YamlReader.getYamlValue("password");
return data;
}
#Test(dataProvider="getData")
public void Test_Login_with_multiple_data_sets(String username, String password) {
element("input_username").sendKeys(username);
element("input_password").sendKeys(password);
element("button_signIn").click();
}
It fails because i don't know the way to pass exact value based on the index for email and password.

Related

Parsing object in dart (Unsupported operation: Cannot add to a fixed-length list)

I have a user object which saved to the cloud firestore database when the user Sign In / Sign Up.
So the user object is retrieved from the database when he signs in, and everything works until i try to do the 'add' operation on the list 'usersProject':
// Add the new project ID to the user's project list
user.userProjectsIDs.add(projectID);
So i get the exception Unhandled Exception: Unsupported operation: Cannot add to a fixed-length list
i believe the problem is when converting the user from json to object, because when the user is signing up the object is converted to json and stored in the database and the user will be automatically signed in using the object before converting.
void createUser(String email, String password, String username, String name, String birthDate) async {
try {
// Check first if username is taken
bool usernameIsTaken = await UserProfileCollection()
.checkIfUsernameIsTaken(username.toLowerCase().trim());
if (usernameIsTaken) throw FormatException("Username is taken");
// Create the user in the Authentication first
final firebaseUser = await _auth.createUserWithEmailAndPassword(
email: email.trim(), password: password.trim());
// Encrypting the password
String hashedPassword = Password.hash(password.trim(), new PBKDF2());
// Create new list of project for the user
List<String> userProjects = new List<String>();
// Create new list of friends for the user
List<String> friends = new List<String>();
// Creating user object and assigning the parameters
User _user = new User(
userID: firebaseUser.uid,
userName: username.toLowerCase().trim(),
email: email.trim(),
password: hashedPassword,
name: name,
birthDate: birthDate.trim(),
userAvatar: '',
userProjectsIDs: userProjects,
friendsIDs: friends,
);
// Create a new user in the fire store database
await UserProfileCollection().createNewUser(_user);
// Assigning the user controller to the 'user' object
Get.find<UserController>().user = _user;
Get.back();
} catch (e) {
print(e.toString());
}}
When the user is signed off then he signs in and try to make operation on the user object, here comes the problem some of the properties (the List type) can't be used.
This code creates project and add projectID to the user's list
Future<void> createNewProject(String projectName, User user) async {
String projectID = Uuid().v1(); // Project ID, UuiD is package that generates random ID
// Add the creator of the project to the members list and assign him as admin
var member = Member(
memberUID: user.userID,
isAdmin: true,
);
List<Member> membersList = new List();
membersList.add(member);
// Save his ID in the membersUIDs list
List <String> membersIDs = new List();
membersIDs.add(user.userID);
// Create chat for the new project
var chat = Chat(chatID: projectID);
// Create the project object
var newProject = Project(
projectID: projectID,
projectName: projectName,
image: '',
joiningLink: '$projectID',
isJoiningLinkEnabled: true,
pinnedMessage: '',
chat: chat,
members: membersList,
membersIDs: membersIDs,
);
// Add the new project ID to the user's project list
user.userProjectsIDs.add(projectID);
try {
// Convert the project object to be a JSON
var jsonUser = user.toJson();
// Send the user JSON data to the fire base
await Firestore.instance
.collection('userProfile')
.document(user.userID)
.setData(jsonUser);
// Convert the project object to be a JSON
var jsonProject = newProject.toJson();
// Send the project JSON data to the fire base
return await Firestore.instance
.collection('projects')
.document(projectID)
.setData(jsonProject);
} catch (e) {
print(e);
}}
Here where the exception happens only when the user signs off then signs in, but when he signed up for the first time there will be no exception.
// Add the new project ID to the user's project list
user.userProjectsIDs.add(projectID);
The sign in function
void signIn(String email, String password) async {
try {
// Signing in
FirebaseUser firebaseUser = await _auth.signInWithEmailAndPassword(email: email.trim(), password: password.trim());
// Getting user document form firebase
DocumentSnapshot userDoc = await UserProfileCollection().getUser(firebaseUser.uid);
// Converting the json data to user object and assign the user object to the controller
Get.find<UserController>().user = User.fromJson(userDoc.data);
print(Get.find<UserController>().user.userName);
} catch (e) {
print(e.toString());
}}
I think the problem caused by User.fromJson
why it makes the array from the firestore un-modifiable ?
The user class
class User {
String userID;
String userName;
String email;
String password;
String name;
String birthDate;
String userAvatar;
List<String> userProjectsIDs;
List<String> friendsIDs;
User(
{this.userID,
this.userName,
this.email,
this.password,
this.name,
this.birthDate,
this.userAvatar,
this.userProjectsIDs,
this.friendsIDs});
User.fromJson(Map<String, dynamic> json) {
userID = json['userID'];
userName = json['userName'];
email = json['email'];
password = json['password'];
name = json['name'];
birthDate = json['birthDate'];
userAvatar = json['UserAvatar'];
userProjectsIDs = json['userProjectsIDs'].cast<String>();
friendsIDs = json['friendsIDs'].cast<String>();
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userID'] = this.userID;
data['userName'] = this.userName;
data['email'] = this.email;
data['password'] = this.password;
data['name'] = this.name;
data['birthDate'] = this.birthDate;
data['UserAvatar'] = this.userAvatar;
data['userProjectsIDs'] = this.userProjectsIDs;
data['friendsIDs'] = this.friendsIDs;
return data;
}
}
Just add the growable argument..
If [growable] is false, which is the default, the list is a fixed-length list of length zero. If [growable] is true, the list is growable and equivalent to [].
final growableList = List.empty(growable: true);
this works for me:
list = list.toList();
list.add(value);
Your JSON decoding is likely returning fixed-length lists, which you're then using to initialize userProjectsIDs in the User class. This prevent you from adding additional elements.
Change the following from the fromJson constructor:
userProjectsIDs = json['userProjectsIDs'].cast<String>();
to
userProjectsIDs = List.of(json['userProjectsIDs'].cast<String>());

.Net Core Identity seed data: unable to login using credentials seeded

I have my Initialiser setup and everything seems to run correctly and all the details are saved to the database but when I try to log in it via the webapp it fails everytime. When I run the debugger in the login controller it returns {Failed} after this is hit:
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
Initialiser:
public class DbInitialiser : IDbInitialiser
{
private readonly ApplicationDbContext _db;
private readonly UserManager<IdentityUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public DbInitialiser(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager, ApplicationDbContext db)
{
_db = db;
_userManager = userManager;
_roleManager = roleManager;
}
public void Initialise()
{
try
{
if (_db.Database.GetPendingMigrations().Count() > 0)
{
_db.Database.Migrate();
}
}
catch (Exception ex)
{
}
if (_db.Roles.Any(r => r.Name == "Admin")) return;
_roleManager.CreateAsync(new IdentityRole("Admin")).GetAwaiter().GetResult();//makes sure this executes before proceceding with anything else
_roleManager.CreateAsync(new IdentityRole("Manager")).GetAwaiter().GetResult();
_userManager.CreateAsync(new Employee
{
UserName = "Admin",
Email = "admin#gmail.com",
EmailConfirmed = true,
TwoFactorEnabled = false,
PhoneNumberConfirmed = true
//can set other properties, this is for the initial setup
}, "Abc123!Abc123!").GetAwaiter().GetResult();
IdentityUser user = _db.Users.Where(u => u.Email == "admin#gmail.com").FirstOrDefault();
_userManager.AddToRoleAsync(user, "Admin").GetAwaiter().GetResult();
}
(My Employee class extends IdentityUser)
I have checked all my password requirements as mentioned in other similar posts so I know it isnt to do with that and when I check in SSMS all the data for the user is there in aspnetusers so I am not sure why it wont let me login to the admin user that is seeded
When I run the debugger in the login controller it returns {Failed}
In the source code of SignInManager<TUser>.PasswordSignInAsync method, we can find it would check the user based on the provided userName.
public virtual async Task<SignInResult> PasswordSignInAsync(string userName, string password,
bool isPersistent, bool lockoutOnFailure)
{
var user = await UserManager.FindByNameAsync(userName);
if (user == null)
{
return SignInResult.Failed;
}
return await PasswordSignInAsync(user, password, isPersistent, lockoutOnFailure);
}
In your code, you set UserName with "Admin" that is not same as Email with "admin#gmail.com". If user login with email account, the code snippet var user = await UserManager.FindByNameAsync(userName); would return null, which cause the issue.
To fix it, you can try to set UserName with same value of Email (admin#gmail.com). Or modify the login code logic to find user by the Email, then sign in that user with password, like below.
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var user = await _userManager.FindByEmailAsync(Input.Email);
//var istrue = await _userManager.CheckPasswordAsync(user, Input.Password);
var result = await _signInManager.PasswordSignInAsync(user, Input.Password, Input.RememberMe, lockoutOnFailure: true);
//var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);

Flutter floor database Future bool action in DAO file?

While using floor database can we set an action which will turn as a boolean like below example?
Future<bool> isItAdded(in user_id) async{
var = dbClient = await db;
List<Map> list = await dbClient.rawQuery{SELECT * FROM Users WHERE user_id}, [user_id]}
return list.lenght > 0 ? true : false
}
You may write DAO object:
#dao
abstract class UsersDao {
#Query('SELECT * FROM users WHERE user_id = :userId')
Future<List<User>> findUsers(Int userId);
}
Before that you neeed to create entity:
#Entity(tableName: 'users')
class User{
#PrimaryKey(autoGenerate: true)
final int id;
#ColumnInfo(name: 'user_id')
final int userId;
}
Also you need to create database access object:
part 'database.g.dart'; // the generated code will be there
#Database(version: 1, entities: [User])
abstract class AppDatabase extends FloorDatabase {
UsersDao get usersDao;
}
Then generate additional code by command:
flutter packages pub run build_runner build
And then write check function inside database access object:
Future<bool> isItAdded(in user_id) async {
List<User> list = await usersDao.findUsers(user_id);
return list.lenght > 0;
}
The best solution is not to add user_id column and use only unique id column.

ASP.NET Core encryption and SQL Server

I am creating a default user for my system. However I am creating through SQL Server database.
I use ASP.NET Core and Entity Framework to handle logins, by default Entity Framework creates a table called AspNetUsers; this table has a column called PasswordHash, I believe the encryption used is of the Hash type.
I am entering the password on this user by the database as follows:
DECLARE #HashThis nvarchar(4000);
SET #HashThis = CONVERT(nvarchar(4000),'Administrador');
SELECT HASHBYTES('SHA1', #HashThis)
UPDATE AspNetUsers
SET PasswordHash = HASHBYTES('SHA1', #HashThis),
SecurityStamp = '0b12450e-016d-4cd6-af7b-fa6d2198586f',
ConcurrencyStamp = 'a63a5236-4020-4f69-93b1-9f077ba014cd',
UserName = 'administrador#administrador.com.br'
But the password column is getting strange characters in Japanese, it follows the image:
The biggest issue and when I log in ASP.NET Core, only the password invalidates.
How can I do to bypass this?
Observation: when I create the user through ASP.NET Core, it works normally.
Here is one example how you can seed you user:
In you SecurityDbContext you can create following methods (I added SeedRoles in case you need them):
public static async Task Seed(IServiceProvider serviceProvider)
{
await SeedRoles(serviceProvider);
await SeedUsers(serviceProvider);
}
Seed Roles:
public static async Task SeedRoles(IServiceProvider serviceProvider)
{
RoleManager<ApplicationRole> roleManager = serviceProvider.GetRequiredService<RoleManager<ApplicationRole>>();
string[] roles = ...;
foreach(var role in roles)
{
ApplicationRole appRole = await roleManager.FindByNameAsync(role);
if (appRole == null)
{
await roleManager.CreateAsync(new ApplicationRole(role));
}
}
}
Seed User:
public static async Task SeedUser(IServiceProvider serviceProvider, UserManager<ApplicationUser> userManager, string email, string password, string roleName = "")
{
string userName = roleName;
ApplicationUser user = await userManager.FindByNameAsync(userName);
if (user == null)
{
// Create user account if it doesn't exist
user = new ApplicationUser
{
UserName = userName,
Email = email
};
IdentityResult result = await userManager.CreateAsync(user, password);
// Assign role to the user
if (result.Succeeded)
{
user = await userManager.FindByNameAsync(userName);
}
}
if (user != null && roleName.Length > 0)
{
await userManager.AddToRoleAsync(user, roleName);
}
}
From SeedUsers method, just call SeedUser as many times as you need.
And then just simply call Seed method from Startup.cs Configure method:
SecurityDbContextSeed.Seed(app.ApplicationServices).Wait();

upload multiple files , enctype=“multipart/form-data”

I want to upload multiple files to the controller but its taking only one.
I am using multipart for file transfer.
How to get the multiple files to the controller side.
I am not able to access bytes and filename. Its throwing errors,
#RequestMapping(value = "/home/step38/uploadReport", method = RequestMethod.POST)
public ModelAndView uploadReport(
#RequestParam(value = "fileName") List<MultipartFile> files,
#RequestParam(value = "pLogId") String pLogId,
HttpServletRequest request, HttpSession session)
{
int applicationNameId = 0;
String fileName;
String typeOption = "Raw Particle Data";
for(MultipartFile file:files)
fileName = file.getOriginalFilename();
logger.debug("step3.1 upload particle count -- Start");
ModelAndView modelAndView = createModelAndView(ToogleStep.step38);
setCurrentStep(session, modelAndView, ToogleStep.step38);
String view = "redirect:/home/step38";
modelAndView.setViewName(view);
try
{
User user = (User) session.getAttribute(Constants.USER_DB);
Project current_project = (Project) session.getAttribute(Constants.PROJECT);
Credential credential = (Credential) session.getAttribute(Constants.AUTH_USER);
boolean checkOK = true;
if (current_project != null && SystemUtils.projectEditable(current_project, credential))
{
long projectId = current_project.getId();
if(checkOK)
{
byte[] bytes = file.getBytes();
HashMap<String,String> options= new HashMap<String,String>();
//added pLogId in the options(this will contain demoToogleFileInfoId)
options.put(ToogleReportDataConstants.TTL_PROCESS_LOG_ID_OPTION,pLogId);
String toogleFileId = reportService.uploadReport(user, projectId, fileName, typeOption, bytes, applicationNameId, options);
}
}
}
You are not looping through at the right location.
try looping it after you have your modelAndView(view)
int applicationNameId = 0;
String typeOption = "Raw Particle Data";
ModelAndView modelAndView = createModelAndView(ToogleStep.step38);
setCurrentStep(session, modelAndView, ToogleStep.step38);
String view = "redirect:/home/step38";
modelAndView.setViewName(view);
// upload multiple files.
for(MultipartFile file:files){
String fileName= file.getOriginalFilename();
and then you will be able to access bytes and filename. Give this a try.
Atleast by looking at your problem I can suggest and if you can give more specific error, I can help.

Resources