The SonarLint tells me that I can reduce this block of code:
if (item != null && StringUtils.isNotBlank(item.getDateService())) {
LocalDate dateConverted = MapperUtil.convertToLocalDate(item.getDateService());
if (dateConverted != null) {
if (item.getInstallId() == null) {
if (dateConverted.getYear() == year) {
letter = "A";
} else {
if (dateConverted.getYear() == year - 1) {
letter = "C";
}
}
} else {
if (dateConverted.getYear() == year) {
letter = "E";
}
}
}
}
This is the error:
Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed. How to refactor and reduce the complexity
Any suggestions?
Thanks.
Try splitting out some of the logic to another method - innerCall:
if (item != null && StringUtils.isNotBlank(item.getDateService())) {
LocalDate dateConverted = MapperUtil.convertToLocalDate(item.getDateService());
if (dateConverted != null) {
letter = innerCall(item, dateConverted);
}
}
...
public String innerCall(ItemClass item, DateConvertedClass dateConverted) {
String letter = null;
if (item.getInstallId() == null) {
if (dateConverted.getYear() == year) {
letter = "A";
} else {
if (dateConverted.getYear() == year - 1) {
letter = "C";
}
}
} else {
if (dateConverted.getYear() == year) {
letter = "E";
}
}
return letter;
}
Related
Are there any Dart resources that would split a command-line String into a List<String> of arguments?
ArgsParser takes a List<String> of already split arguments usually from main(List<String>).
To answer my own question,
I've converted a Java function I liked into a Dart Converter<String, List<String>) class:
import 'dart:convert';
/// Splits a `String` into a list of command-line argument parts.
/// e.g. "command -p param" -> ["command", "-p", "param"]
///
class CommandlineConverter extends Converter<String, List<String>>
{
#override
List<String> convert(String input)
{
if (input == null || input.isEmpty)
{
//no command? no string
return [];
}
final List<String> result = new List<String>();
var current = "";
String inQuote;
bool lastTokenHasBeenQuoted = false;
for (int index = 0; index < input.length; index++)
{
final token = input[index];
if (inQuote != null)
{
if (token == inQuote)
{
lastTokenHasBeenQuoted = true;
inQuote = null;
}
else
{
current += token;
}
}
else
{
switch (token)
{
case "'": // '
case '"': // ""
inQuote = token;
continue;
case " ": // space
if (lastTokenHasBeenQuoted || current.isNotEmpty)
{
result.add(current);
current = "";
}
break;
default:
current += token;
lastTokenHasBeenQuoted = false;
}
}
}
if (lastTokenHasBeenQuoted || current.isNotEmpty)
{
result.add(current);
}
if (inQuote != null)
{
throw new Exception("Unbalanced quote $inQuote in input:\n$input");
}
return result;
}
}
In the query below I created new variables with anonymous type.
var sampleDetailsList = (from detailsA in context.SampleDetailsA
join detailsB in context.SampleDetailsB
on
new
{
Key1 = detailsA.SampleId,
Key2 = detailsA.Main.Year
}
equals
new
{
Key1 = detailsB.SampleId,
Key2 = detailsB.Main.Year
}
where (detailsA.Main.Year == "2018" && detailsB.Main.Year == "2018")
select new
{
SDASampleId = detailsA.SDASampleId,
SDASampleDetailId = detailsA.Id,
SDAAmountA = detailsA.SDAAmountA,
SDAAmountB = detailsA.SDAAmountB,
SDAAmountC = detailsA.SDAAmountC,
SDBSampleId = detailsB.SDBSampleId,
SDBSampleDetailId = detailsB.Id,
SDBAmountA = detailsB.SDBAmountA,
SDBAmountB = detailsB.SDBAmountB,
SDBAmountC = detailsB.SDBAmountC,
}).ToList();
Since anonymous type's properties are read-only. I could not assign new values in foreach loop. I need to add the amount in the transactional list below to the sampleDetailsList if a condition is met.
var transactionalList = (from tra in context.Transactions
where (tra.Year == "2018") && (tra.SDASampleDetailId != null || tra.SDBSampleDetailId != null)
select tra).ToList();
if (transactionalList.Count != 0)
{
foreach (var traItem in transactionalList)
{
foreach (var smDetail in sampleDetailsList)
{
if (smDetail.SDASampleId == traItem.SDASampleId)
{
if (traItem.TypeId == "AAA")
{
smDetail.SDAAmountA = smDetail.SDAAmountA + traItem.Amount;
}
else if (traItem.TypeId == "BBB")
{
smDetail.SDAAmountB = smDetail.SDAAmountB + traItem.Amount;
}
else if (traItem.TypeId == "CCC")
{
smDetail.SDAAmountC = smDetail.SDAAmountC + traItem.Amount;
}
}else if (smDetail.SDBSampleId == traItem.SDBSampleId)
{
if (traItem.TypeId == "AAA")
{
smDetail.SDBAmountA = smDetail.SDBAmountA + traItem.Amount;
}
else if (traItem.TypeId == "BBB")
{
smDetail.SDBAmountB = smDetail.SDBAmountB + traItem.Amount;
}
else if (traItem.TypeId == "CCC")
{
smDetail.SDBAmountC = smDetail.SDBAmountC + traItem.Amount;
}
}
}
}
}
How to assign the values just like in the foreach loop?
It seems to me that your query is like this:
var results =
(
from detailsA in context.SampleDetailsA
join detailsB in context.SampleDetailsB
on
new
{
Key1 = detailsA.SampleId,
Key2 = detailsA.Main.Year
}
equals
new
{
Key1 = detailsB.SampleId,
Key2 = detailsB.Main.Year
}
where detailsA.Main.Year == "2018"
where detailsB.Main.Year == "2018"
from tra in context.Transactions
where tra.Year == "2018"
where (tra.SDASampleDetailId != null || tra.SDBSampleDetailId != null)
select new
{
SDASampleId = detailsA.SDASampleId,
SDASampleDetailId = detailsA.Id,
SDAAmountA = detailsA.SDAAmountA + (((detailsA.SDASampleId == tra.SDASampleId) && tra.TypeId == "AAA") ? tra.Amount : 0),
SDAAmountB = detailsA.SDAAmountB + (((detailsA.SDASampleId == tra.SDASampleId) && tra.TypeId == "BBB") ? tra.Amount : 0),
SDAAmountC = detailsA.SDAAmountC + (((detailsA.SDASampleId == tra.SDASampleId) && tra.TypeId == "CCC") ? tra.Amount : 0),
SDBSampleId = detailsB.SDBSampleId,
SDBSampleDetailId = detailsB.Id,
SDBAmountA = detailsB.SDBAmountA + (((detailsB.SDBSampleId == tra.SDBSampleId) && tra.TypeId == "AAA") ? tra.Amount : 0),
SDBAmountB = detailsB.SDBAmountB + (((detailsB.SDBSampleId == tra.SDBSampleId) && tra.TypeId == "BBB") ? tra.Amount : 0),
SDBAmountC = detailsB.SDBAmountC + (((detailsB.SDBSampleId == tra.SDBSampleId) && tra.TypeId == "CCC") ? tra.Amount : 0),
}
)
.ToList();
And just to help others, this is the code that I had to write to make this code compilable:
public static class context
{
public static List<DetailA> SampleDetailsA = new List<DetailA>();
public static List<DetailB> SampleDetailsB = new List<DetailB>();
public static List<Transaction> Transactions = new List<Transaction>();
}
public class Transaction
{
public string Year;
public int? SDASampleDetailId;
public int? SDBSampleDetailId;
public int SDASampleId;
public int SDBSampleId;
public string TypeId;
public int Amount;
}
public class DetailA
{
public int Id;
public int SampleId;
public int SDASampleId;
public int SDAAmountA;
public int SDAAmountB;
public int SDAAmountC;
public Main Main;
}
public class DetailB
{
public int Id;
public int SampleId;
public Main Main;
public int SDBSampleId;
public int SDBAmountA;
public int SDBAmountB;
public int SDBAmountC;
}
public class Main
{
public string Year;
}
The only way out is probably creating a class SampleDetail with the properties that you need, and then change the LINQ to use select new SampleDetail { SDASampleId = ... etc }.
You can then change the values of each SampleDetail object as needed, at any time afterwards.
For some reason, I need to combine Linq Expression (only where clause) & an HQL where clause into one query.
I find that the session.Query<T>() API will translate Linq Expression to a HqlQuery object (that extends HqlExpression).
How can I translate the Linq Expression where clause to an HQL where clause queryString, and then I can combine another HQL where clause queryString into a new query?
Seems that is not possible to use exists NHibernate API to convert Linq expression to HQL tree.
The HQL tree produced from the Linq expression is not reversable to an actual HQL query.
So I have to translate Linq expression to HQL by self:
var expr = GetExpr<Ninja>(x =>
x.Age > 1 && x.Country.Name == "中国"
||
(x.Id > 10 && x.Country.Name == "中国")
);
var translator = new ExpressionToHqlTranslator("_this");
translator.Translate(expr);
Console.WriteLine(translator.WhereClause);
Console.WriteLine(translator.Patameters);
============== result =============
WhereClause: (((_this.Age > ?) AND (_this.Country.Name = ?)) OR ((_this.Id > ?) AND (_this.Country.Name = ?)))
Patameters:4
=============== the critical code =============
static Expression<Func<T, object>> GetExpr<T>(Expression<Func<T, object>> expr){
eturn expr;
}
using System;
using System.Linq;
using NHibernate.Linq;
using NHibernate.Linq.Visitors;
using System.Linq.Expressions;
using NHibernate;
using System.Text;
using System.Collections.Generic;
namespace Rhythm.Linq
{
public class ExpressionToHqlTranslator : System.Linq.Expressions.ExpressionVisitor
{
private StringBuilder sb;
private string _orderBy = "";
private int? _skip = null;
private int? _take = null;
private string _whereClause = "";
List<object> patameters;
public int? Skip
{
get
{
return _skip;
}
}
public int? Take
{
get
{
return _take;
}
}
public string OrderBy
{
get
{
return _orderBy;
}
}
public string WhereClause
{
get
{
return _whereClause;
}
}
public List<object> Patameters
{
get
{
return patameters;
}
set
{
patameters = value;
}
}
string prefix;
public ExpressionToHqlTranslator(string prefix = null)
{
this.prefix = string.IsNullOrEmpty(prefix) ? null : (prefix + ".");
}
public string Translate(Expression expression)
{
this.sb = new StringBuilder();
this.patameters = new List<object>();
this.Visit(expression);
_whereClause = this.sb.ToString();
return _whereClause;
}
private static Expression StripQuotes(Expression e)
{
while (e.NodeType == ExpressionType.Quote)
{
e = ((UnaryExpression)e).Operand;
}
return e;
}
protected override Expression VisitMethodCall(MethodCallExpression m)
{
if (m.Method.DeclaringType == typeof(Queryable) && m.Method.Name == "Where")
{
this.Visit(m.Arguments[0]);
LambdaExpression lambda = (LambdaExpression)StripQuotes(m.Arguments[1]);
this.Visit(lambda.Body);
return m;
}
else if (m.Method.Name == "Take")
{
if (this.ParseTakeExpression(m))
{
Expression nextExpression = m.Arguments[0];
return this.Visit(nextExpression);
}
}
else if (m.Method.Name == "Skip")
{
if (this.ParseSkipExpression(m))
{
Expression nextExpression = m.Arguments[0];
return this.Visit(nextExpression);
}
}
else if (m.Method.Name == "OrderBy")
{
if (this.ParseOrderByExpression(m, "ASC"))
{
Expression nextExpression = m.Arguments[0];
return this.Visit(nextExpression);
}
}
else if (m.Method.Name == "OrderByDescending")
{
if (this.ParseOrderByExpression(m, "DESC"))
{
Expression nextExpression = m.Arguments[0];
return this.Visit(nextExpression);
}
}
throw new NotSupportedException(string.Format("The method '{0}' is not supported", m.Method.Name));
}
protected override Expression VisitUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Not:
sb.Append(" NOT ");
this.Visit(u.Operand);
break;
case ExpressionType.Convert:
this.Visit(u.Operand);
break;
default:
throw new NotSupportedException(string.Format("The unary operator '{0}' is not supported", u.NodeType));
}
return u;
}
/// <summary>
///
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
protected override Expression VisitBinary(BinaryExpression b)
{
sb.Append("(");
this.Visit(b.Left);
switch (b.NodeType)
{
case ExpressionType.And:
sb.Append(" AND ");
break;
case ExpressionType.AndAlso:
sb.Append(" AND ");
break;
case ExpressionType.Or:
sb.Append(" OR ");
break;
case ExpressionType.OrElse:
sb.Append(" OR ");
break;
case ExpressionType.Equal:
if (IsNullConstant(b.Right))
{
sb.Append(" IS ");
}
else
{
sb.Append(" = ");
}
break;
case ExpressionType.NotEqual:
if (IsNullConstant(b.Right))
{
sb.Append(" IS NOT ");
}
else
{
sb.Append(" <> ");
}
break;
case ExpressionType.LessThan:
sb.Append(" < ");
break;
case ExpressionType.LessThanOrEqual:
sb.Append(" <= ");
break;
case ExpressionType.GreaterThan:
sb.Append(" > ");
break;
case ExpressionType.GreaterThanOrEqual:
sb.Append(" >= ");
break;
default:
throw new NotSupportedException(string.Format("The binary operator '{0}' is not supported", b.NodeType));
}
this.Visit(b.Right);
sb.Append(")");
return b;
}
protected override Expression VisitConstant(ConstantExpression c)
{
this.patameters.Add(c.Value);
sb.Append('?');
//IQueryable q = c.Value as IQueryable;
//if (q == null && c.Value == null)
//{
// sb.Append("NULL");
//}
//else if (q == null)
//{
// switch (Type.GetTypeCode(c.Value.GetType()))
// {
// case TypeCode.Boolean:
// sb.Append(((bool)c.Value) ? 1 : 0);
// break;
// case TypeCode.String:
// sb.Append("'");
// sb.Append(c.Value);
// sb.Append("'");
// break;
// case TypeCode.DateTime:
// sb.Append("'");
// sb.Append(c.Value);
// sb.Append("'");
// break;
// case TypeCode.Object:
// throw new NotSupportedException(string.Format("The constant for '{0}' is not supported", c.Value));
// default:
// sb.Append(c.Value);
// break;
// }
//}
return c;
}
protected override Expression VisitMember(MemberExpression m)
{
if (this.prefix != null)
{
sb.Append(this.prefix);
}
sb.Append(ContactModelPropertyVistHierarchyExpression(m, m.Member.DeclaringType));
//if (m.Expression != null && m.Expression.NodeType == ExpressionType.Parameter)
//{
// sb.Append(m.Member.Name);
// return m;
//}
return m;
//throw new NotSupportedException(string.Format("The member '{0}' is not supported", m.Member.Name));
}
protected bool IsNullConstant(Expression exp)
{
return (exp.NodeType == ExpressionType.Constant && ((ConstantExpression)exp).Value == null);
}
private bool ParseOrderByExpression(MethodCallExpression expression, string order)
{
UnaryExpression unary = (UnaryExpression)expression.Arguments[1];
LambdaExpression lambdaExpression = (LambdaExpression)unary.Operand;
lambdaExpression = (LambdaExpression)NHibernate.Linq.Visitors.Evaluator.PartialEval(lambdaExpression);
MemberExpression body = lambdaExpression.Body as MemberExpression;
if (body != null)
{
if (string.IsNullOrEmpty(_orderBy))
{
_orderBy = string.Format("{0} {1}", body.Member.Name, order);
}
else
{
_orderBy = string.Format("{0}, {1} {2}", _orderBy, body.Member.Name, order);
}
return true;
}
return false;
}
private bool ParseTakeExpression(MethodCallExpression expression)
{
ConstantExpression sizeExpression = (ConstantExpression)expression.Arguments[1];
int size;
if (int.TryParse(sizeExpression.Value.ToString(), out size))
{
_take = size;
return true;
}
return false;
}
private bool ParseSkipExpression(MethodCallExpression expression)
{
ConstantExpression sizeExpression = (ConstantExpression)expression.Arguments[1];
int size;
if (int.TryParse(sizeExpression.Value.ToString(), out size))
{
_skip = size;
return true;
}
return false;
}
}
public static string ContactModelPropertyVistHierarchyExpression(Expression expr, Type modelType)
{
StringBuilder sb = new StringBuilder();
Expression curr = expr;
// TypedParameterExpression
while (curr != null)
{
if (curr is MemberExpression)
{
var x = curr as MemberExpression;
sb.Insert(0, x.Member.Name);
curr = x.Expression;
}
else if (curr is MethodCallExpression)
{
var x = curr as MethodCallExpression;
sb.Insert(0, x.Method.Name);
curr = x.Object;
}
else if (curr is ParameterExpression)
{
break;
}
else
{
throw new ArgumentException("Unsupported Expression type " + curr.GetType().FullName + " for expression " + expr.ToString(), "expr");
}
sb.Insert(0, '.');
}
return sb.Length > 1 ? sb.Remove(0, 1).ToString() : sb.ToString();
}
}
add dll reference NHibernate.Linq.dll
I have a book table in my database and I have book view named vwShared in my edmx. I want to create dynamic search with operators for user to find books. I have 2 SearchColumns dropdownlist contains "Title, Authors, Published Year, Subject". I have 2 SearchType dropdownlist contains "StartsWith, Contains, EndsWith, Equals". I have another dropdownlist contains "AND, OR" to combine 2 search results. The following is my code.
var predicate = PredicateBuilder.True<DataLayer.vwShared>();
if (joinOperator == "AND")
{
if (SearchColumn1 == "Title" && SearchType1 == "Contains")
predicate = predicate.And(e1 => e1.Title.Contains(txtSearch1.Text));
if (SearchColumn2 == "Authors" && SearchType2 == "Contains")
predicate = predicate.And(e1 => e1.Authors.Contains(txtSearch2.Text));
}
else if (joinOperator == "OR")
{
if (SearchColumn1 == "Title" && SearchType1 == "Contains")
predicate = predicate.Or(e1 => e1.Title.Contains(txtSearch1.Text));
if (SearchColumn2 == "Authors" && SearchType2 == "Contains")
predicate = predicate.Or(e1 => e1.Authors.Contains(txtSearch2.Text));
}
List<DataLayer.vwShared> bookList= new DataLayer.Solib_DMREntities().SP_SharedData_GetAll("AllLocal").ToList<DataLayer.vwShared>();
var bookList= from books in bookList.AsQueryable().Where(predicate)
select books ;
gvBooks.DataSource = bookList.ToList();
gvBooks.DataBind();
The above code not return proper results. Is there something wrong. ?
The following is my references website.
http://www.albahari.com/nutshell/predicatebuilder.aspx
Please give me advice.
Thanks.
Answering your concrete question. The problem is in the branch for building OR predicate, in which case you should start with PredicateBuilder.False, otherwice there will not be filtering at all (as we know from the school, true or something is always true :)
// ...
else if (joinOperator == "OR")
{
predicate = PredicateBuilder.False<DataLayer.vwShared>();
// ...
}
// ...
step 1:Model
public class Person
{
public int PersonId { get; set; }
public int? Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Salary { get; set; }
}
public class PersonDBContext : DbContext
{
public virtual DbSet<Person> People { get; set; }
}
step 2 : controller
public class PersonController
{
PersonDBContext db = new PersonDBContext();
public void Add(Person person)
{
db.People.Add(person);
db.SaveChanges();
}
public List<Person> GetAll()
{
return db.People.ToList();
}
public List<Person> GetByPredicateValue(Expression<Func<Person, bool>> predicate)
{
if (predicate != null)
return db.People.Where(predicate.Compile()).ToList();
else
return null;
}
public List<Person> GetByPredicateAndPersonListValue(List<Person> PeopleList,Expression<Func<Person, bool>> predicate)
{
if (predicate != null)
return PeopleList.Where(predicate.Compile()).ToList();
else
return null;
}
}
step 3: code behind
public partial class MainWindow : Window
{
PersonController pc;
public static List<Person> PeopleFilterList = null;
public static string CurrentColumn = null;
public MainWindow()
{
pc = new PersonController();
InitializeComponent();
grid.ItemsSource = pc.GetAll();
grid.PreviewMouseDown += grid_PreviewMouseDown;
}
void grid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
TableViewHitInfo hi = ((TableView)grid.View).CalcHitInfo(e.OriginalSource as DependencyObject);
if (hi == null) return;
if (hi.HitTest == TableViewHitTest.ColumnHeader || hi.HitTest == TableViewHitTest.ColumnHeaderFilterButton)
{
grid.UnselectAll();
GridColumn currentColumn = ((DevExpress.Xpf.Grid.GridViewHitInfoBase)(hi)).Column;
CurrentColumn = currentColumn.FieldName;
(grid.View as TableView).SelectCells(0, currentColumn, grid.VisibleRowCount - 1, currentColumn);
}
}
Expression<Func<Person, bool>> _result=null;
string str="";
private void IdForm_ButtonClicked(object sender, IdentityUpdateEventArgs e)
{
_result = e.FirstName;
}
public MainWindow(Expression<Func<Person, bool>> result)
{
Window1 f = new Window1();
f.IdentityUpdated += new Window1.IdentityUpdateHandler(IdForm_ButtonClicked);
pc = new PersonController();
InitializeComponent();
_result = result;
if (PeopleFilterList != null)
PeopleFilterList = pc.GetByPredicateAndPersonListValue(PeopleFilterList,_result).ToList();
else
PeopleFilterList = pc.GetByPredicateValue(_result).ToList();
grid.ItemsSource = PeopleFilterList;
grid.PreviewMouseDown += grid_PreviewMouseDown;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Window1 w1 = new Window1(CurrentColumn);
w1.Show();
}
}
step 4 : Filter code behind
public partial class Window1 : Window
{
public delegate void IdentityUpdateHandler(object sender, IdentityUpdateEventArgs e);
public event IdentityUpdateHandler IdentityUpdated;
string _currentColumn = null;
public Window1()
{
InitializeComponent();
}
public Window1(string currentColumn)
{
_currentColumn = currentColumn;
InitializeComponent();
}
public static Expression<Func<Person, bool>> predicateValue;
IdentityUpdateEventArgs args;
private void Button_Click(object sender, RoutedEventArgs e)
{
string operatorName = "";
if (!String.IsNullOrEmpty(txtSmaller.Text.Trim()))
operatorName = txtSmaller.Name;
else if (!String.IsNullOrEmpty(txtElder.Text.Trim()))
operatorName = txtElder.Name;
else if (!String.IsNullOrEmpty(txtContains.Text.Trim()))
operatorName = txtContains.Name;
else if (!String.IsNullOrEmpty(txtStartWith.Text.Trim()))
operatorName = txtStartWith.Name;
else if (!String.IsNullOrEmpty(txtEqual.Text.Trim()))
operatorName = txtEqual.Name;
else if (!String.IsNullOrEmpty(txtNotEqual.Text.Trim()))
operatorName = txtNotEqual.Name;
else if (!String.IsNullOrEmpty(txtSmallerOrEqual.Text.Trim()))
operatorName = txtSmallerOrEqual.Name;
else if (!String.IsNullOrEmpty(txtElderOrEqual.Text.Trim()))
operatorName = txtElderOrEqual.Name;
else if (!String.IsNullOrEmpty(txtSmallerThan.Text.Trim()) && !String.IsNullOrEmpty(txtBiggerThan.Text.Trim()))
operatorName = txtSmallerThan.Name;
switch (operatorName)
{
case "txtSmaller":
predicateValue = (x => (int)x.GetType().GetProperty(_currentColumn).GetValue(x, null) < Convert.ToInt32(txtSmaller.Text));
break;
case "txtElder":
predicateValue = (x => (int)x.GetType().GetProperty(_currentColumn).GetValue(x, null) > Convert.ToInt32(txtElder.Text));
break;
case "txtSmallerOrEqual":
predicateValue = (x => (int)x.GetType().GetProperty(_currentColumn).GetValue(x, null) <= Convert.ToInt32(txtSmallerOrEqual.Text));
break;
case "txtElderOrEqual":
predicateValue = (x => (int)x.GetType().GetProperty(_currentColumn).GetValue(x, null) >= Convert.ToInt32(txtElderOrEqual.Text));
break;
case "txtEqual":
predicateValue = (x => (int)x.GetType().GetProperty(_currentColumn).GetValue(x, null) == Convert.ToInt32(txtEqual.Text));
break;
case "txtNotEqual":
predicateValue = (x => (int)x.GetType().GetProperty(_currentColumn).GetValue(x, null) != Convert.ToInt32(txtNotEqual.Text));
break;
case "txtSmallerThan":
predicateValue = (x => (int)x.GetType().GetProperty(_currentColumn).GetValue(x, null) >= Convert.ToInt32(txtBiggerThan.Text)
&& (int)x.GetType().GetProperty(_currentColumn).GetValue(x, null) <= Convert.ToInt32(txtSmallerThan.Text));
break;
case "txtStartWith":
predicateValue = (x => x.GetType().GetProperty(_currentColumn).GetValue(x, null).ToString().StartsWith(txtStartWith.Text));
break;
case "txtContains":
predicateValue = (x => x.GetType().GetProperty(_currentColumn).GetValue(x,null).ToString().Contains(txtContains.Text));
break;
}
MainWindow mw = new MainWindow(predicateValue);
mw.Show();
this.Close();
}
void Window1_IdentityUpdated(object sender, IdentityUpdateEventArgs e)
{
e = args;
}
}
public class IdentityUpdateEventArgs : System.EventArgs
{
private Expression<Func<Person, bool>> mFirstName;
public IdentityUpdateEventArgs(Expression<Func<Person, bool>> sFirstName)
{
this.mFirstName = sFirstName;
}
public Expression<Func<Person, bool>> FirstName
{
get
{
return mFirstName;
}
}
}
I am trying to convert my method to Async. I cannot seem to grasp converting a linq query or foreach loop into a form that is awaitable. I read here on SO that EntityFramework + Linq don’t mix very well asynchronously. Perhaps that is why I could not find a previous Question that matches my needs exactly. Would someone care to point me in the right direction?
private static async Task<decimal> GetLastPriceAsync(string customer, string stockNumber)
{
Debug.WriteLine("Get Last Price Called");
decimal lastCost = 0;
var lastDate = new DateTime(1900, 1, 1);
if (string.IsNullOrEmpty(customer))
{
Debug.WriteLine("There was no customer");
return 0;
}
Debug.WriteLine("We have a customer");
if (string.IsNullOrEmpty(stockNumber))
{
Debug.WriteLine("There was no item");
return 0;
}
Debug.WriteLine("We have a Part Number");
try
{
IEnumerable<SA_HistoryHeader> orders =
DContext.SA_HistoryHeader.Local.Where(c => c.strCustomer == customer);
if (!orders.Any())
{
Debug.WriteLine("No order found.");
return 0;
}
Debug.WriteLine("We have previous Orders Found");
foreach (SA_HistoryHeader thisOrder in orders)
{
Debug.WriteLine("Looping through orders.");
DateTime date = lastDate;
IEnumerable<SA_HistoryDetail> details = thisOrder.SA_HistoryDetail
.Where(i => i.strStock == stockNumber && i.dteLineDate > date && i.bytLineType == 003);
foreach (
SA_HistoryDetail detail in
details.Where(detail => detail != null && !string.IsNullOrEmpty(detail.strDescription)))
{
if (detail.dteLineDate != null)
{
lastDate = (DateTime) detail.dteLineDate;
}
else
{
Debug.WriteLine("Order Date was null");
}
if (detail.curUnitPrice != null)
{
lastCost = (decimal) detail.curUnitPrice;
}
else
{
Debug.WriteLine("Last Cost was null");
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Last Price Calc Error: " + ex.InnerException.Message);
}
return lastCost;
}