RavenDB MultiMapReduce Sum not returning the correct value - mapreduce

Sorry for this lengthy query, I decided to add the whole test so that it will be easier for even newbies to help me with this total brain-melt.
The using directives are:
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Raven.Client;
using Raven.Client.Embedded;
using Raven.Client.Indexes;
Please leave feedback if I'm too lengthy, but what could possibly go wrong if I add a complete test?
[TestFixture]
public class ClicksByScoreAndCardTest
{
private IDocumentStore _documentStore;
[SetUp]
public void SetUp()
{
_documentStore = new EmbeddableDocumentStore {RunInMemory = true}.Initialize();
_documentStore.DatabaseCommands.DisableAllCaching();
IndexCreation.CreateIndexes(typeof (ClicksBySearchAndProductCode).Assembly, _documentStore);
}
[TearDown]
public void TearDown()
{
_documentStore.Dispose();
}
[Test]
public void ShouldCountTotalLeadsMatchingPreference()
{
var userFirst = new User {Id = "users/134"};
var userSecond = new User {Id = "users/135"};
var searchFirst = new Search(userFirst)
{
Id = "searches/24",
VisitId = "visits/63"
};
searchFirst.Result = new Result();
searchFirst.Result.Rows = new List<Row>(
new[]
{
new Row {ProductCode = "CreditCards/123", Score = 6},
new Row {ProductCode = "CreditCards/124", Score = 4}
});
var searchSecond = new Search(userSecond)
{
Id = "searches/25",
VisitId = "visits/64"
};
searchSecond.Result = new Result();
searchSecond.Result.Rows = new List<Row>(
new[]
{
new Row {ProductCode = "CreditCards/122", Score = 9},
new Row {ProductCode = "CreditCards/124", Score = 4}
});
var searches = new List<Search>
{
searchFirst,
searchSecond
};
var click = new Click
{
VisitId = "visits/64",
ProductCode = "CreditCards/122",
SearchId = "searches/25"
};
using (var session = _documentStore.OpenSession())
{
foreach (var search in searches)
{
session.Store(search);
}
session.Store(click);
session.SaveChanges();
}
IList<ClicksBySearchAndProductCode.MapReduceResult> clicksBySearchAndProductCode = null;
using (var session = _documentStore.OpenSession())
{
clicksBySearchAndProductCode = session.Query<ClicksBySearchAndProductCode.MapReduceResult>(ClicksBySearchAndProductCode.INDEX_NAME)
.Customize(x => x.WaitForNonStaleResults()).ToArray();
}
Assert.That(clicksBySearchAndProductCode.Count, Is.EqualTo(4));
var mapReduce = clicksBySearchAndProductCode
.First(x => x.SearchId.Equals("searches/25")
&& x.ProductCode.Equals("CreditCards/122"));
Assert.That(mapReduce.Clicks,
Is.EqualTo(1));
}
}
public class ClicksBySearchAndProductCode :
AbstractMultiMapIndexCreationTask
<ClicksBySearchAndProductCode.MapReduceResult>
{
public const string INDEX_NAME = "ClicksBySearchAndProductCode";
public override string IndexName
{
get { return INDEX_NAME; }
}
public class MapReduceResult
{
public string SearchId { get; set; }
public string ProductCode { get; set; }
public string Score { get; set; }
public int Clicks { get; set; }
}
public ClicksBySearchAndProductCode()
{
AddMap<Search>(
searches =>
from search in searches
from row in search.Result.Rows
select new
{
SearchId = search.Id,
ProductCode = row.ProductCode,
Score = row.Score.ToString(),
Clicks = 0
});
AddMap<Click>(
clicks =>
from click in clicks
select new
{
SearchId = click.SearchId,
ProductCode = click.ProductCode,
Score = (string)null,
Clicks = 1
});
Reduce =
results =>
from result in results
group result by
new { SearchId = result.SearchId, ProductCode = result.ProductCode }
into g
select
new
{
SearchId = g.Key.SearchId,
ProductCode = g.Key.ProductCode,
Score = g.First(x => x.Score != null).Score,
Clicks = g.Sum(x => x.Clicks)
};
}
}
public class User
{
public string Id { get; set; }
}
public class Search
{
public string Id { get; set; }
public string VisitId { get; set; }
public User User { get; set; }
private Result _result = new Result();
public Result Result
{
get { return _result; }
set { _result = value; }
}
public Search(User user)
{
User = user;
}
}
public class Result
{
private IList<Row> _rows = new List<Row>();
public IList<Row> Rows
{
get { return _rows; }
set { _rows = value; }
}
}
public class Row
{
public string ProductCode { get; set; }
public int Score { get; set; }
}
public class Click
{
public string VisitId { get; set; }
public string SearchId { get; set; }
public string ProductCode { get; set; }
}
My problem here is that I expect Count to be one in that specific test, but it just doesn't seem to add the Clicks in the Click map and the result is 0 clicks. I'm totally confused, and I'm sure that there is a really simple solution to my problem, but I just can't find it..
..hope there is a week-end warrior out there who can take me under his wings.

Yes, it was a brain-melt, for me non-trivial, but still. The proper reduce should look like this:
Reduce =
results =>
from result in results
group result by
new { SearchId = result.SearchId, ProductCode = result.ProductCode }
into g
select
new
{
SearchId = g.Key.SearchId,
ProductCode = g.Key.ProductCode,
Score = g.Select(x=>x.Score).FirstOrDefault(),
Clicks = g.Sum(x => x.Clicks)
};
Not all Maps had the Score set to a non-null-value, and therefore my original version had a problem with:
Score = g.First(x => x.Score != null).Score
Mental note, use:
Score = g.Select(x=>x.Score).FirstOrDefault()
Don't use:
Score = g.First(x => x.Score != null).Score

Related

How to access a list inside a class and return as a list of items in asp.netcore?

I have a class showbookings with salesinformation list.
public class ShowBookings
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string ShowId { get; set; }
public DateTime ShowTime { get; set; }
public List<SalesInformation> SalesInformation { get; set; }
}
public class SalesInformation
{
public string SeatNo { get; set; }
public string SalesOrderConfirmationId { get; set; }
}
While calling update method I need to update for SeatNo and SalesOrderConfirmationId but this list is not accessible to me inside for loop.I need to return the list of items after updating showid,seatno SalesOrderConfirmationId but item.SalesInformation = salesInfo shows an error cannot convert salesinformation to generic list.Pls let me know how to sort this issue
public async Task<ActionResult<List<ShowBookings>>> UpdateShowBookings(string ShowId, string SeatNo, string SalesOrderConfirmationId)
{
var showBookings = new List<ShowBookings>();
var salesInformation = new List<SalesInformation>();
showBookings = await _context.DbCollection.Find(ShowBookings => ShowBookings.ShowId == ShowId)
.ToListAsync().ConfigureAwait(false);
if (showBookings != null)
{
var _sbList = showBookings.ToList();
foreach (var item in _sbList)
{
var salesInfo = new SalesInformation();
item.ShowId = ShowId;
salesInfo.SeatNo = SeatNo;
item.SalesInformation = salesInfo;
_sbList.Add(item);
}
return _sbList;
}
else
{
return new List<ShowBookings>();
}
}
"SalesInformation" is a list, while salesInfo is a object. You need to do:
item.SalesInformation.Add(salesInfo);
Also, in ShowBooking, inside constructor, initialize your List, else you will receive NullReferenceException.
Try to use
item.SalesInformation = new List<SalesInformation> { salesInfo };
SalesInformation of ShowBookings is List<SalesInformation> type,so you need to set its value with a list.
you already have list of showbookings
public async Task<ActionResult<List<ShowBookings>>> UpdateShowBookings(string ShowId, string SeatNo, string SalesOrderConfirmationId)
{
var salesInformation = new List<SalesInformation>();
var showBookings = await _context.DbCollection.Find(ShowBookings => ShowBookings.ShowId == ShowId)
.ToListAsync().ConfigureAwait(false);
if (showBookings != null)
{
return showBookings;
}
else
{
return new List<ShowBookings>();
}
}

wpf DataGrid set itemsource List<object>

I have a problem with DataGrid in wpf
this is a class :
class Superviser
{
public long Id = 0;
public string name = "";
public string father = "";
public string code = "";
}
and this is a function that build a list of this class object
public List<Superviser> allSuperviser()
{
return db.tbPersons.Where(i => i.level == StaticsObject.isSuperviser).Select(x => new Superviser
{
Id = x.Id,
name = x.firstName,
father = x.father,
code = x.code,
}).ToList();
}
and I use this code to set this list in datagrid
dgvPerson.ItemsSource = classPerson.allSuperviser();
but when run program datagrid is empty !
tip : The list is not empty.
Where is the problem?
How do I display this list on DataGrid?
hello agian i solved it
I changed class to :
class Superviser
{
public long Id { get; set; }
public string name { get; set; }
public string father { get; set; }
public string code { get; set; }
public Superviser() { }
public Superviser(long Id, string name, string father, string code)
{
this.Id = Id;
this.name = name;
this.father = father;
this.code = code;
}
}
and change function to :
public List<Superviser> allSuperviser()
{
return db.tbPersons.Where(i => i.level == StaticsObject.isSuperviser).Select(x => new Superviser { Id = x.Id, name = x.firstName + " " + x.lastName, father = x.father, code = x.code }).ToList();
}
And the problem was fixed :)

How to get meta tags value from search engine optimization in SharePoint 2013

¿How to read meta tags in SharePoint 2013 in every page with friendly url?
Thanks in advance.
Ok,
I found the answer debuggin, this work for me.
public class SEOProperties {
public string PropBrowserTitle { get; set; }
public string PropBrowserDescription { get; set; }
public string PropBrowserKeyWords { get; set; }
public string PropBrowserSiteNoIndex { get; set; }
}
private SEOProperties GetSEOProperties(){
SEOProperties SEO = new SEOProperties();
if (SPContext.Current != null)
{
Guid siteGuid = SPContext.Current.Site.ID;
Guid webGuid = SPContext.Current.Web.ID;
using (SPSite site = new SPSite(siteGuid))
{
using (SPWeb web = site.OpenWeb())
{
TaxonomySession session = new TaxonomySession(site);
NavigationTerm navTermino = TaxonomyNavigationContext.Current.NavigationTerm;
Term termino = navTermino.GetTaxonomyTerm(session);
var SEOPropBrowserTitle = termino.LocalCustomProperties.Where(o => o.Key == "_Sys_Seo_PropBrowserTitle").SingleOrDefault();
var SEOPropDescription = termino.LocalCustomProperties.Where(o => o.Key == "_Sys_Seo_PropDescription").SingleOrDefault();
var SEOPropKeyWords = termino.LocalCustomProperties.Where(o => o.Key == "_Sys_Seo_PropKeywords").SingleOrDefault();
var SEOPropSiteNoIndex = termino.LocalCustomProperties.Where(o => o.Key == "_Sys_Seo_PropSitemapNoIndex").SingleOrDefault();
SEO.PropBrowserDescription = SEOPropDescription.Value;
SEO.PropBrowserKeyWords = SEOPropKeyWords.Value;
SEO.PropBrowserSiteNoIndex = SEOPropSiteNoIndex.Value;
SEO.PropBrowserTitle = SEOPropBrowserTitle.Value;
}
}
}
return SEO;
}

Dictionary int, myclass

That's my class
public class PersonelAtama
{
public int PersonelID { get; set; }
public int YonetimTalepID { get; set; }
public bool durum { get; set; }
}
I want to doDictionary<int,list<myclass>>
Dictionary<int, List<PersonelAtama>>
PersonelAtamaListesi = new Dictionary<int, List<PersonelAtama>>();
How to insert into the list
PersonelAtamaListesi.Add
How assignments are made
PersonelAtamaListesi[0][1]
PersonelAtamaListesi.Add(0,new PersonelAtama()
{
PersonelID = personelID,
YonetimTalepID = yonetimTalepID,
durum = false
});
assignment into the list and how to use again
I want to add to the list and component values to achieve. I want to sample code.
You have List as TValue so:
PersonelAtamaListesi.Add(0, new List<PersonelAtama>()
{
new PersonelAtama()
{
PersonelID = 1,
YonetimTalepID = 2,
durum = false
},
new PersonelAtama()
{
PersonelID = 11,
YonetimTalepID = 222,
durum = true
}
});

Saving my list to Isolated Storage

I'm having an issue while saving my list items to isolated storage.(Windows Phone 7)
Here is how I defined my list class; I'm using data binding
public class CTransaction
{
public String Date1 { get; set; }
public String Amount1 { get; set; }
public String Type1 { get; set; }
public String Time1 { get; set; }
public String Dis1 { get; set; }
public String Def1 { get; set; }
public CTransaction(String date1, String amount1, String type1, String time1, String dis1, String def1)
{
this.Date1 = date1;
this.Amount1 = amount1;
this.Time1 = time1;
this.Dis1 = dis1;
this.Def1 = def1;
switch (type1)
{
case "FR":
this.Type1 = "Images/a.png";
break;
case "TA":
this.Type1 = "Images/b.png";
break;
case "DA":
this.Type1 = "Images/c.png";
break;
case "CC":
this.Type1 = "Images/mount.png";
break;
}
}
}
Here is how I insert the items to my list; I'm assigning something to the fields and then I'm inserting this into my list like;
List<CTransaction> ctransactionList = new List<CTransaction>();
//some list item filling operations here***
ctransactionList.Insert(0, new CTransaction(DefaultDate, DefaultAmount, RandomType, Times, Dist, Defin));//This one inserts at the top of my list
CTransactionList.ItemsSource = null;
CTransactionList.ItemsSource = ctransactionList; //These two operations refreshes my list
!!Yes, you see how I insert and create my list. Everything is OK. now I want to save ctransactionList
Here is How I save it;(by clicking a button)
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("saver"))
{
store.DeleteFile("saver");
}
using (var stream = new IsolatedStorageFileStream("saver", FileMode.OpenOrCreate, FileAccess.Write, store))
{
var serializer = new XmlSerializer(typeof(List<CTransaction>));
serializer.Serialize(stream, ctransactionList);
}
Here is How I load it (By clicking another button)
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("saver"))
{
using (var stream = new IsolatedStorageFileStream("saver", FileMode.OpenOrCreate, FileAccess.Read, store))
{
var reader = new StreamReader(stream);
if (!reader.EndOfStream)
{
var serializer = new XmlSerializer(typeof(List<CTransaction>));
ctransactionList = (List<CTransaction>)serializer.Deserialize(reader);
}
}
}
While debugging, saving operation seems consistent and not raising any error, but while loading; this is the raised error at this line;
ctransactionList = (List<CTransaction>)serializer.Deserialize(reader);
ERROR: There is an error in XML document (3, 4).
If you can help me, I'd really appreciate it.
Thanks in advance
Try this to make your class serializable:
[DataContract]
public class CTransaction
{
[DataMember]
public String Date1 { get; set; }
[DataMember]
public String Amount1 { get; set; }
[DataMember]
public String Type1 { get; set; }
[DataMember]
public String Time1 { get; set; }
[DataMember]
public String Dis1 { get; set; }
[DataMember]
public String Def1 { get; set; }
public CTransaction(String date1, String amount1, String type1, String time1, String dis1, String def1)
{
//your code
}
}
then change the load and save methods to:
public List<CTransaction> LoadFromIsolatedStorage()
{
List<CTransaction> ret = new List<CTransaction>();
try
{
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("saver"))
{
using (var stream = new IsolatedStorageFileStream("saver", FileMode.OpenOrCreate, FileAccess.Read, store))
{
if (stream.Length > 0)
{
DataContractSerializer dcs = new DataContractSerializer(typeof(List<CTransaction>));
ret = dcs.ReadObject(stream) as List<CTransaction>;
}
}
}
}
catch (Exception ex)
{
// handle exception
}
}
public void SaveToIsolatedStorage(List<CTransaction> listToSave)
{
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("saver"))
{
store.DeleteFile("saver");
}
using (var stream = new IsolatedStorageFileStream("saver", FileMode.OpenOrCreate, FileAccess.Write, store))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(List<CTransaction>));
dcs.WriteObject(stream, ctransactionList);
}
}