How to build QueryOver with simple bool condition? - queryover

one very simple question I believe, I just dont get it:
This method throws an exception:
public void SetState( bool active )
{
Query.Where( q => q.Inactive == !active );
}
Cannot interpret member from Not(value(Business.Filter.EmployeeFilter+<>c__DisplayClass12).active)
I simply want to attach a bool condition to my query: "WHERE Inactive = true/false"
Thanks in advance

this works, but still strange:
public void SetState( bool inactive )
{
Query.Where( q => q.Inactive == inactive );
}

Related

Entity state is DETACHED when it should be Modified

I am trying to modify data and save changes to my database using EFCore 3.1.
but my modifications are not being saved to the database, so after further investigation I found out that after I pull my entity from the context, its state is DETACHED instead of ATTACHED,
so that's why the changes aren't being saved, because they're not tracked in the first place.
I couldn't figure out why this is happening, I made sure that I did not add AsNoTracking() when getting the entity.
Here are my classes and methods:
public class UserSettingsDataAccess : IUserSettingsDataAccess
private readonly NotificationDBContext _context;
private readonly IReminderDatesDataAccess _reminderDatesDataAccess;
public UserSettingsDataAccess(NotificationDBContext context, IReminderDatesDataAccess reminderDatesDataAccess)
{
_context = context;
_reminderDatesDataAccess = reminderDatesDataAccess;
}
public bool ToggleRemindersForAppointmentAsync(int appointment_id)
{
Appointments appointment = _appointmentDataAccess.GetByIdWithReminders(appointment_id);
if (appointment == null || appointment.Reminders == null)
return bool.Parse(null);
var x = _context.Entry(appointment).State;
appointment.Reminders.IsActive = !appointment.Reminders.IsActive;
var y = _context.Entry(appointment).State;
_context.SaveChanges();
var z = _context.Entry(appointment).State;
return appointment.Reminders.IsActive.Value;
}
//rest of code is omitted for brevity
}
This one uses another method to get the appointment, toggle its reminder , save changes and return the new reminder state. all of x,y,z variables have DETACHED value . when debugging
Here's the second class that contains the method that brings the appointment :
public class AppointmentDataAccess: IAppointmentDataAccess
{
private readonly NotificationDBContext _context;
public ReminderDatesDataAccess(NotificationDBContext context)
{
_context = context;
}
public Appointments GetByIdWithReminders(int appointment_id)
{
return _context.Appointments.Where(a => a.Id == appointment_id && a.DeletedAt == null)
.Include(a=>a.Reminders).FirstOrDefault();
}
}
Startup.cs :
services.AddDbContext<NotificationDBContext>(options => options
.UseSqlServer(Configuration.GetConnectionString("Database"))
, ServiceLifetime.Transient,ServiceLifetime.Transient);
and IUserSettingsDataAccess, IAppointmentDataAccess are just interfaces.
Can anyone point out why this is happening? and how to fix it? it's been driving me crazy for a good couple of hours . TIA!

Return multiple results matching

How return MULTIPLE results matching??
my method.. :
public IQueryable<Products> GetSelectProduct()
{
int[] value = GetProdutctsBascket();
return mm.getProducts().Where(p => p.Id.Equals(value));
}
how select widht array and return this ???
Try:
return mm.getProducts().Where(p => value.Contains(p.Id));
YD1m answered the question in exactly the correct way. However, I offer a small alternative - just because you can. You can use an extension method on you IEnumerable which serves the same purpose:
public static class MiscServiceTools
{
public static IEnumerable<T> WhereIn<T, TValue>(
this IQueryable<T> query,
Expression<Func<T, TValue>> selector,
params TValue[] collection) where T : class
{
if (selector == null) throw new ArgumentNullException("selector");
if (collection == null) throw new ArgumentNullException("collection");
ParameterExpression p = selector.Parameters.Single();
if (!collection.Any()) return query;
IEnumerable<Expression> equals = collection.Select(value =>
(Expression) Expression.Equal(selector.Body,
Expression.Constant(value, typeof (TValue))));
Expression body = equals.Aggregate(Expression.Or);
return query.Where(Expression.Lambda<Func<T, bool>>(body, p));
}
}
the usage would then be:
return mm.getProducts().WhereIn(p => p.Id, value);

Android, Checkboxes Randomly Checked/Unchecked in Expandable List

Using this Expandable List checkbox example code as an baseline, I am trying to save and maintain the checkbox state. However, random checkboxes are being checked and unchecked ( triggering my OnCheckedChangeListener with the new values ) when I scroll them out of sight, minimize their group, or even minimize/maximize a nearby group!
public Object getChild(int groupPosition, int childPosition) {
return colors.get( groupPosition ).get( childPosition );
}
public long getChildId(int groupPosition, int childPosition) {
return (long)( groupPosition*1024+childPosition ); // Max 1024 children per group
}
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
View v = null;
if( convertView != null ) {
v = convertView;
} else {
v = inflater.inflate(R.layout.child_row, parent, false);
}
Color c = (Color)getChild( groupPosition, childPosition );
TextView color = (TextView)v.findViewById( R.id.childname );
if( color != null ) {
color.setText( c.getColor() );
}
TextView rgb = (TextView)v.findViewById( R.id.rgb );
if( rgb != null ) {
rgb.setText( c.getRgb() );
}
CheckBox cb = (CheckBox)v.findViewById( R.id.check1 );
cb.setChecked( c.getState() );
cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
colors.get(groupPosition).get(childPosition).setState(isChecked);
context.setColorBool(groupPosition, childPosition, isChecked);
Log.d("ElistCBox2", "listitem position: " +groupPosition+"/"+childPosition+" "+isChecked);
}
});
return v;
}
I don't know what piece of code could be responsible for this, so any suggestions on what to include here are welcome. My code only differs from the original in my attempt to save the values.
my guess is that as your adapter is creating views, the check listener is being called as the checkbox view is initialized. a lot of widgets in android work like this ... the listener is called when the view is initialized.
i don't know why things work like this, but it might be to allow the client code to initialize itself in a consistent way. e.g., whether the checkbox is checked by the user or whether it is initialized as checked, run the same code.
to counteract this, you can try doing something like setting a flag in your listener class impl to allow you to ignore the first click, something like,
cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
private void first = true;
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (first) {
first = false;
return;
}
colors.get(groupPosition).get(childPosition).setState(isChecked);
context.setColorBool(groupPosition, childPosition, isChecked);
Log.d("ElistCBox2", "listitem position: " +groupPosition+"/"+childPosition+" "+isChecked);
}
});
also, ensure that you are correctly re-using convertView in your implementation of getView() in your adapter. e.g.,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.applications_item, null);
}
This is a very old question, but I struggled with the same problem so here is my answer for anybody looking:
The simplest way is to use CheckBox.onClickListener instead of onCheckedChangeListener.
This is only mildly annoying in terms of rearranging your logic, but will ensure that when the boxes are unchecked randomly (by, e.g. expanding an adjacent group) the event will not fire.
Honestly I think this should be considered a bug, even though I'm sure the behaviour can be explained from the Android source.

Using Rx in Silverlight for WCF calls doesn't work with TakeUntil

I have the following bit of code to set up my Rx hookups:
Event related definitions:
public class QueryEventArgs : EventArgs
{
public SomeParametersType SomeParameters
{
get;
set;
}
public object QueryContext
{
get;
set;
}
};
public delegate void QueryDelegate(object sender, QueryEventArgs e);
public event QueryDelegate QueryEvent;
Initialization:
queryObservable = Observable.FromEvent<QueryEventArgs>(this, "QueryEvent");
queryObservable.Subscribe((e) =>
{
tbQueryProgress.Text = "Querying... ";
client.QueryAsync(e.EventArgs.SomeParameters, e.EventArgs.QueryContext);
});
queryCompletedObservable = from e in Observable.FromEvent<QueryCompletedEventArgs>(client, "QueryCompleted").TakeUntil(queryObservable) select e;
queryCompletedObservable.Subscribe((e) =>
{
tbQueryProgress.Text = "Ready";
SilverlightClientService_QueryCompleted(e.Sender, e.EventArgs);
},
(Exception ex) =>
{
SetError("Query error: " + ex);
}
);
"client" is the WCF client and everything else is fairly self-explanatory.
The "TakeUntil" is there to stop the user stomping on himself when doing a new query while in the middle of a currently running one. However, while the code works if I remove the "TakeUntil" clause, if I put it in, the query is never completed.
Is this the correct pattern? If so, am I doing something wrong?
Cheers,
-Tim
TakeUntil terminates the subscription when a value is received from its argument, so your first queryObservable starts up the query but also terminates the subscription to the complete events.
The simpler solution is to setup an IObservable around your actual query, and then use Switch to ensure that only one query runs at a time.
public static class ClientExtensions
{
public static IObservable<QueryCompletedEventArgs> QueryObservable(
this QueryClient client,
object[] someParameters, object queryContext)
{
return Observable.CreateWithDisposable<QueryCompletedEventArgs>(observer =>
{
var subscription = Observable.FromEvent<QueryCompletedEventArgs>(
h => client.QueryCompleted += h,
h => client.QueryCompleted -= h
)
.Subscribe(observer);
client.QueryAsync(someParameters, queryContext);
return new CompositeDisposable(
subscription,
Disposable.Create(() => client.Abort())
);
});
}
}
Then you can do this:
queryObservable = Observable.FromEvent<QueryEventArgs>(this, "QueryEvent");
queryObservable
.Select(query => client.QueryObservable(
query.EventArgs.SomeParameters,
query.EventArgs.QueryContext
))
.Switch()
.Subscribe(queryComplete =>
{
tbQueryProgress.Text = "Ready";
// ... etc
});
This sets up one continuous flow, whereby each "Query" event starts a query which emits the complete event from that query. New queries automatically teriminate the previous query (if possible) and start a new one.

Silverlight 3 Validation - manual validate not working?

Apologies for cross posting (I asked this on the Silverlight Forum but got no response)
I have an entity that I am trying to use validation on so I have decorated a property like so:
[Required]
[StringLength(10)]
public string Code
{
get
{
return this.code;
}
set
{
if (this.code != value)
{
this.code = value;
this.SendPropertyChanged("Code");
}
}
}
I have a list of these objects bound to a grid. If I put an empty entry in, it shows a validation error. If I put too long a code in, I get a validation error. Perfect! Except...
I want to be able to stop the user from saving the entity so I added the following to my entity:
public bool IsValid()
{
try
{
this.Validate();
}
catch
{
return false;
}
return true;
}
public void Validate()
{
var ctx = new ValidationContext(this, null, null);
Validator.ValidateObject(this, ctx);
}
And when i go to save I call the IsValid method on each object and not save if it's false.
This works fine for the required attribute (it wont save if Code is empty) but not for StringLength (I can save with any length code).
I have reproduced this in a simple project here:
http://walkersretreat.co.nz/files/Slvalidation.zip
Can anyone help?
Thanks!
Mark
you should write as:
[CustomValidation( typeof( MyExtraClassValidation ), "Validate" )]
public class MyExtraClass : Entity, IEditableObject, INotifyPropertyChanged
{
/****/
}
public class MyExtraClassValidation
{
public MyExtraClassValidation ()
{}
public static ValidationResult Validate( MyExtraClass myExtraClass )
{
if ( /**class is not valid*/)
return new ValidationResult( "Oops" );
return ValidationResult.Success;
}
}
Of course, your interfaces may be ablolutely anorther, but I reccomend you use it.
Also, you can call validateHandler from your control and check, for example, after every user key pressing.

Resources