how to pass two or three values to fluent validation Must function? - fluentvalidation

my code :
public class MandatoryValidator : AbstractValidator<Entity.EigenSchema.AttributeSet>
{
private string Keyvalue = string.Empty;
public MandatoryValidator(string keyvalue)
{
Keyvalue = keyvalue;
RuleFor(record => record.Mandatory).Must(Mandatory);
}
protected bool Mandatory(bool val)
{
if (val)
{
if(Keyvalue!=null || Keyvalue!="")
{
return true;
}
return false;
}
else
{
return true;
}
}
}
this checks if the field is mandatory or not.
Now I need a function that takes more than one parameter to mandatory function, something like this..
protected bool Mandatory(bool val, string strval, int val)
{
//strval = record.LocalUnique
//val = record.Size
}

You can do it like this
RuleFor(record => record.Mandatory).Must(mandatoryField => Mandatory(mandatoryField, Keyvalue, 012));
You can also
RuleFor(record => record).Must(WholeObject=> Mandatory(WholeObject))
.WithName("Mandatory");
//.WithName(x => x.MandatoryFieldName) optional
//and now
private bool MandatorChecker(MyRecordType obj)
{
strval = obj.LocalUnique;
val = obj.Size;
}
This one will use the name you provided if this rule breaks.

Related

Make [FromQuery] bool testValue accept 'testValue', 'test_value' and 'test-value'

In ASP NET 6+ I need to make [FromQuery] replace underscores _ and minuses - before matching names.
So I want to plumb ASP to allow [FromQuery] bool testValue to be equivalent to all at once:
[FromQuery(Name="testValue")] bool testValue
[FromQuery(Name="test-value")] bool testValue
[FromQuery(Name="test_value")] bool testValue
Is there a place in the pipeline I can get in before names are compared (to remove _ and - myself)?
My current solution is just to replace the Request.Query with my own doctored QueryCollection that duplicates variables with fixed names in a middleware.
But I'm looking for any answer that's more... unhacky?!
public class RequeryMiddleware : IMiddleware
{
private static readonly char[] separators = new[] { '_', '-', '.', '|' };
private static bool Requery(ref string name)
{
bool changed = false;
if (name.IndexOfAny(separators) >= 0)
{
name = string.Concat(name.Split(separators, StringSplitOptions.None));
changed = true;
}
return changed;
}
public Task InvokeAsync(HttpContext context, RequestDelegate next)
{
Dictionary<string, StringValues> mods = new(
StringComparer.OrdinalIgnoreCase
);
foreach (var item in context.Request.Query)
{
string key = item.Key;
if (Requery(ref key))
{
mods.Add(key, item.Value);
}
}
if (mods.Count > 0)
{
Dictionary<string, StringValues> query = new(
context.Request.Query.Count + mods.Count
, StringComparer.OrdinalIgnoreCase
);
foreach (var item in context.Request.Query)
{
query.Add(item.Key, item.Value);
}
foreach (var mod in mods)
{
// if we get here it's bad...
query.TryAdd(mod.Key, mod.Value);
}
// replace the Query collection
context.Request.Query = new QueryCollection(query);
// change the QueryString too
QueryBuilder qb = new(context.Request.Query);
context.Request.QueryString = qb.ToQueryString();
}
return next(context);
}
}

null userId, Unhandled Exception: Null check operator used on a null value

I have an issue with userId in Habits table. it is a foreign key from id in Users Table. but I keep getting the error "Unhandled Exception: Null check operator used on a null value " from AddHabitDialogController class.
obviously userId should never be null. where is the issue? how can I solve it?
if more code is needed you can check : https://github.com/sarasoltan/habit_tracker
Users Table:
class UsersTable {
static const String tableName = 'Users';
static const String id = 'id';
static const String email = 'email';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$email text not null unique);''';
#override
String toString() => 'Person, ID: $id, email: $email';
#override
bool operator ==(covariant Users other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
Habits table:
class HabitsTable {
static const String tableName = 'Habits';
static const String id = 'id';
static const String userId = 'userId';
static const String text = 'text';
static const String emoji = 'emoji';
static const String period = 'period';
static const String startPeriod = 'startPeriod';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$userId integer not null,
$text text not null,
$emoji text not null,
$period text not null,
$startPeriod integer,
FOREIGN Key($userId) REFERENCES ${UsersTable.tableName}(${UsersTable.id}));''';
User model class:
class Users {
late final int id;
late String email;
Users({
required this.id,
required this.email,
});
Users.fromDb(Map<String, dynamic> map) {
id = map[UsersTable.id];
email = map[UsersTable.email];
}
}
Habit model class:
class Habit {
late final int id;
late final int userId;
late String text;
late String emoji;
late final List<int> period;
late final DateTime? startPeriod;
Habit(
{
//required this.id,
required this.userId,
required this.text,
required this.emoji,
required this.period,
this.startPeriod});
Habit.fromDb(Map<String, dynamic> map) {
id = map[HabitsTable.id] as int;
userId = map[HabitsTable.userId] as int;
text = map[HabitsTable.text] as String;
emoji = map[HabitsTable.emoji];
period = (jsonDecode(map[HabitsTable.period]) as List<dynamic>)
.map((e) => e as int)
.toList();
if (map[HabitsTable.startPeriod] != null) {
startPeriod =
DateTime.fromMillisecondsSinceEpoch(map[HabitsTable.startPeriod]);
} else {
startPeriod = null;
}
}
Map<String, dynamic> toDb() {
Users? owner;
return {
//HabitsTable.id: id,
HabitsTable.userId: owner!.id,
HabitsTable.text: text,
HabitsTable.emoji: emoji,
HabitsTable.period: jsonEncode(period),
HabitsTable.startPeriod: startPeriod?.millisecondsSinceEpoch
};
}
AddHabitDialogController(error):
class AddHabitDialogController {
Users? owner;
//final user = FirebaseAuth.instance.currentUser;
//String get owneruserId => AuthService.firebase().currentUser!.id;
final List<bool> period = [true, true, true, true, true, true, true];
int? id;
int? userId;
String? emoji;
String? text;
StartPeriod startPeriod = StartPeriod.none;
final StreamController<bool> _addBtnEnabledCtrl = StreamController();
Stream<bool> get addBtnEnabled => _addBtnEnabledCtrl.stream;
final StreamController<StartPeriod> _selectedStartPeriodCtrl =
StreamController();
Stream<StartPeriod> get selectedStartPeriod =>
_selectedStartPeriodCtrl.stream;
final StreamController<bool> _loadingCtrl = StreamController();
Stream<bool> get loading => _loadingCtrl.stream;
void changePeriodValue(int index, bool newValue) {
period[index] = newValue;
_updateAddBtnEnabledState();
}
void changeTextValue(String newValue) {
text = newValue;
_updateAddBtnEnabledState();
}
void changeEmojiValue(String newEmoji) {
emoji = newEmoji;
_updateAddBtnEnabledState();
}
void changeStartPeriod(StartPeriod newValue) {
startPeriod = newValue;
_selectedStartPeriodCtrl.add(startPeriod);
}
Future<void> addHabit(BuildContext context) async {
_loadingCtrl.add(true);
final dataService = GetIt.I.get<DataService>();
final List<int> forPeriod = [];
for (int i = 0; i < period.length; i++) {
if (period[i]) {
forPeriod.add(i + 1);
}
}
final habit = Habit(
//id: id!,
userId: owner!.id, //error from here
emoji: emoji!,
text: text!,
period: forPeriod,
startPeriod: _calculateStartPeriodDateTime());
await dataService.addHabit(habit);
_loadingCtrl.add(false);
Navigator.of(context).pop();
}
void _updateAddBtnEnabledState() {
_addBtnEnabledCtrl.add((text?.isNotEmpty ?? false) &&
(emoji?.isNotEmpty ?? false) &&
period.where((e) => e).isNotEmpty);
}
DateTime? _calculateStartPeriodDateTime() {
final now = DateTime.now();
switch (startPeriod) {
case StartPeriod.today:
return DateTime(now.year, now.month, now.day);
case StartPeriod.thisMonth:
return DateTime(now.year, now.month);
case StartPeriod.thisYear:
return DateTime(now.year);
case StartPeriod.none:
default:
return null;
}
}
void dispose() {
_addBtnEnabledCtrl.close();
_loadingCtrl.close();
_selectedStartPeriodCtrl.close();
}
}
enum StartPeriod { none, today, thisMonth, thisYear }
Because the local variable of AddHabitDialogController owner can't be referenced before it is declared
class AddHabitDialogController {
Users? owner; // -> you did not assign this owner?

Dart == operator and identical function does not yield true for 2 objects with same content

So I have been trying to compare two objects by their fields.
I have noticed there is no equals method in dart. But there are the identical function and the == operator.
I can't seem to understand why there is no equals method. What if I want to do this?
class Name {
String fname;
String lname;
String get firstName => this.fname;
void set firstName(String fname) => this.fname = fname;
String get lastName => this.lname;
void set lastName(String lname) => this.lname = lname;
Name({this.fname, this.lname});
#override
String toString() {
return this.firstName + " " + this.lastName;
}
bool equals(Name n2) {
return this.firstName == n2.firstName && this.lastName == n2.lastName
? true
: false;
}
}
void main(List<String> args) {
Name n1 = new Name();
n1.firstName = "James";
n1.lastName = "Bond";
Name n2 = new Name();
n2.firstName = "James";
n2.lastName = "Bond";
print(n1.equals(n2)); // true
print(identical(n1, n2)); // false
print(n1 == n2); // false
}
What can I do instead of making my own equals. Or does dart expect you to do this manually.
identical will not return true even if the first name and last name of the two objects you are comparing are the same. That's because they are not the same instances. Each instance has its own identity and own hashcode.
You could override the == operator and the hashcode. Then you will be able to compare two different instances. The Equatable-Package already does that for you so you can use the == operator two compare two different instances: https://pub.dev/packages/equatable
You can write code just like this
#override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType)
return false;
/// do smth
}
#override
int get hashCode {
}

How to map collections in proper way

What is the best way for mapping collection of objects in NHibernate?
Now I am using bags, but maybe another approach can be more efficient?
Before wore Bag and ClassMapping, something very similar to this:
Bag(am => am.AlumnoMateriaId, map =>
{
map.Table("Calificacion");
map.Cascade(Cascade.None);
map.Key(k =>
{
k.Column("AlumnoId");
k.ForeignKey("FK_Calificacion_AlumnoMateria");
});
}, rel => rel.ManyToMany(p => p.Column("AlumnoId")));
Now Use the NHibernate.Mapping.Attributes, and a class would look like:
using NHMA = NHibernate.Mapping.Attributes;
[NHMA.Class(Table = " Calificacion ")]
public class Calificacion
{
[NHMA.Id(0, Name = "id", TypeType = typeof(Int32), Column = "Id", Access = "field")]
[NHMA.Generator(1, Class = "native")]
public Int32 id;
public virtual Int32 Id
{
get { return id; }
set { id = value; }
}
[NHMA.ManyToOne(2, Name = "calificacion", Access = "field", Column = "CalificacionID",
Class = "Calificacion", ClassType = typeof(Calificacion),
ForeignKey = "FK_Calificacion_Alumno", NotNull = false)]
private Calificacion calificaion;
public virtual Calificacion Calificaion
{
get { return calificaion; }
set { calificaion = value; }
}
[NHMA.Property(Name = "nombre", Access = "field", Column = "Nombre", Length = 50)]
private string nombre;
public virtual string Nombre
{
get { return nombre; }
set { nombre = value; }
}
}

two way mapping

Is any way, how to create two classes, which will be referenced both way and will use only one FK? This interest me in One-to-One as like as One-to-Many cases.
f.e.:
Class First: Entity
{
Second second;
}
Class Second: Entity
{
First first;
}
String TwoWayReference()
{
First Fir = new First();
Second Sec = new Second();
Fir.second = Sec; // I need it is equivalent to: Sec.first = Fir;
if (Sec.first == Fir)
return "Is any way how to do this code works and code return this string?";
else
return "Or it is impossible?"
}
simplest would be
class First : Entity
{
private Second second;
public virtual Second Second
{
get { return this.second; }
set {
if (value != null)
{
value.First = this;
this.second = value;
}
}
}
}
class Second : Entity
{
private First first;
public virtual First First
{
get { return this.first; }
set {
if (value != null && value.Second != this)
{
value.Second = this;
this.first = value;
}
}
}
}