OrderByDescending linq query - linq

I am trying to show deal.type as decending order by date but I cannot get the result to show in Descending order.
[Authorize(Roles = "admin")]
[HttpGet]
[Queryable(PageSize = 10)]
public HttpResponseMessage Get([FromUri] Query query)
{
var data = db.database_ICs.AsQueryable();
if (query.price_type != null)
{
data = data.Where(c => c.Cover == query.price_type);
}
if (query.deal_type != null)
{
data = data.Where(c => c.Type == query.deal_type)
.OrderByDescending(c => c.UploadDate);
}
if (query.startDate != null)
{
data = data.Where(c => c.UploadDate >= query.startDate);
}
if (query.endDate != null)
{
data = data.Where(c => c.UploadDate <= query.endDate);
}
if (!data.Any())
{
var message = string.Format("No data was found");
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
return Request.CreateResponse(HttpStatusCode.OK, data);
}
Any help would be very much appreciated.

Please, try change this:
[Queryable(PageSize = 10)]
For this:
[Queryable(PageSize = 10, EnsureStableOrdering = false)]
More informations here.
Hope that helps!
See ya!

Related

Dynamic where clause with two entity

I need a filter between two entity.
Have two tables 1.User 2.Product
Product map with the User table.
I am going to create a dynamic where filter.
I need to find out all the users which have 'test' product.
Conditions: if userFilter count is 0 then I need all test product with the respected user.
If userFilter is there and productFilter is there then below code is working but if userFilter is not there and productFilter is there then it returning 0 row. How can I find the users which have test product? ?
Here is my Code.
public IHttpActionResult GetFilter()
{
var userFilters = new List<Filter>()
{
new Filter { PropertyName = "Username" ,
Operation = Op .Equals, Value = "Karan" },
};
var productfilter = new List<Filter>()
{
new Filter { PropertyName = "Name" ,
Operation = Op .Equals, Value = "Test product" }
};
Func<User, bool> deleg = x => true;
Func<Product, bool> delegProduct = x => true;
if (userFilters.Count > 0)
{
deleg = ExpressionBuilder.GetExpression<User>(userFilters).Compile();
}
if (productfilter.Count > 0)
{
delegProduct = ExpressionBuilder.GetExpression<Product>(productfilter).Compile();
}
var resultt = _localmarketEntities.Users.Where(deleg)
.Select(x => new
{
x.Id,
x.Username,
Product = x.Products.Where(delegProduct).Select(y => new
{
y.Id,
y.Name
}).ToList()
})
.ToList();
return Ok(resultt);
}
if i understand correct, you need all users that have test product when userFiler count is 0.
List<User> res;
var user = _localmarketEntities.Users.Where(deleg).ToList();
if (user.Count == 0) {
res = _localmarketEntities.Products.Where(delegProduct).Select(q => new User() {
Id = q.Id,
Username = q.Username,
Product = q
}).ToList();
}
else {
res = _localmarketEntities.Users.Where(deleg)
.Select(x => new
{
x.Id,
x.Username,
Product = x.Products.Where(delegProduct).Select(y => new
{
y.Id,
y.Name
}).ToList()
})
.ToList();
}

how to get count new message found as per enquiry/ticket with two way conditions

i 'm working with crm application. i developed it finally i'm getting confused how i detect new messages as per flag must have display and message not have to true.
here is my db schema for understanding problem.
here is my constructed query to get new message count :
int new_messages = 0;
foreach (var enquiry in db.Enquiries.Where(i => (i.ForwardTo.Equals(userid) || i.AttendBy.Equals(userid))).ToList())
{
if (enquiry != null)
{
bool IsIns = true;
foreach (var flag in db.Flags.Where(f => f.Enquiry_History_id.Equals(enquiry.Ref_no) && f.User_id.Equals(userid)).Select(f => new { IsDisplay = f.IsDisplay }).ToList())
{
if (flag != null)
{
if (flag.IsDisplay == false)
{
IsIns = false;
}
}
}
if (IsIns == true)
{
foreach (var message in db.Messages.Where(m => m.Enquiry_History_id.Equals(enquiry.Ref_no) && m.User_id.Equals(userid)).Select(m => new { IsRead = m.IsRead }).ToList())
{
if (message.IsRead == true)
{
//do another stuff
}
else
{
new_messages++;
}
}
}
}
}
lbl_msg.Text = new_messages.ToString();
here i have to take each enquiry that have been AttendBy or ForwardBy to user and check it first it should be display is not false and after that check as per each message should not have IsRead to true. i'm trying with my best way but this not gives me out put as i want.
i have an idea just insert two values one for true which generate message and second for false to froward. and at finding out only which have IsRead to false.
something like this way :
using (DataClassesDataContext db = new DataClassesDataContext())
{
string userid = db.Users.Where(u => u.Username.Equals((String)Session["Username"])).Select(u => u.Ref_no).SingleOrDefault().ToString();
bool IsIns = true;
foreach (var enquiry in db.Enquiries.Where(i => i.AttendBy.Equals(userid) || i.ForwardTo.Equals(userid)).ToList())
{
if (enquiry != null)
{
foreach (var flag in db.Flags.Where(f => f.Enquiry_History_id.Equals(enquiry.Ref_no) && f.User_id.Equals(userid)).Select(f => new { IsDisplay = f.IsDisplay }).ToList())
{
if (flag.IsDisplay == false)
{
IsIns = false;
}
if (IsIns == true)
{
foreach (var message in db.Messages.Where(m => m.Enquiry_History_id.Equals(enquiry.Ref_no)).ToList())
{
if (message != null)
{
bool IsIns1 = false;
foreach (var messageflag in db.MessageFlags.Where(mf => mf.MessageId.Equals(message.Id) && mf.UserId.Equals(userid)).Select(mf => new
{
IsRead = mf.IsRead,
User_id = mf.UserId,
Message = message.body,
CreatedDate = message.Created_date
}).ToList())
{
if (messageflag.IsRead == false)
{
IsIns1 = true;
}
if (IsIns1 == true)
{
DataRow dr = dt.NewRow();
dr["Ref_no"] = enquiry.Ref_no.ToString();
dr["Name"] = db.Users.Where(u => u.Ref_no.Equals(messageflag.User_id)).Select(u => u.FirstName + ' ' + u.LastName).SingleOrDefault().ToString();
dr["UserId"] = db.Users.Where(u => u.Ref_no.Equals(messageflag.User_id)).Select(u => u.Ref_no).SingleOrDefault().ToString();
dr["Message"] = messageflag.Message.ToString();
dr["CreatedDate"] = messageflag.CreatedDate.ToString();
dt.Rows.Add(dr);
}
}
}
}
}
}
}
}
myDataSet.Tables.Add(dt);
lbl_count_messages.Text = myDataSet.Tables[0].Rows.Count.ToString();
if (myDataSet.Tables[0].Rows.Count == 0)
{
message_alert.Visible = false;
}
Repeater_Messages.DataSource = myDataSet;
Repeater_Messages.DataBind();
}

url.Action with MvcContrib generates invalid links

In our application we use MvcContrib for generating links with the exception of cross area links where Contrib seems to be not working properly (or we are doing something wrong). In services we have a function that generates a List< ZakladkaModel > which contains url and other properties used in generating tabstrib via custom html helper. That function takes as an argument an id of database object and UrlHelper to help in link creating.
m_service.GenerowanieZakladkiDlaKontrolera_ARCH_Akt(idAktu, new UrlHelper(this.ControllerContext.RequestContext));
Then in the GenerowanieZakladkiDlaKontrolera_ARCH_Akt we have something like this:
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Akt", Url = "" });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Wzmianki", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.ARCH_WzmiankiController>(c => c.Index(idAktu)) });
if (tekstJednolity.StanTekstuJednolitego == "RB" || tekstJednolity.StanTekstuJednolitego == "SW")
{
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "t.j. aktu", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.ARCH_TekstJednolityController>(c => c.Edytuj(tekstJednolity.Id)) });
}
else
{
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "t.j. aktu", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.ARCH_TekstJednolityController>(c => c.Raport(tekstJednolity.Id)) });
}
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 1", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek1Controller>(c => c.Index(idAktu)) });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 2", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek2Controller>(c => c.Index(idAktu)) });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 3", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek3Controller>(c => c.Edytuj(idAktu)) });
model.Add(new ZakladkaModel { Aktywnosc = true, NazwaZakladki = "Przypisek 4", Url = url.Action<Usc.Presentation.Areas.FU_RAU.Controllers.ARCH.Przypisek4Controller>(c => c.Edytuj(idAktu)) });
Now the problem is that on some co-workers computers it generates links to actions properly and on some it looks like it takes a ranedom area from our app and tries to make an invalid link. We could use a simple url.Action("action","controler") which works fine on all but we would prefer MvcContrib :). Does anyone have any idea why this occurs? Or can share an alternative?
It seems that LinkBuilder which is used under doesn't use GetVirtualPatchForArea at all which as I read is MVC bug. So i decided to make my own HtmlHelper which uses that method:
public static string ActionArea<TController>(this HtmlHelper urlHelper, Expression<Action<TController>> expression) where TController : Controller
{
RouteValueDictionary routeValues = GetRouteValuesFromExpression(expression);
VirtualPathData vpd = new UrlHelper(urlHelper.ViewContext.RequestContext).RouteCollection.GetVirtualPathForArea(urlHelper.ViewContext.RequestContext, routeValues);
return (vpd == null) ? null : vpd.VirtualPath;
}
public static string ActionArea<TController>(this UrlHelper urlHelper, Expression<Action<TController>> expression) where TController : Controller
{
RouteValueDictionary routeValues = GetRouteValuesFromExpression(expression);
VirtualPathData vpd = urlHelper.RouteCollection.GetVirtualPathForArea(urlHelper.RequestContext, routeValues);
return (vpd == null) ? null : vpd.VirtualPath;
}
public static RouteValueDictionary GetRouteValuesFromExpression<TController>(Expression<Action<TController>> action) where TController : Controller
{
if (action == null)
{
throw new ArgumentNullException("action");
}
MethodCallExpression call = action.Body as MethodCallExpression;
if (call == null)
{
throw new ArgumentException("Akcja nie może być pusta.", "action");
}
string controllerName = typeof(TController).Name;
if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("Docelowa klasa nie jest kontrolerem.(Nie kończy się na 'Controller')", "action");
}
controllerName = controllerName.Substring(0, controllerName.Length - "Controller".Length);
if (controllerName.Length == 0)
{
throw new ArgumentException("Nie można przejść do kontrolera.", "action");
}
// TODO: How do we know that this method is even web callable?
// For now, we just let the call itself throw an exception.
string actionName = GetTargetActionName(call.Method);
var rvd = new RouteValueDictionary();
rvd.Add("Controller", controllerName);
rvd.Add("Action", actionName);
var namespaceNazwa = typeof(TController).Namespace;
if(namespaceNazwa.Contains("Areas."))
{
int index = namespaceNazwa.IndexOf('.',namespaceNazwa.IndexOf("Areas."));
string nazwaArea = namespaceNazwa.Substring(namespaceNazwa.IndexOf("Areas.") + 6, index - namespaceNazwa.IndexOf("Areas.") + 1);
if (!String.IsNullOrEmpty(nazwaArea))
{
rvd.Add("Area", nazwaArea);
}
}
//var typ = typeof(TController).GetCustomAttributes(typeof(ActionLinkAreaAttribute), true /* inherit */).FirstOrDefault();
/*ActionLinkAreaAttribute areaAttr = typ as ActionLinkAreaAttribute;
if (areaAttr != null)
{
string areaName = areaAttr.Area;
rvd.Add("Area", areaName);
}*/
AddParameterValuesFromExpressionToDictionary(rvd, call);
return rvd;
}
private static string GetTargetActionName(MethodInfo methodInfo)
{
string methodName = methodInfo.Name;
// do we know this not to be an action?
if (methodInfo.IsDefined(typeof(NonActionAttribute), true /* inherit */))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,
"Nie można wywoływać metod innych niż akcje.", methodName));
}
// has this been renamed?
ActionNameAttribute nameAttr = methodInfo.GetCustomAttributes(typeof(ActionNameAttribute), true /* inherit */).OfType<ActionNameAttribute>().FirstOrDefault();
if (nameAttr != null)
{
return nameAttr.Name;
}
// targeting an async action?
if (methodInfo.DeclaringType.IsSubclassOf(typeof(AsyncController)))
{
if (methodName.EndsWith("Async", StringComparison.OrdinalIgnoreCase))
{
return methodName.Substring(0, methodName.Length - "Async".Length);
}
if (methodName.EndsWith("Completed", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentUICulture,
"Nie można wywoływać kompletnych metod.", methodName));
}
}
// fallback
return methodName;
}
static void AddParameterValuesFromExpressionToDictionary(RouteValueDictionary rvd, MethodCallExpression call)
{
ParameterInfo[] parameters = call.Method.GetParameters();
if (parameters.Length > 0)
{
for (int i = 0; i < parameters.Length; i++)
{
Expression arg = call.Arguments[i];
object value = null;
ConstantExpression ce = arg as ConstantExpression;
if (ce != null)
{
// If argument is a constant expression, just get the value
value = ce.Value;
}
else
{
value = CachedExpressionCompiler.Evaluate(arg);
}
rvd.Add(parameters[i].Name, value);
}
}
}
Hope this helps people with similiar problems. Some of the code above i got from mvc2-rtm-sources modified to my needs http://aspnet.codeplex.com/releases/view/41742

MVC 3 - How to know if query returns 0 rows

Probably pretty easy, but I can't get it sorted out. I want to redirect the user to an error page if the requested id doesn't exist in the database. My code:
public ActionResult Details(int id)
{
DetailsAdViewModel DAVM = new DetailsAdViewModel();
DAVM.Ad = db.Ads.Include("Images").Where(a => a.AdId == id).First();
DAVM.FirstImage = db.Images.Where(a => a.AdId == id).OrderBy(a => a.ImageId).Take(1);
// make sure the ad isn't deleted or that it really exists
if (DAVM.Ad == null)
{
return RedirectToAction("ShowError", "Error", new { errorCode = "adDeleted" });
}
return View(DAVM);
}
This doesn't work, and there is an server error if I enter a false id.
Use .FirstOrDefault() instead of .First(). This will return null if not record is found instead of throwing an exception:
DAVM.Ad = db.Ads.Include("Images").FirstOrDefault(a => a.AdId == id);
Now you can check if DAVM.Ad is null:
if (DAVM.Ad == null)
{
return RedirectToAction("ShowError", "Error", new { errorCode = "adDeleted" });
}
Found a solution:
public ActionResult Details(int id)
{
if (db.Ads.Any(a => a.AdId == id))
{
DetailsAdViewModel DAVM = new DetailsAdViewModel();
DAVM.Ad = db.Ads.Include("Images").Where(a => a.AdId == id).First();
DAVM.FirstImage = db.Images.Where(a => a.AdId == id).OrderBy(a => a.ImageId).Take(1);
return View(DAVM);
}
else
{
return RedirectToAction("ShowError", "Error", new { errorCode = "adDeleted" });
}
}

Ordering in LINQ Statement Ineffective

I'm having trouble getting some ordering working in a LINQ statement I've been working on. Here is the code:
public static List<Contact> GetAllTheCusts(string fName,
string lName,
string middleName,
int? customerId,
string sort,
int pageIndex,
int pageSize)
{
AWEntities entities = Common.GetContext();
int skipCount = pageSize * pageIndex;
var contacts = entities.Contacts
.Include("Individuals.Customer")
.Where(c => customerId.HasValue
? c.Individuals.Any(i => i.CustomerID == customerId.Value)
: c.Individuals.Any(i => i.Customer.CustomerID == i.CustomerID))
.Where(c => string.IsNullOrEmpty(fName) || c.FirstName.Contains(fName))
.Where(c => string.IsNullOrEmpty(lName) || c.LastName.Contains(lName))
.Where(c => string.IsNullOrEmpty(middleName) || c.MiddleName.Contains(middleName));
.Select(c => c);
IOrderedQueryable<Contact> contactsOrdered = contacts.OrderByDescending(o => o.ContactID);;
return contactsOrdered.Skip(skipCount).Take(pageSize).ToList();
}
For some reason, the OrderByDescending method is not performing its role. Can anybody help please.
Cheers
Thought I would post the final working code here. This has successfully converted the stored procedure to LINQ-to-Entities:
public static List<Contact> GetCustomersWithContactDetails(string fName, string lName, string middleName, int? customerId,
string sort, int pageIndex, int pageSize, out int count)
{
AWEntities entities = Common.GetContext();
int skipCount = pageSize * pageIndex;
var contacts = entities.Contacts
.Include("Individuals.Customer")
.Where(c => customerId.HasValue
? c.Individuals.Any(i => i.CustomerID == customerId.Value)
: c.Individuals.Any(i => i.Customer.CustomerID == i.CustomerID))
.Where(c => string.IsNullOrEmpty(fName) || c.FirstName.Contains(fName))
.Where(c => string.IsNullOrEmpty(lName) || c.LastName.Contains(lName))
.Where(c => string.IsNullOrEmpty(middleName) || c.MiddleName.Contains(middleName));
// Get ordering based on the "sort" parameter
var contactsOrdered = GetOrdering(sort, contacts);
count = contacts.Count();
return contactsOrdered.Skip(skipCount).Take(pageSize).ToList();
}
private static IOrderedQueryable<Contact> GetOrdering(string sort, IQueryable<Contact> contacts)
{
IOrderedQueryable<Contact> contactsOrdered;
if (string.IsNullOrEmpty(sort))
{
contactsOrdered = contacts.OrderBy(o => o.LastName);
}
else
{
SortDirection sortDirection = sort.EndsWith("ASC", StringComparison.Ordinal)
? SortDirection.asc
: SortDirection.desc;
switch (sort.Substring(0, sort.IndexOf(' ')))
{
case "ContactID":
{
if (sortDirection == SortDirection.asc)
{
contactsOrdered = contacts.OrderBy(o => o.ContactID);
}
else
{
contactsOrdered = contacts.OrderByDescending(o => o.ContactID);
}
break;
}
case "LastName":
{
if (sortDirection == SortDirection.asc)
{
contactsOrdered = contacts.OrderBy(o => o.LastName);
}
else
{
contactsOrdered = contacts.OrderByDescending(o => o.LastName);
}
break;
}
case "FirstName":
{
if (sortDirection == SortDirection.asc)
{
contactsOrdered = contacts.OrderBy(o => o.FirstName);
}
else
{
contactsOrdered = contacts.OrderByDescending(o => o.FirstName);
}
break;
}
case "MiddleName":
{
if (sortDirection == SortDirection.asc)
{
contactsOrdered = contacts.OrderBy(o => o.MiddleName);
}
else
{
contactsOrdered = contacts.OrderByDescending(o => o.MiddleName);
}
break;
}
default:
{
contactsOrdered = contacts.OrderBy(o => o.ContactID);
break;
}
}
}
return contactsOrdered;
}
Cheers

Resources