Which the best way to pass values of dynamically created checkboxes and groupboxes - c#-3.0

I am standing on a cross road with a doubt which way is the correct way. As you all are seeing the image Groupbox and CheckBoxes all are dynamically created. What I am confused about If user select Sun Tue and Fri from XII2013SIF01 and Mon Tue Wed and Thr from XII2013SIG02 how I can pass these check boxes value to Step 3 Form on button click. In Step 3 form I need to identify days by their Group name because according to that processing will be done. What technique will be best for me please give some guidance/suggestion or advice.

The best is to create a class that will contain the data collected in this step (or in the whole sequence of steps). On that class, this specific list of choices can be represented as HashSet<DayOfWeek> property for each section.
Example with class per step:
public class Step2Selection {
public Step2Selection() {
XII2013SIF01 = new HashSet<DayOfWeek>();
XII2013SIG02 = new HashSet<DayOfWeek>();
}
public HashSet<DayOfWeek> XII2013SIF01 { get; private set; }
public HashSet<DayOfWeek> XII2013SIG02 { get; private set; }
}
Alternatively, if the number of sections can grow you may use a dictionary or list of custom section classes.
For your specific case, you can also use a dictionary without custom classes:
IDictionary<string, HashSet<DayOfWeek>> // where dictionary keys are "XII2013SIF01", etc
Though it will not scale well for any additional complexity.

Related

Hibernate Search: Find in list of intervals

I am using Hibernate Search 6.x within my Spring Boot application. I got an indexed entity with a set of date intervals.
#Indexed
public class ProudParent {
...
#IndexedEmbedded(includePaths = {"start", "end"})
Set<DateInterval> parentalLeaves;
}
And the class DateInterval looks like
#Embeddable
public class DateInterval {
#GenericField
LocalDate start;
#GenericField
LocalDate end;
}
That is my range query to search for all proud parents which were in parental leave on a specific date:
bool.must(factory.range().field("parentalLeaves.start").lessThan(date));
bool.must(factory.range().field("parentalLeaves.end").greaterThan(date));
Now the problem is that it finds proud parents which first parental leave was before date and the last parental leave was after date. So it does not search in the "same" date interval.
Can someone give me a hint of what I'm doing wrong?
Regards, Rokko
#IndexedEmbedded will "flatten" the object structure by default, so all starts and ends are mixed together in the index, with no way to know which end matches which start.
You can read more about this in this section of the reference documentation. In short, this default is mainly for performance, because preserving the object structure can be (very) costly on large indexes, and is usually not necessary.
The solution, in your case, would be to use a NESTED structure:
#Indexed
public class ProudParent {
...
#IndexedEmbedded(includePaths = {"start", "end"}, structure = ObjectStructure.NESTED)
Set<DateInterval> parentalLeaves;
}
Then make sure to tell Hibernate Search you want the matches on start and end to be on the same parentalLeave, using a nested predicate:
bool.must(factory.nested().objectField("parentalLeaves")
.nest(factory.bool()
.must(factory.range()
.field("parentalLeaves.start")
.lessThan(date))
.must(factory.range()
.field("parentalLeaves.end")
.greaterThan(date)))
Don't forget to reindex your data before testing.
Side note: the syntax should be slightly more convenient with the upcoming Hibernate Search 6.2.0.Alpha2 (not yet released):
bool.must(factory.nested("parentalLeaves")
.add(factory.range()
.field("parentalLeaves.start")
.lessThan(date))
.add(factory.range()
.field("parentalLeaves.end")
.greaterThan(date)))
Other side note: hopefully one day we'll have date ranges as a primitive type in Hibernate Search (HSEARCH-4199) and this whole discussion will become irrelevant :)

Mongoose: virtual properties that depend on other virtual properties

In mongoose, is it possible to have a virtual property that depends on another virtual property? For example:
If I have the properties squaresAmnt, trianglesAmnt, appleAmnt, and pearAmnt (all of type Number) and then create two virtual properties:
mySchema.virtual('totalShapes').get(function() {
return this.squaresAmnt + this.trianglesAmnt;
});
mySchema.virtual('totalFruit').get(function() {
return this.appleAmnt + this.pearAmnt;
});
Is it possible to create a 3rd virtual property total using the sum of totalShapes + totalFruit instead of the 4 properties on their own? For my very specific use case, I'd like to avoid the later.
Yes you can refer to them with this. eg. this.totalShapes.
One thing to be careful of - if the person writing the query uses $select the fields your virtuals rely on might not exist; fields not returned by the query aren’t available to the virtuals. So be defensive and check for needed fields in your virtual implementations.

set a field in pivot table whenever a record insert or update happens in laravel

OK, recently I am implementing an RBAC based system in laravel.
I have these two classes as my models:
class User extends Authenticatable
{
public function roles(){
return $this->belongsToMany(\App\Role::class, 'user_role', 'user_id', 'role_id')->withPivot('is_expired', 'assigned_at', 'expire_at');
}
}
class Role extends Model
{
public function users(){
return $this->belongsToMany(\App\User::class, 'user_role', 'role_id', 'user_id')->withPivot('is_expired', 'assigned_at', 'expire_at');
}
}
it works fine BUT, I want to set a default value for the expire_at attribute of the pivot table based on an attribute of the Role model. for example I have a period attribute on Roles table, and its a number representing number of months.
So i want when a role assigned to a user (inserted in pivot table) the value of expire_at set to currentDatetime + thePeriodNum months and save in the pivot table.
how can I achieve this?
I have tried laravel custom pivot class and mutators but it seems not working or I did something wrong.
somebody mentioned that the mutators dont get triggered when using attach()/detach() methods so I think even if it was working i could not see the difference.
Someone mentioned its possible with observers but I have no Idea what is an observer im noob.
So thats all, it would be really good for me if anybody could help me through this mess I'm in right now.
Thanks in advance.
It is possible to attach the new role and set the expires_at column at the same time. This would avoid needing to use observers (listeners of model events) within your code.
The code would look like the following:
$role = Role::find($roleId);
$expireAt = now()->addMonths($role->period)->toDateTimeString();
// or Carbon::now()->addMonths($role->period)->toDateTimeString();
User::find($userId)->roles()->attach($role->id, ['expire_at' => $expireAt]);
Here, the role is found. A timestamp is created by taking the current time, adding the addition months based on the role's period (this should be an integer value).
Finally, this is added to the attachment of the role to the user.
Add as a model method
This can all be added as a function/method on the User model which would clean up the code into one action, ->addRole($roleId):
// Within App\User.php
public function addRole($roleId)
{
$role = \App\Role::find($roleId);
$expiresAt = now()->addMonths($role->period)->toDateTimeString();
$this->roles()->attach($role->id, [ 'expire_at' => $expiresAt ]);
}
This can then be called with the following:
$user = User::find($id);
$user->addRole($roleId);
I hope this help.

How to handle DataAnnotation RequiredField(ErrorMessage...) using EntityTypeConfiguration

I have EF poco classproperty which has the DataAnnotatins. They include the FK, mandatory, maxlength conditions.
[Required(ErrorMessage = "Company name cannot be empty")]
[StringLength(128, ErrorMessage = "The CompanyName should be less than 128 characters or less.")]
[Index(IsUnique = true)]
public string CompanyName { get; set; }
I am trying to move all these into EntityTypeConfigurations and am struggling to move the ErrorMessages.
Can any one give me a pointer on how to get this done>
As you can read here, constraints configured by fluent mappings will by evaluated only in the context. They don't trickle through to the UI, as data annotations do (when used with the correct framework). So the EF team figured it wouldn't make sense to craft a user-friendly error message here. The validation will just throw a standard DbValidationError saying something like
The field Name must be a string or array type with a maximum length of '128'
So you need the annotations if you want your own custom messages.

How to get available classes at runtime

I would like to poll a class and have it return all available subclasses in a way I can then address them. It can return an array, a dictionary, or something else. As long as I can then loop through the set of them and read properties or call functions from each.
Scenario:
I want to create a form where the user inputs the details of a series of events. Then I read the form and output a report. Each kind of event has a ".Name", but a different set of inputs (FormOptions) and methods (FormatOutput) to create an output. Right now this is implemented with a complex form and a script that runs after the user submits the form.
The trouble is that every time I add an option to the form, I have to change code in several different places. In the interest of making my code easier to maintain, I would like to contain all the code for each event type in a Class, then build the form based on the available Classes.
So as an example, I'm building an itinerary from a collection of Meeting and Travel objects:
Class Itinerary
Class Event
Public Property Get Name()
Name = "Meeting"
End Property
Public Function FormOptions(id)
Form Options = "<div id="& id &">form code for Meeting options</div>"
End Function
Public Sub FormatOutput(Time, Title, Location)
'Make a fancy meeting entry
End Sub
End Class
Class Travel
Public Property Get Name()
Name = "Travel"
End Property
Public Function FormOptions(id)
Form Options = "<div id="& id &">form code for Travel options</div>"
End Function
Public Sub FormatOutput(StartTime, EndTime, Origin, Destination)
'Make a fancy travel entry
End Sub
End Class
End Class
When the script runs it creates a form where the user can add a series of events. Each time the user chooses between "Meeting" and "Travel" then fills out the options for that event type. At the end, they push a button and the script makes a pretty document listing all the user's inputs.
At some point in the future, I will want to add a new kind of event: lodging.
Class Lodging
Public Property Get Name()
Name = "Lodging"
End Property
Public Function FormOptions(id)
Form Options = "<div id="& id &">form code for Lodging options</div>"
End Function
Public Sub FormatOutput(Date, Location)
'Make a fancy Lodging entry
End Sub
End Class
How do I setup my Itinerary class so that it automatically recognizes the new class and can return it as an available event type? I can think of several ways of doing this, but they all involve keeping an index of the available classes separate from the actual classes, and I'm trying to minimize the number of places I have to change code when I add new event types.
I am very purposely not including any details on how I build the form since at this point I'm open to anything. Also, please be gentle with references to "inheritance", "extensibility", or "polymorphism". I'm a just a scripter and these OOP concepts are still a bit foreign to me.
I don't think this is possible, but one way to come close to this would be to have a unique list of class names -- the simplest would be to have a global dictionary.
You can get a list of classes by reading the Keys collection of the dictionary.
I don't think VBScript supports references to classes, so when the user chooses one of the types use Eval to create an instance of the appropriate class.
Dim ClassList
Set ClassList = CreateObject("Scripting.Dictionary")
'on type selection:
Function GetItineraryInstance(className)
Set GetItineraryInstance = Eval("New " & className)
End Function
ClassList("Travel") = 1
Class Travel
'methods
End Class
At least the class registration can be kept together with the class definition.