getmethod(methodname,new[]Type) in Type arrays contains ref parameter and method is overrided - c#-3.0

For example
class xx
{
public string name
{
get {return "";}
}
}
class yy
{
public string name(string n)
{
return "";
}
public string name(string n,ref string m)
{
return "";
}
public string name(string n,string m,ref xx k)
{
return "";
}
}
How to get "name" method by reflection technology ?

There's no easy way to do it using GetMethod. However, you can easily do it with GetMethods and Linq :
var methodInfo = from m in typeof(yy).GetMethods()
where m.Name == "name"
let prms = m.GetParameters()
where prms.Length == 3
&& prms[0].ParameterType == typeof(string)
&& prms[1].ParameterType == typeof(string)
&& prms[2].ParameterType == typeof(xx).MakeByRefType()
select m;

You could use Type.MakeByRefType()-Method to create an ref type param. The rest is done by reflection classes.
var method = typeof(yy).GetMethod(
"name",
new[] {typeof(string), typeof(string).MakeByRefType()});

Related

how can I write generic queries in entity framework?

I have 3 methods these are same methods only some parameters will be change I want to write one method how can i write
public string method1(int id)
{
var getAllStudents = rep.Students.Where(e => e.StudentId == id).ToList();
foreach (var item in getAllStudents)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
public string method2(int id)
{
var getAllTeachers = rep.Teachers.Where(e => e.TeacherId == id).ToList();
foreach (var item in getAllTeachers)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
public string method3(int id)
{
var getAllClasses = rep.Classes.Where(e => e.ClassId == id).ToList();
foreach (var item in getAllClasses)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
I think there is very easy way to write 1 method. the think is where parameter has different id..
Thanks.
Avoid conditional logic based on arguments. This leads to fragile code because every parameter combination has to be tested to be considered reliable. This leads to complex code that is easily prone to bugs. Having simpler single-purpose methods are typically much more reliable and easier to understand and maintain.
For instance given your example and assuming that "rep" was your instance's DbContext...
public bool IsActiveStudent(int id)
{
bool result = rep.Students.Any(x => x.StudentId == id && x.IsActive);
return result;
}
public bool IsActiveTeacher(int id)
{
bool result = rep.Teachers.Any(x => x.TeacherId == id && x.IsActive);
return result;
}
public bool IsActiveClass(int id)
{
bool result = rep.Classes.Any(x => x.ClassId == id && x.IsActive);
return result;
}
These can be essentially one-liners by simply returning the .Any() result. I tend to favour selecting the result into a variable first and returning it on a separate line since it makes it easier to breakpoint and inspect.
If you need to return a string for "Ok" vs. "Error" then:
return result ? "OK" : "Error";
Methods should strive to do one thing, and do it well. Easy to understand and troubleshoot if need be. Adding parameters and conditional code inside the method merely makes the code more volatile and leaves openings for bugs. In the end it doesn't make the code much shorter when the initial method could be simplified.
You can not overload methods if they signatures are the same.
You have two methods with the same signature:
public string checkexist(int id)
What you can do is to rename your methods, like this:
public interface WriteSomethingHere {
public boolean isStudentExist(int id);
public boolean isTeacherExist(int id);
public boolean isClassExist(int id);
}
I just found answer using generic repo
public T GetEntity<T>(int Id)
where T : class
{
using (MyEntities rpContext = new MyEntities())
{
return rpContext.Set<T>().Find(e => e.Id == Id);
}
}
after calling
var entityStudent = GetEntity<Student>(1);
var entityTeacher = GetEntity<Teacher>(1);
var entityClasses = GetEntity<Classes>(1);
You have Create Enumeration
Public Enum ParameterStaus:short
{
Student=1,
Teacher=2,
Classess=3
}
public string method2(int id.ParameterStatus status)
{
if(status==ParameterStatus.Teacher)
{
var getAllTeachers = rep.Teachers.Where(e => e.TeacherId == id).ToList();
foreach (var item in getAllTeachers )
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
}
Else if(status==ParameterStatus.Student)
{
var getAllStudents = rep.Students.Where(e => e.StudentId == id).ToList();
foreach (var item in getAllStudents)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
Else
{
var getAllClasses = rep.Classes.Where(e => e.ClassId == id).ToList();
foreach (var item in getAllClasses)
{
if (item.isActive != true)
return "Error";
}
return "OK";
}
}

How to construct a dynamic where filter in EF.Core to handle equals, LIKE, gt, lt, etc

Please how do we construct a dynamic where filter in EF.Core to handle:
Query.Where(fieldName, compareMode, value)
I basically Expect to use it like below:
[HttpGet(Name = nameof(GetStaff))]
public IActionResult GetStaffAsync([FromQuery] QueryParams p)
{
var s = db.Staff.AsNoTracking()
.Where(p.filter_field, p.filter_mode, p.filter_value)
.OrderByMember(p.sortBy, p.descending);
var l = new Pager<Staff>(s, p.page, p.rowsPerPage);
return Ok(l);
}
//Helpers
public class QueryParams
{
public bool descending { get; set; }
public int page { get; set; } = 1;
public int rowsPerPage { get; set; } = 5;
public string sortBy { get; set; }
public onject filter_value { get; set; }
public string filter_field { get; set; }
public string filter_mode { get; set; }
}
public class Pager<T>
{
public int pages { get; set; }
public int total { get; set; }
public IEnumerable<T> Items { get; set; }
public Pager(IEnumerable<T> items, int offset, int limit)
{
Items = items.Skip((offset - 1) * limit).Take(limit).ToList<T>();
total = items.Count();
pages = (int)Math.Ceiling((double)total / limit);
}
}
Assuming all you have is the entity type and strings representing the property, comparison operator and the value, building dynamic predicate can be done with something like this:
public static partial class ExpressionUtils
{
public static Expression<Func<T, bool>> BuildPredicate<T>(string propertyName, string comparison, string value)
{
var parameter = Expression.Parameter(typeof(T), "x");
var left = propertyName.Split('.').Aggregate((Expression)parameter, Expression.Property);
var body = MakeComparison(left, comparison, value);
return Expression.Lambda<Func<T, bool>>(body, parameter);
}
private static Expression MakeComparison(Expression left, string comparison, string value)
{
switch (comparison)
{
case "==":
return MakeBinary(ExpressionType.Equal, left, value);
case "!=":
return MakeBinary(ExpressionType.NotEqual, left, value);
case ">":
return MakeBinary(ExpressionType.GreaterThan, left, value);
case ">=":
return MakeBinary(ExpressionType.GreaterThanOrEqual, left, value);
case "<":
return MakeBinary(ExpressionType.LessThan, left, value);
case "<=":
return MakeBinary(ExpressionType.LessThanOrEqual, left, value);
case "Contains":
case "StartsWith":
case "EndsWith":
return Expression.Call(MakeString(left), comparison, Type.EmptyTypes, Expression.Constant(value, typeof(string)));
default:
throw new NotSupportedException($"Invalid comparison operator '{comparison}'.");
}
}
private static Expression MakeString(Expression source)
{
return source.Type == typeof(string) ? source : Expression.Call(source, "ToString", Type.EmptyTypes);
}
private static Expression MakeBinary(ExpressionType type, Expression left, string value)
{
object typedValue = value;
if (left.Type != typeof(string))
{
if (string.IsNullOrEmpty(value))
{
typedValue = null;
if (Nullable.GetUnderlyingType(left.Type) == null)
left = Expression.Convert(left, typeof(Nullable<>).MakeGenericType(left.Type));
}
else
{
var valueType = Nullable.GetUnderlyingType(left.Type) ?? left.Type;
typedValue = valueType.IsEnum ? Enum.Parse(valueType, value) :
valueType == typeof(Guid) ? Guid.Parse(value) :
Convert.ChangeType(value, valueType);
}
}
var right = Expression.Constant(typedValue, left.Type);
return Expression.MakeBinary(type, left, right);
}
}
Basically building property accessor (with nested property support), parsing the comparison operator and calling the corresponding operator/method, dealing with from/to string and from/to nullable type conversions. It can be extended to handle EF Core specific functions like EF.Functions.Like by adding the corresponding branch.
It can be used directly (in case you need to combine it with other predicates) or via custom extension method like this:
public static partial class QueryableExtensions
{
public static IQueryable<T> Where<T>(this IQueryable<T> source, string propertyName, string comparison, string value)
{
return source.Where(ExpressionUtils.BuildPredicate<T>(propertyName, comparison, value));
}
}
based on Ivans answer this is what i came up with
public static class ExpressionUtils
{
public static Expression<Func<T, bool>> BuildPredicate<T>(string propertyName, string comparison, object value)
{
var parameter = Expression.Parameter(typeof(T));
var left = propertyName.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
var body = MakeComparison(left, comparison, value);
return Expression.Lambda<Func<T, bool>>(body, parameter);
}
static Expression MakeComparison(Expression left, string comparison, object value)
{
var constant = Expression.Constant(value, left.Type);
switch (comparison)
{
case "==":
return Expression.MakeBinary(ExpressionType.Equal, left, constant);
case "!=":
return Expression.MakeBinary(ExpressionType.NotEqual, left, constant);
case ">":
return Expression.MakeBinary(ExpressionType.GreaterThan, left, constant);
case ">=":
return Expression.MakeBinary(ExpressionType.GreaterThanOrEqual, left, constant);
case "<":
return Expression.MakeBinary(ExpressionType.LessThan, left, constant);
case "<=":
return Expression.MakeBinary(ExpressionType.LessThanOrEqual, left, constant);
case "Contains":
case "StartsWith":
case "EndsWith":
if (value is string)
{
return Expression.Call(left, comparison, Type.EmptyTypes, constant);
}
throw new NotSupportedException($"Comparison operator '{comparison}' only supported on string.");
default:
throw new NotSupportedException($"Invalid comparison operator '{comparison}'.");
}
}
}
and some tests
public class Tests
{
[Fact]
public void Nested()
{
var list = new List<Target>
{
new Target
{
Member = "a"
},
new Target
{
Member = "bb"
}
};
var result = list.AsQueryable()
.Where(ExpressionUtils.BuildPredicate<Target>("Member.Length", "==", 2))
.Single();
Assert.Equal("bb", result.Member);
}
[Fact]
public void Field()
{
var list = new List<TargetWithField>
{
new TargetWithField
{
Field = "Target1"
},
new TargetWithField
{
Field = "Target2"
}
};
var result = list.AsQueryable()
.Where(ExpressionUtils.BuildPredicate<TargetWithField>("Field", "==", "Target2"))
.Single();
Assert.Equal("Target2", result.Field);
}
[Theory]
[InlineData("Name", "==", "Person 1", "Person 1")]
[InlineData("Name", "!=", "Person 2", "Person 1")]
[InlineData("Name", "Contains", "son 2", "Person 2")]
[InlineData("Name", "StartsWith", "Person 2", "Person 2")]
[InlineData("Name", "EndsWith", "son 2", "Person 2")]
[InlineData("Age", "==", 13, "Person 2")]
[InlineData("Age", ">", 12, "Person 2")]
[InlineData("Age", "!=", 12, "Person 2")]
[InlineData("Age", ">=", 13, "Person 2")]
[InlineData("Age", "<", 13, "Person 1")]
[InlineData("Age", "<=", 12, "Person 1")]
public void Combos(string name, string expression, object value, string expectedName)
{
var people = new List<Person>
{
new Person
{
Name = "Person 1",
Age = 12
},
new Person
{
Name = "Person 2",
Age = 13
}
};
var result = people.AsQueryable()
.Where(ExpressionUtils.BuildPredicate<Person>(name, expression, value))
.Single();
Assert.Equal(expectedName, result.Name);
}
}
I modified the answer I found here: Linq WHERE EF.Functions.Like - Why direct properties work and reflection does not?
I chucked together a version for those using NpgSQL as their EF Core provider as you will need to use the ILike function instead if you want case-insensitivity, also added a second version which combines a bunch of properties into a single Where() clause:
public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, string propertyName, string searchTerm)
{
// Check property name
if (string.IsNullOrEmpty(propertyName))
{
throw new ArgumentNullException(nameof(propertyName));
}
// Check the search term
if(string.IsNullOrEmpty(searchTerm))
{
throw new ArgumentNullException(nameof(searchTerm));
}
// Check the property exists
var property = typeof(T).GetProperty(propertyName);
if (property == null)
{
throw new ArgumentException($"The property {typeof(T)}.{propertyName} was not found.", nameof(propertyName));
}
// Check the property type
if(property.PropertyType != typeof(string))
{
throw new ArgumentException($"The specified property must be of type {typeof(string)}.", nameof(propertyName));
}
// Get expression constants
var searchPattern = "%" + searchTerm + "%";
var itemParameter = Expression.Parameter(typeof(T), "item");
var functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions)));
var likeFunction = typeof(NpgsqlDbFunctionsExtensions).GetMethod(nameof(NpgsqlDbFunctionsExtensions.ILike), new Type[] { functions.Type, typeof(string), typeof(string) });
// Build the property expression and return it
Expression selectorExpression = Expression.Property(itemParameter, property.Name);
selectorExpression = Expression.Call(null, likeFunction, functions, selectorExpression, Expression.Constant(searchPattern));
return source.Where(Expression.Lambda<Func<T, bool>>(selectorExpression, itemParameter));
}
public static IQueryable<T> WhereLike<T>(this IQueryable<T> source, IEnumerable<string> propertyNames, string searchTerm)
{
// Check property name
if (!(propertyNames?.Any() ?? false))
{
throw new ArgumentNullException(nameof(propertyNames));
}
// Check the search term
if (string.IsNullOrEmpty(searchTerm))
{
throw new ArgumentNullException(nameof(searchTerm));
}
// Check the property exists
var properties = propertyNames.Select(p => typeof(T).GetProperty(p)).AsEnumerable();
if (properties.Any(p => p == null))
{
throw new ArgumentException($"One or more specified properties was not found on type {typeof(T)}: {string.Join(",", properties.Where(p => p == null).Select((p, i) => propertyNames.ElementAt(i)))}.", nameof(propertyNames));
}
// Check the property type
if (properties.Any(p => p.PropertyType != typeof(string)))
{
throw new ArgumentException($"The specified properties must be of type {typeof(string)}: {string.Join(",", properties.Where(p => p.PropertyType != typeof(string)).Select(p => p.Name))}.", nameof(propertyNames));
}
// Get the expression constants
var searchPattern = "%" + searchTerm + "%";
var itemParameter = Expression.Parameter(typeof(T), "item");
var functions = Expression.Property(null, typeof(EF).GetProperty(nameof(EF.Functions)));
var likeFunction = typeof(NpgsqlDbFunctionsExtensions).GetMethod(nameof(NpgsqlDbFunctionsExtensions.ILike), new Type[] { functions.Type, typeof(string), typeof(string) });
// Build the expression and return it
Expression selectorExpression = null;
foreach (var property in properties)
{
var previousSelectorExpression = selectorExpression;
selectorExpression = Expression.Property(itemParameter, property.Name);
selectorExpression = Expression.Call(null, likeFunction, functions, selectorExpression, Expression.Constant(searchPattern));
if(previousSelectorExpression != null)
{
selectorExpression = Expression.Or(previousSelectorExpression, selectorExpression);
}
}
return source.Where(Expression.Lambda<Func<T, bool>>(selectorExpression, itemParameter));
}

Entity framework ordering using reflection

I have an extension method for ordering, the sortExpression can be something like "Description" or "Description DESC", it is working perfectly for columns at the same table:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortExpression)
{
if (source == null)
throw new ArgumentNullException("source");
if (string.IsNullOrEmpty(sortExpression))
return source;
var parts = sortExpression.Split(' ');
var isDescending = false;
var propertyName = "";
var type = typeof(T);
if (parts.Length > 0 && parts[0] != "")
{
propertyName = parts[0];
if (parts.Length > 1)
isDescending = parts[1].ToLower().Contains("esc");
var prop = type.GetProperty(propertyName);
if (prop == null)
throw new ArgumentException(string.Format("No property '{0}' on type '{1}'", propertyName, type.Name));
var funcType = typeof(Func<,>)
.MakeGenericType(type, prop.PropertyType);
var lambdaBuilder = typeof(Expression)
.GetMethods()
.First(x => x.Name == "Lambda" && x.ContainsGenericParameters && x.GetParameters().Length == 2)
.MakeGenericMethod(funcType);
var parameter = Expression.Parameter(type);
var propExpress = Expression.Property(parameter, prop);
var sortLambda = lambdaBuilder
.Invoke(null, new object[] { propExpress, new ParameterExpression[] { parameter } });
var sorter = typeof(Queryable)
.GetMethods()
.FirstOrDefault(x => x.Name == (isDescending ? "OrderByDescending" : "OrderBy") && x.GetParameters().Length == 2)
.MakeGenericMethod(new[] { type, prop.PropertyType });
var result = (IQueryable<T>)sorter
.Invoke(null, new object[] { source, sortLambda });
return result;
}
return source;
}
Working Example:
var query = db.Audit.Include("AccessLevel").AsQueryable();
query = query.OrderBy("Description");
Please note that the "Description" column exists at the same table "Audit".
What I'm trying to do is to sort by a column in a relation table:
Like the following
var query = db.Audit.Include("AccessLevel").AsQueryable();
query = query.OrderBy("AccessLevel.Name");
Which is equivalent to:
query = query.OrderBy(o => o.AccessLevel.Name);
What is the required modification on my extension method ?
I solved it by using the following code:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, parts[0], "OrderBy");
}
public static IQueryable<T> OrderByDescending<T>(this IQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "OrderByDescending");
}
public static IQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenBy");
}
public static IQueryable<T> ThenByDescending<T>(this IOrderedQueryable<T> source, string property)
{
return ApplyOrder<T>(source, property, "ThenByDescending");
}
static IQueryable<T> ApplyOrder<T>(IQueryable<T> source, string property, string methodName)
{
if (source == null)
throw new ArgumentNullException("source");
if (string.IsNullOrEmpty(property))
return source;
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach (string prop in props)
{
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.Name == methodName
&& method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] { source, lambda });
return (IQueryable<T>)result;
}

How to store user sql where clause, and how to apply it on a select?

I am using JPA / Eclipselink / PostgreSQL within my application.
I have a model that list some data, and I would like to let the user of the application to create his own where clause parameters.
How can I store theses parameters ? as plain sql string ?
Then how can I apply the where clause ? as a simple string concatenation ? (I don't like this idea at all).
Bests regards.
Ok, so I solved my problem.
For information : I have created a recursive JSON representation of every where clause parameters possibility.
And I have created a query using criteria api by decoding the pojo structure from json.
The json class look like that :
public class JSonSearchCriteria
{
public static enum CriteriaType
{
asc,
desc,
count,
countDistinct,
and,
or,
not,
equal,
notEqual,
between,
gt,
ge,
lt,
le,
like,
notLike;
}
#Expose
public CriteriaType type;
#Expose
public List<JSonSearchCriteria> sub;
#Expose
public String what = null;
#Expose
public List<Integer> integerValue = null;
#Expose
public List<Long> longValue = null;
#Expose
public List<Boolean> booleanValue = null;
#Expose
public List<String> stringValue = null;
#Expose
public List<DateTime> datetimeValue = null;
public JSonSearchCriteria()
{
}
public JSonSearchCriteria(final CriteriaType type)
{
this.type = type;
}
public JSonSearchCriteria(final CriteriaType type, final String what)
{
this(type);
this.what = what;
}
public JSonSearchCriteria(final CriteriaType type, final String what, final String... values)
{
this(type, what);
for(final String value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final Long... values)
{
this(type, what);
for(final Long value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final Integer... values)
{
this(type, what);
for(final Integer value : values)
{
value(value);
}
}
public JSonSearchCriteria(final CriteriaType type, final String what, final DateTime... values)
{
this(type, what);
for(final DateTime value : values)
{
value(value);
}
}
public void add(final JSonSearchCriteria subCriteria)
{
if(sub == null)
{
sub = new ArrayList<>();
}
sub.add(subCriteria);
}
public void value(final String value)
{
if(stringValue == null)
{
stringValue = new ArrayList<>();
}
stringValue.add(value);
}
public void value(final Long value)
{
if(longValue == null)
{
longValue = new ArrayList<>();
}
longValue.add(value);
}
public void value(final Integer value)
{
if(integerValue == null)
{
integerValue = new ArrayList<>();
}
integerValue.add(value);
}
public void value(final DateTime value)
{
if(datetimeValue == null)
{
datetimeValue = new ArrayList<>();
}
datetimeValue.add(value);
}
#SuppressWarnings(
{
"unchecked", "rawtypes"
})
#Transient
public Predicate buildPredicate(final CriteriaBuilder builder, final Root<Record> root, Join<Record, RecordInfo> infos)
{
switch(type)
{
case and:
case or:
final Predicate[] preds = new Predicate[sub.size()];
int cpt = 0;
for(final JSonSearchCriteria s : sub)
{
preds[cpt] = s.buildPredicate(builder, root, infos);
cpt++;
}
if(type == CriteriaType.and)
{
return builder.and(preds);
}
else if(type == CriteriaType.or)
{
return builder.or(preds);
}
break;
case equal:
case lt:
case gt:
case between:
final Path p;
if(what.startsWith("infos."))
{
p = infos.get(what.substring(6));
}
else
{
p = root.get(what);
}
if(stringValue != null && !stringValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, stringValue.get(0));
}
}
else if(longValue != null && !longValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, longValue.get(0));
}
else if(type == CriteriaType.lt)
{
return builder.lt(p, longValue.get(0));
}
else if(type == CriteriaType.gt)
{
return builder.gt(p, longValue.get(0));
}
}
else if(integerValue != null && !integerValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, integerValue.get(0));
}
else if(type == CriteriaType.lt)
{
return builder.lt(p, integerValue.get(0));
}
else if(type == CriteriaType.gt)
{
return builder.gt(p, integerValue.get(0));
}
}
else if(booleanValue != null && !booleanValue.isEmpty())
{
return builder.equal(p, booleanValue.get(0));
}
else if(datetimeValue != null && !datetimeValue.isEmpty())
{
if(type == CriteriaType.equal)
{
return builder.equal(p, datetimeValue.get(0));
}
else if(type == CriteriaType.between && datetimeValue.size() > 1)
{
return builder.between(p, datetimeValue.get(0), datetimeValue.get(1));
}
}
break;
}
System.err.println(type + " - not implemented");
return null;
}
}
And it is used like that :
final SearchTemplate templ = DBHelper.get(SearchTemplate.class, 100);
final Gson gson = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeJsonAdapter()).create();
final JSonSearchCriteria crits = gson.fromJson(templ.getTemplate(), JSonSearchCriteria.class);
final CriteriaBuilder critBuilder = DBHelper.getInstance().em().getCriteriaBuilder();
final CriteriaQuery<Record> critQuery = critBuilder.createQuery(Record.class);
final Root<Record> root = critQuery.from(Record.class);
final Join<Record, RecordInfo> infos = root.join("infos");
critQuery.where(crits.buildPredicate(critBuilder, root, infos));
final TypedQuery<Record> query = DBHelper.getInstance().em().createQuery(critQuery);
final List<Record> result = query.getResultList();
for(final Record rec : result)
{
System.err.println(rec.toString());
}

sorting xtext AST through quickfix

I've Been Trying to change the order of nodes through quickfix, but something is wrong.
Here's my code in xtend:
#Fix(org.xtext.custom.conventions.validation.ConventionsValidator::CONVENTION_NOT_ORDERED)
def fixFeatureName( Issue issue, IssueResolutionAcceptor acceptor){
acceptor.accept(issue, 'Sort', "Sort '" + issue.data.head + "'", null)[
element, context |
var gr=(element as Greeting)
if (gr.name === null || gr.name.length === 0)
return;
var econt=gr.eContainer.eContents
var comparator = [ EObject obj1, EObject obj2 |
var o1 = (obj1 as Greeting)
var o2 = (obj2 as Greeting)
return o1.name.compareTo(o2.name)
]
ECollections::sort(econt, comparator)
]
}
No exception is being thrown to console, in debug I found an UnsupportedOperationException is thrown and handled by xtext.
I suspect that EList is immutable.
So how can I sort the AST?
(Here is the generated code: )
#Fix(ConventionsValidator.CONVENTION_NOT_ORDERED)
public void fixFeatureName(final Issue issue, final IssueResolutionAcceptor acceptor) {
String[] _data = issue.getData();
String _head = IterableExtensions.<String>head(((Iterable<String>)Conversions.doWrapArray(_data)));
String _plus = ("Sort \'" + _head);
String _plus_1 = (_plus + "\'");
final ISemanticModification _function = new ISemanticModification() {
public void apply(final EObject element, final IModificationContext context) throws Exception {
Greeting gr = ((Greeting) element);
boolean _or = false;
String _name = gr.getName();
boolean _tripleEquals = (_name == null);
if (_tripleEquals) {
_or = true;
} else {
String _name_1 = gr.getName();
int _length = _name_1.length();
boolean _tripleEquals_1 = (Integer.valueOf(_length) == Integer.valueOf(0));
_or = (_tripleEquals || _tripleEquals_1);
}
if (_or) {
return;
}
EObject _eContainer = gr.eContainer();
EList<EObject> econt = _eContainer.eContents();
final Function2<EObject,EObject,Integer> _function = new Function2<EObject,EObject,Integer>() {
public Integer apply(final EObject obj1, final EObject obj2) {
Greeting o1 = ((Greeting) obj1);
Greeting o2 = ((Greeting) obj2);
String _name = o1.getName();
String _name_1 = o2.getName();
return _name.compareTo(_name_1);
}
};
Function2<EObject,EObject,Integer> comparator = _function;
final Function2<EObject,EObject,Integer> _converted_comparator = (Function2<EObject,EObject,Integer>)comparator;
ECollections.<EObject>sort(econt, new Comparator<EObject>() {
public int compare(EObject o1,EObject o2) {
return _converted_comparator.apply(o1,o2);
}
});
}
};
acceptor.accept(issue, "Sort", _plus_1, null, _function);
}
thanks!
Sorting a temporary collection which will then replace econt didn't work. but I managed to solve it in a different way.
so one solution was to force a cast of eContainer as it's runtime element (which is Model), and then getting a list with it's getGreetings getter, and with that element the sorting works, but I didn't want to involve non-generic code, for technical reasons.
So after a lot of experiments I finally found that element without involving any other elements or keywords from the grammar:
var econt = (gr.eContainer.eGet(gr.eContainingFeature) as EObjectContainmentEList<Greeting>)
and that is exactly what was looking for. Sorting is successful!
Here's the resulting Xtend code (got rid of casing in the comperator as well):
#Fix(ConventionsValidator::CONVENTION_NOT_ORDERED)
def fixFeatureName(Issue issue, IssueResolutionAcceptor acceptor) {
acceptor.accept(issue, 'Sort', "Sort '" + issue.data.head + "'", null) [
element, context |
var gr = (element as Greeting)
if (gr.name === null || gr.name.length === 0)
return;
var econt = (gr.eContainer.eGet(gr.eContainingFeature) as EObjectContainmentEList<Greeting>)
var comparator = [ Greeting o1, Greeting o2 |
return o1.name.compareTo(o2.name)
]
ECollections::sort(econt, comparator)
]
}
and the generated java:
#Fix(ConventionsValidator.CONVENTION_NOT_ORDERED)
public void fixFeatureName(final Issue issue, final IssueResolutionAcceptor acceptor) {
String[] _data = issue.getData();
String _head = IterableExtensions.<String>head(((Iterable<String>)Conversions.doWrapArray(_data)));
String _plus = ("Sort \'" + _head);
String _plus_1 = (_plus + "\'");
final ISemanticModification _function = new ISemanticModification() {
public void apply(final EObject element, final IModificationContext context) throws Exception {
Greeting gr = ((Greeting) element);
boolean _or = false;
String _name = gr.getName();
boolean _tripleEquals = (_name == null);
if (_tripleEquals) {
_or = true;
} else {
String _name_1 = gr.getName();
int _length = _name_1.length();
boolean _tripleEquals_1 = (Integer.valueOf(_length) == Integer.valueOf(0));
_or = (_tripleEquals || _tripleEquals_1);
}
if (_or) {
return;
}
EObject _eContainer = gr.eContainer();
EStructuralFeature _eContainingFeature = gr.eContainingFeature();
Object _eGet = _eContainer.eGet(_eContainingFeature);
EObjectContainmentEList<Greeting> econt = ((EObjectContainmentEList<Greeting>) _eGet);
final Function2<Greeting,Greeting,Integer> _function = new Function2<Greeting,Greeting,Integer>() {
public Integer apply(final Greeting o1, final Greeting o2) {
String _name = o1.getName();
String _name_1 = o2.getName();
return _name.compareTo(_name_1);
}
};
Function2<Greeting,Greeting,Integer> comparator = _function;
final Function2<Greeting,Greeting,Integer> _converted_comparator = (Function2<Greeting,Greeting,Integer>)comparator;
ECollections.<Greeting>sort(econt, new Comparator<Greeting>() {
public int compare(Greeting o1,Greeting o2) {
return _converted_comparator.apply(o1,o2);
}
});
}
};
acceptor.accept(issue, "Sort", _plus_1, null, _function);
}