Why does RavenDB return a wrong total result count? - ravendb

As shown in the following unit test I expect stats.TotalResults to be 2 but is 3. Why is that?
[Test]
public void RavenQueryStatisticsTotalResultsTest1()
{
using (var db = _documentStore.OpenSession())
{
db.Store(new Club { Name = "Foo1", Type = "Amateur" }); // --> Matches all conditions
db.Store(new Club { Name = "Foo2", Type = "Professional" });
db.Store(new Club { Name = "Foo3", Type = "Amateur" }); // --> Matches all conditions
db.Store(new Club { Name = "Boo1", Type = "Amateur" });
db.Store(new Club { Name = "Boo2", Type = "Professional" });
db.SaveChanges();
}
WaitForIndexing(_documentStore);
using (var db = _documentStore.OpenSession())
{
RavenQueryStatistics stats;
var query = db.Query<Club>()
.Statistics(out stats)
.Where(club => club.Type == "Amateur")
.Intersect()
.Search(club => club.Name, "Foo*", escapeQueryOptions: EscapeQueryOptions.AllowPostfixWildcard);
var clubs = query.ToList();
Assert.AreEqual(2, clubs.Count);
Assert.AreEqual(2, stats.TotalResults); // I expect 2 but was 3! Why is that?
}
}

You need Intersect when using multiple where clauses. To combine Where and Search, you have to pass SearchOptions.And to Search:
using (var db = _documentStore.OpenSession()) {
RavenQueryStatistics stats;
var query = db.Query<Club>()
.Customize(_ => _.WaitForNonStaleResultsAsOfLastWrite())
.Statistics(out stats)
.Where(club => club.Type == "Amateur")
.Search(
club => club.Name,
"Foo*",
escapeQueryOptions: EscapeQueryOptions.AllowPostfixWildcard,
options:SearchOptions.And);
var clubs = query.ToList();
Assert.AreEqual(2, clubs.Count);
Assert.AreEqual(2, stats.TotalResults);
}

Related

how to add conditional where parameters to sql query in node js

I have the below method that aims to filter records from a table. But sometimes, the user might only select one filter or two. I want to add where conditions only for parameters that the user sends. At the moment, it filters with all conditions. One possibility I know is to use some conditions to concatenate the string if true but I do not think this is the best way.
Any better way of doing this?
// Retrieve hotels by filter
app.get('/filter', (request, response) => {
var name = request.query.name;
var country = request.query.country;
var freeWifi = request.query.freeWifi;
var freeParking = request.query.freeParking;
var restaurant = request.query.restaurant;
var pool = request.query.pool;
var gym = request.query.gym;
var airconditioning = request.query.airconditioning;
let query = `select * from hotels h inner join hotelFilters hf on h.id = hf.hotelId where h.title like "%${isNullOrUndefined(name) ? '' : name}%"
and hf.freeWifi = ${freeWifi} and hf.freeParking = ${freeParking} and hf.restaurant = ${restaurant} and hf.outdoorPool = ${pool}
and hf.airConditioning = ${airconditioning}
and hf.gym = ${gym}`;
connection.query(query, (error, result) => {
if (error) {
console.log(error, 'Error occurred with hotels/filter API...');
}
if (result.length > 0) {
response.send({
result
})
}
})
});

_userManager.ReplaceClaimAsync error Id = 414, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"

In my controller asp.net core 6.0 I got this error when execute ReplaceClaimAsync:
Id = 414, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
var user11 = _userManager.FindByIdAsync(User.Id).Result;
user11.Email = user.Email;
var Result = _userManager.UpdateAsync(user11).Result;
if (!Result.Succeeded)
{
ModelState.AddModelError(Result.Errors.First().Code, Result.Errors.First().Description);
//throw new Exception(result.Errors.First().Description);
return BadRequest(ModelState);
}
var claimsOriginaux = _userManager.GetClaimsAsync(user11);
var claimOld = claimsOriginaux.Result.FirstOrDefault(r => r.Type == JwtClaimTypes.GivenName);
var claimNew = new Claim(JwtClaimTypes.GivenName, User.GivenName);
if (claimNew.Value != claimOld.Value)
{
var temp = _userManager.ReplaceClaimAsync(user11, claimOld, claimNew);
}
return NoContent(); //success
Any clue?
You are calling a bunch of async methods, and you are not using them the way you should.
You should await all async methods, instead of calling the .Result property.
Using await
var user11 = await _userManager.FindByIdAsync(User.Id);
user11.Email = user.Email;
var Result = await _userManager.UpdateAsync(user11);
if (!Result.Succeeded)
{
ModelState.AddModelError(Result.Errors.First().Code, Result.Errors.First().Description);
//throw new Exception(result.Errors.First().Description);
return BadRequest(ModelState);
}
var claimsOriginaux = await _userManager.GetClaimsAsync(user11);
var claimOld = claimsOriginaux.Result.FirstOrDefault(r => r.Type == JwtClaimTypes.GivenName);
var claimNew = new Claim(JwtClaimTypes.GivenName, User.GivenName);
if (claimNew.Value != claimOld.Value)
{
var temp = await _userManager.ReplaceClaimAsync(user11, claimOld, claimNew);
}
return NoContent(); //success
or
Using GetAwaiter()
var user11 = _userManager.FindByIdAsync(User.Id).GetAwaiter().GetResult();
user11.Email = user.Email;
var Result = _userManager.UpdateAsync(user11).GetAwaiter().GetResult();
if (!Result.Succeeded)
{
ModelState.AddModelError(Result.Errors.First().Code, Result.Errors.First().Description);
//throw new Exception(result.Errors.First().Description);
return BadRequest(ModelState);
}
var claimsOriginaux = _userManager.GetClaimsAsync(user11).GetAwaiter().GetResult();
var claimOld = claimsOriginaux.Result.FirstOrDefault(r => r.Type == JwtClaimTypes.GivenName);
var claimNew = new Claim(JwtClaimTypes.GivenName, User.GivenName);
if (claimNew.Value != claimOld.Value)
{
var temp = _userManager.ReplaceClaimAsync(user11, claimOld, claimNew).GetAwaiter().GetResult();
}
return NoContent(); //success

How to avoid duplicated headlines from news api?

I am using a news api where I am often getting many duplicate headlines. How can I adapt my code to avoid this?
final response = await http.get(url);
final jsonData = jsonDecode(response.body);
if (jsonData[Strings.status] == Strings.ok) {
jsonData[Strings.articles].forEach((element) {
if (element[Strings.urlToImg] != null &&
element[SharedStrings.description] != null) {
ArticleModel articleModel = ArticleModel(
title: element[SharedStrings.title],
author: element[Strings.author],
description: element[SharedStrings.description],
url: element[Strings.urlText],
urlToImage: element[Strings.urlToImg],
content: element[Strings.content], //context
);
news.add(articleModel);
getNews() async {
News newsClass = News();
await newsClass.getNews();
articles = newsClass.news;
setState(() => _loading = false);
}
before the line
news.add(articleModel);
Add this:
var isDuplicated = false;
for (var new in news) {
if (new.title == articleModel.title) {
isDuplicated = true;
}
}
if (!isDuplicated) {
// Now you can add it
news.add(articleModel);
}

How to fetch dynamic table list in MVC and angularJS

I'm getting a list in my angular.js file (EditDeleteItem.js) which I'm making based on the selected table name.
The function to send my list is as below:-
$scope.SaveTblRecord = function (list) {
//alert(JSON.stringify($scope.employeeList));
$scope.FetchTableName();
//var Data = $.param({ TblData: $scope.MyTblDataList });
var itemList = [];
angular.forEach(list, function (value, key) {
if (list[key].selected) {
itemList.push(list[key].selected);
}
});
$scope.ItemsList = [];
$scope.ItemsList = itemList;
$http({
method: "Post",
url: "/Admin/SaveTblData",
data: $scope.ItemsList,
}).success(function (data) {
$scope.GetTblData($scope.TempName);
}).error(function (err) {
alert(err.Message);
})
};//SaveTblRecord
Now in my Controller I want to fetch that list based on the selected table name but I can't do it :-
public JsonResult SaveTblData(List<LocationTbl> NewTblList) //Need To Have TableName here instead of LocationTbl so that selected table name list is fetched.
{
string MyTableName = Convert.ToString(TempData["TableName"]);
try
{
if (NewTblList == null)
{
return new JsonResult { Data = "Empty Selection", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else {
using (EBContext db = new EBContext())
{
bool results = false;
Type tableType = typeof(CourseDesc);
switch (MyTableName)
{
//case "CourseTbl":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var CtObj = NewTblList[i];
// CourseTbl ct = db.Courses.AsNoTracking().FirstOrDefault(x => x.ID == CtObj.ID);
// results = UtilityMethods<CourseTbl, int>.EditEntity(db, CtObj);
// }
// break;
//case "CourseDescTbl":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var CdtObj = NewTblList[i];
// CourseDesc cd = db.CourseDesc.AsNoTracking().FirstOrDefault(x => x.ID == CdtObj.ID);
// results = UtilityMethods<CourseDesc, int>.EditEntity(db, CdtObj);
// }
// break;
//case "CourseSubDesc":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var CsdObj = NewTblList[i];
// CourseSubDesc csd = db.CourseSubDesc.AsNoTracking().FirstOrDefault(x => x.ID == CsdObj.ID);
// results = UtilityMethods<CourseSubDesc, int>.EditEntity(db, CsdObj);
// }
// break;
//case "InternTbl":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var ItObj = NewTblList[i];
// InternShip It = db.Interns.AsNoTracking().FirstOrDefault(x => x.ID == ItObj.ID);
// results = UtilityMethods<InternShip, int>.EditEntity(db, ItObj);
// }
// break;
case "LocationTbl":
for (int i = 0; i < NewTblList.Count; i++)
{
var LtObj = NewTblList[i];
LocationTbl lt = db.Loc.AsNoTracking().FirstOrDefault(x => x.ID == LtObj.ID);
results = UtilityMethods<LocationTbl, int>.EditEntity(db, LtObj);
}
break;
}
var resultList = new List<object>();
foreach (var item in db.Set(tableType))
{
resultList.Add(item);
}
return new JsonResult { Data = resultList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}
catch (Exception ex)
{
return new JsonResult { Data = ex.Message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
I've been searching the internet for a while and found some related links like Link1
and Link2
But I can't find solution to my problem. Please HELP!!

sample of kendo combo for relation table with id and value

i'm using kendo ui in my asp.net mvc 4 with razor views and encounter problem with kendo combo when the list load from an action via ajax with sending parameters to the server like the sample here:HERE
becuase the table has more then 2,000 rows.
when i load the edit page, the combo load and filter the data as expected, but the value of this field is - [object object].
i did declare the .DataTextField("ProffName") + .DataValueField("ID")
My ClientsController:
public ActionResult Edit(int id = 0)
{
Clients clients = db.Clients.Find(id);
if (clients == null)
{
return HttpNotFound();
}
ViewData["MyAgency"] = new SelectList(db.Agency, "ID", "AgentName", clients.AgencyId);
ViewData["MyCategory1"] = new SelectList(db.CategoryTbl, "ID", "category", clients.CategoryId);
List<SelectListItem> obj = new List<SelectListItem>();
obj.Add(new SelectListItem { Text = "male", Value = "1" });
obj.Add(new SelectListItem { Text = "female", Value = "2" });
obj.Add(new SelectListItem { Text = "choose", Value = "0" });
ViewData["MyMin"] = obj;
ViewBag.ProffID = new SelectList(db.ProfTBL, "ID", "ProffName", clients.ProffID);
ViewBag.Metapel = new SelectList(db.Workers, "ID", "WorkerName", clients.Metapel);
return View(clients);
}
My ProffController:
public ActionResult ProffVM_Read(string text)
{
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName });
if (!string.IsNullOrEmpty(text))
{
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text));
}
return Json(Proff_Tbl, JsonRequestBehavior.AllowGet);
}
and the Kendo combo:
#Html.Label("Proff")
#(Html.Kendo().ComboBoxFor(model => model.ProffID)
.Name("proffCbo")
.DataTextField("ProffName")
.DataValueField("ID")
.Events(e => e
.Select("proffCbo_select")
.Change("proffCbo_change")
)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("ProffVM_Read", "Proff")
.Data("onAdditionalData");
});
})
)
where am i wrong ???
i can change this combo to textbox but... i have to realize the magic.
Thanks
Change these two lines
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName });
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text));
to
var Proff_Tbl = db.ProfTBL.Select(proff => new ProffVm { ID = proff.ID, ProffName = proff.ProffName }).ToList();
Proff_Tbl = Proff_Tbl.Where(p => p.ProffName.Contains(text)).ToList();