How to write test class for salesforce email template - unit-testing

I'm struggling to write a test class for visualforce email template that I have created as per business requirements but I don't know who to cover "get' methods in the test class.. I spent long hours doing research on google unfortunately I haven't found anything helpful.
I tried many ways to cover 'get' method in test class like below
myClass cls = new myClass;
cls.getMethod();
cls.getProperty = 'test';
but it's giving me the error message "List index out of bounds: 0" because I'm calling another method in getter and that methods takes list of records
Controller Class:
public class JobChangesEmail_ComplianceTeam_Cls {
public string jobId {get; set;}
// public string jUrl{get; }
// public string clientUrl {get; }
// public string endclientUrl {get;}
public static list<job__c> jobs;
public JobChangesEmail_ComplianceTeam_Cls()
{
jobs = [select j.Id,j.name,j.other_location__c,j.account__c,j.account__r.id, j.account__r.name,j.Job_Start_Date__c,j.Job_End_Date__c,j.Job_Status__c,j.account__r.Spreadsheet_SOPs__c,
j.account__r.Facility_SOPs__c,j.End_Client__c,End_Client__r.id,j.End_Client__r.name,j.End_Client__r.Spreadsheet_SOPs__c, j.End_Client__r.Facility_SOPs__c from Job__c j where Id=:jobId];
system.debug('-------------------------------------jobId '+jobId);
}
public list<job__c> getjbs()
{
jobs = [select j.Id,j.name,j.other_location__c,j.account__c, j.account__r.name,j.Job_Start_Date__c,j.Job_End_Date__c,j.Job_Status__c,j.account__r.Spreadsheet_SOPs__c,
j.account__r.Facility_SOPs__c,j.End_Client__c,j.End_Client__r.name,j.End_Client__r.Spreadsheet_SOPs__c, j.End_Client__r.Facility_SOPs__c from Job__c j where Id=:jobId];
system.debug('-------------------------------------jobId '+jobId);
return jobs;
}
Public static string generatejobUrl(list<job__c> jobs)
{
string jurl = System.URL.getSalesforceBaseUrl().toExternalForm() + '/'+jobs[0].Id;
return jurl;
}
Public static string generateclientUrl(list<job__c> jobs)
{
string cUrl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].account__r.id;
return cUrl;
}
Public static string generateEndclientUrl(list<job__c> jobs)
{
string endCUrl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].end_client__r.id;
return endCUrl;
}
public String getjUrl()
{
string jbUrl;
list<job__c> jobs = [select Id,name from Job__c where Id=:jobId];
jbUrl= System.URL.getSalesforceBaseUrl().toExternalForm() + '/'+jobs[0].Id;
return jbUrl;
}
public string clientUrl
{
get { return generateclientUrl(jobs); }
}
public string endclientUrl
{
get { return generateEndclientUrl(jobs); }
}
}
Test class I have written so far:
#isTest(seeAllData= true)
Public class JobChangesEmail_ComplianceTeam_Cls_test {
#isTest
public static void createJob()
{
string clienturl;
string endClienturl;
string joburl;
list<job__c> jobs = new list<job__c>();
Account a = new account(name='ghghghg',type='Other', Account_Status__c='Active',phone='9090909090');
insert a;
Contact contact = new Contact(FirstName='John',LastName='Adams',email='test#gamil.com',phone='14243443', accountid = a.id);
insert contact;
// Opportunity o = [Select id, Name, CloseDate ,Location__c ,AccountId from opportunity limit 1];
Job__c job = new Job__c();
job.Name = 'NewJob'; // Set to match test record
job.X_KOL__c = false; // Set to match test record
job.DE_Job_Type__c = null; // Set to match test record
job.Job_Name_Subject__c = 'TestJob';
job.Job_Start_Date__c = Date.today();
job.End_Client__c = a.Id;
job.Other_Location__c = 'SOS'; // Set to match test record
job.PM__c = 'Amber Anderson';
job.Booked_By__c = UserInfo.getUserId();
job.Account_Manager_COE__c = UserInfo.getUserId();
job.Account__c = a.Id;
job.Contact__c = contact.Id;
job.Respondent_Type__c = 'Acne';
job.Job_Status__c = 'Tentative';
job.Job_Qualification__c = 'Qualitative';
job.Recruitment_Method__c = 'Client List';
job.On_Site_Recruits__c = 5;
job.Off_Site_Recruits__c = 5;
job.London_Project_Number__c = 'Valyria';
job.Recruiting_Begin_Date__c = Date.today();
jobs.add(job);
if(jobs.size()>0)
{
insert jobs;
}
test.startTest();
clienturl = JobChangesEmail_ComplianceTeam_Cls.generateclientUrl(jobs);
endClienturl = JobChangesEmail_ComplianceTeam_Cls.generateEndclientUrl(jobs);
joburl = JobChangesEmail_ComplianceTeam_Cls.generatejobUrl(jobs);
Test.stopTest();
string cUrl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].account__r.id;
string Eurl = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+jobs[0].end_client__r.id;
string jUrl = System.URL.getSalesforceBaseUrl().toExternalForm() + '/'+jobs[0].Id;
system.assertEquals(clienturl, cUrl);
system.assertEquals(endClienturl, Eurl);
system.assertEquals(joburl, jUrl);
JobChangesEmail_ComplianceTeam_Cls cls = new JobChangesEmail_ComplianceTeam_Cls();
cls.getjbs();
string id = cls.jobId;
id = [select id from job__c limit 1].id;
system.assertNotEquals(id,job.id);
}
}
above test class is not covering get methods or properties

Related

test class for handler trigger is not covered

I did a trigger on content version ,but my handler class is not covered ,can you please explain to me why ?
please find below the code and screenshots for non covered lines
in my test class ,i created all data needed for the handler class i call the method with content version input
Trigger:
trigger contentversiontrigger on ContentVersion (before insert, before update, before delete, after insert, after update, after delete, after undelete) {
if(trigger.isAfter && trigger.isInsert) {
Bytel_ContentVersionTriggerHandler.AlignAttachementsWithOpportunity(Trigger.New);
}
}
Trigger Handler
public with sharing class Bytel_ContentVersionTriggerHandler extends TriggerHandler {
public static void AlignAttachementsWithOpportunity(List<ContentVersion> contentVersion) {
Set<Id> contentDocumentIdSet = new Set<Id>();
String Contractid;
String Opportunityid;
for (ContentVersion cv : contentVersion) {
if(cv.ContentDocumentId != null)
{
contentDocumentIdSet.add(cv.ContentDocumentId);
}
}
list<ContentDocumentLink> cdl = [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet];
id LinkedEntityId =cdl[0].LinkedEntityId ;
// List<Contract> contractList = [SELECT Id, name FROM Contract where Id =:cdl.LinkedEntityId];
list<contract> Contracts = [SELECT Id, name FROM Contract where Id =:LinkedEntityId ];
if (!Contracts.isEmpty())
{
Contractid=Contracts[0].Id;
}
// Id Contractid = [SELECT Id, name FROM Contract where Id ='8005t0000001UQFAA2' limit 1].Id;
system.debug('test trigger' +Contractid) ;
// String Contractid= String.valueof(contractList[0].Id);
system.debug('ContractId' +Contractid) ;
list<Contract> contractssecond=[SELECT id ,vlocity_cmt__OpportunityId__c FROM Contract WHERE id =:Contractid limit 1];
if (!contractssecond.isEmpty())
{
Opportunityid=contractssecond[0].vlocity_cmt__OpportunityId__c;
}
system.debug('Opportunityid' +Opportunityid) ;
Id conDoc = cdl[0].ContentDocumentId;
//if (Opportunityid!=Null & conDoc!=Null) {
if (Opportunityid!=Null ) {
//create ContentDocumentLink record
ContentDocumentLink conDocLink = New ContentDocumentLink();
conDocLink.LinkedEntityId = Opportunityid;
conDocLink.ContentDocumentId = conDoc; //ContentDocumentId Id from ContentVersion
conDocLink.shareType = 'V';
insert conDocLink;
}
}
}
Test class of handler
#isTest
public class Bytel_ContentVersionTriggerHandlerTest {
static testMethod void createattachememtns() {
insert Bytel_TestDataFactory.createByPassSettings(false); // Custom setting bypass profile
insert Bytel_TestDataFactory.createGlobalVariableSettings(); // Custom setting globalVaribale, parameter callout end-point
insert Bytel_TestDataFactory.createOpportunityRaisonEchecSettings();
insert Bytel_TestDataFactory.createOpportunityStatusSettings();
Account acc = new Account(
Name = 'Test Account',
TypeIdentifiant__c = 'SIREN',
SIREN__c = '123765982',
Statut__c = 'Prospect'
);
insert acc;
Opportunity opp = Bytel_TestDataFactory.createOpportunity(
'FILL AUTO',
'Etape10',
acc.Id,
null
);
opp.Tech_AccountIdToDelete__c = acc.id;
opp.ScoringFinancier__c = 'Vert';
opp.siren__c = '123765981';
insert opp;
Quote quote = new Quote(Name = 'devis1', OpportunityId = opp.Id);
insert quote;
Contract contract1 = new Contract(
vlocity_cmt__QuoteId__c = quote.Id,
vlocity_cmt__OpportunityId__c=opp.id,
AccountId = acc.id
);
insert contract1;
Contract contract2 = new Contract(
vlocity_cmt__QuoteId__c = quote.Id,
AccountId = acc.id,
vlocity_cmt__OpportunityId__c=opp.id
);
insert contract2;
Blob bodyBlob=Blob.valueOf('Unit Test ContentVersion Body to be insert in test class for testing the');
ContentVersion contentVersion_1 = new ContentVersion(
Title='SampleTitle',
PathOnClient ='SampleTitle.txt',
Type_de_Fichier__c='RIB',
VersionData = bodyBlob,
origin = 'H'
);
insert contentVersion_1;
Contract contra = [SELECT Id
FROM Contract WHERE Id = :contract1.Id LIMIT 1];
List<ContentVersion> contentVersion_2 = [SELECT Id, Title, ContentDocumentId
FROM ContentVersion WHERE Id = :contentVersion_1.Id ];
// ContentDocumentLink contentlink = new ContentDocumentLink();
// contentlink.LinkedEntityId = contra.id;
// contentlink.contentdocumentid = contentVersion_2.contentdocumentid;
// contentlink.ShareType = 'V';
// insert contentlink;
Bytel_ContentVersionTriggerHandler.AlignAttachementsWithOpportunity(contentVersion_2);
}
}
After a first look, I guess you forgot to add #isTest to your test method.
#isTest
static testMethod void createattachememtns() {
//Your Code
}

How to write an Apex Test Class for Importing a CSV File?

Hello! I am unable to test the written apex class.. Could you help me with this task?
Through the component, we transfer the ID of the CSV file sent to the server to the apex class, after which our apex class creates stations if there were none before, and also updates the list of sensors based on the records of the CSV file (insert/ update).
Controller Class
public inherited sharing class lwnReadCsvFileController {
#AuraEnabled
public static list<Sensor__c> readCSVFile(Id idContentDocument){
list<Sensor__c> lstSensToInsert = new list<Sensor__c>();
if(idContentDocument != null) {
// getting File Data based on document id
ContentVersion objVersion = [SELECT Id, VersionData FROM ContentVersion WHERE ContentDocumentId =:idContentDocument];
// split the file data
list<String> lstCSVLines = objVersion.VersionData.toString().split('\n');
//creating Basic Stations records
List<Base_Station__c> createdBSRec = [SELECT Name, Id From Base_Station__c];
List<Base_Station__c> newBSRec = new List<Base_Station__c>();
Set<String> uniqueSet = new Set<String>();
for ( Integer i = 1; i < lstCSVLines.size(); i++ ) {
integer coincidences = 0;
list<String> csvRowData = lstCSVLines[i].split(',');
for ( Base_Station__c rec : createdBSRec ) {
if (csvRowData[0] == rec.Name) {
coincidences++;
}
}
if ( coincidences == 0 ) {
uniqueSet.add(csvRowData[0]);
}
}
List<String> uniquelist = new List<String>(uniqueSet);
for (integer i = 0; i < uniquelist.size() ; i++) {
Base_Station__c newBS = new Base_Station__c(Name = uniquelist[i]);
NewBSRec.add(newBS);
}
upsert newBSRec;
//creating Sensor records
for(Integer i = 1; i < lstCSVLines.size(); i++){
Sensor__c objRec = new Sensor__c();
list<String> csvRowData = lstCSVLines[i].split(',');
string tempBase = csvRowData[0];
objRec.Name = csvRowData[1];
objRec.Base_Station__c = [SELECT Id From Base_Station__c Where Name = :tempBase ].id;
objRec.Sensor_ID__c = integer.valueof(csvRowData[1]);
objRec.Status__c = csvRowData[2];
objRec.Sensor_Model__c = csvRowData[3];
lstSensToInsert.add(objRec);
}
if(!lstSensToInsert.isEmpty()) {
List<Sensor__c> createdSenRec = [SELECT Name, Sensor_ID__c From Sensor__c];
for (Sensor__c sens : lstSensToInsert ) {
integer coincidences = 0;
for (Sensor__c rec : createdSenRec ) {
if (sens.Sensor_ID__c == rec.Sensor_ID__c) {
sens.id = rec.id;
update sens;
coincidences++;
}
}
if ( coincidences == 0 ) {
insert sens;
}
}
}
}
return lstSensToInsert;
}
}
Test Class 100% coverage
#isTest
public class IwnReadCsvFileControllerTest {
public static String str = 'BASE STATION,SENSOR ID,STATUS,SENSOR MODEL \n' +
'Leeds,1,Enabled ,R8 \n' +
'Glasgow Central,2,Enabled,R8';
#isTest
public static void testReadCSVFile(){
Base_Station__c newBS = new Base_Station__c(Name = 'Leeds');
upsert newBS;
Sensor__c newSensor = new Sensor__c (Name = '1', Sensor_Id__c = 1, Status__c = 'Enabled', Base_Station__c = newBs.id);
insert newSensor;
ContentVersion contentVersionInsert = new ContentVersion(
Title = 'Test',
PathOnClient = 'Test.csv',
VersionData = Blob.valueOf(str),
IsMajorVersion = true
);
insert contentVersionInsert;
Id getId = [Select ContentDocumentId From ContentVersion Where Id =:contentVersionInsert.id and isLatest=true].ContentDocumentId;
List<Sensor__c> result = lwnReadCsvFileController.readCSVFile(getId);
}
}
Your unit test class is passing a ContentVersion Id:
List<Sensor__c> result = lwnReadCsvFileController.readCSVFile(contentVersionInsert.Id);
but your class is treating this Id as a ContentDocument Id:
public static list<Sensor__c> readCSVFile(Id idContentDocument){
if(idContentDocument != null) {
ContentVersion objVersion = [
SELECT Id, VersionData
FROM ContentVersion
WHERE ContentDocumentId =:idContentDocument
];
Your test class needs to query for the ContentDocumentId of the newly-inserted ContentVersion and pass that Id into your class under test.

Record system list of customers each with list of cars

I am working on a simple simulation for a mechanic record system where it will contain a list of customers and their details; each having a list of cars which they own. Every visit will also be recorded.
Customer: Name, address, list of cars (with make, model and reg number)
Visit: Date, Owner, Car, Description on work done, Date of next visit
In the main method i need to simulate the creation of two clients with each having 5 cars each. The data will be hard coded. Then need to add 7 visit and display all info.
class Human
{
int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string address;
public string Address
{
get { return address; }
set { address = value; }
}
}
class Customer : Human
{
public LinkedList<Car> Cars = new LinkedList<Car>();
public Customer()
{
}
}
public class Visit
{
public int visitId { get; set; }
public DateTime DateTimeVisited { get; set; }
public string customer { get; set; }
public string Discussion { get; set; }
public DateTime NextDateTimetoVisit { get; set; }
}
class Mechanic :Human
{
public LinkedList<Customer> customerDetails;
public LinkedList<Visit> visitDetails;
public LinkedList<Car> carDetails;
public Mechanic()
{
customerDetails = new LinkedList<Customer>();
visitDetails = new LinkedList<Visit>();
carDetails = new LinkedList<Car>();
}
public void AddCustomer(Customer c)
{
customerDetails.AddLast(c);
}
public void AddVisit(Visit v)
{
visitDetails.AddLast(v);
}
public LinkedList<Customer> ViewCustomer()
{
return customerDetails;
}
public LinkedList<Visit> ViewVisit()
{
return visitDetails;
}
public void AddCar(Car car)
{
carDetails.AddLast(car);
}
}
//Main
//Create customer
Customer customer1 = new Customer();
Customer customer2 = new Customer();
customer1.Id = 1;
customer1.Name = "Brandon Spiteri";
customer1.Address = "22, St. George's St. B'bugia";
mech1.AddCustomer(customer1);
Car car1 = new Car();
car1.carmake = "Hyundai";
car1.carmodelnum = "HJ30NAEJJ";
car1.carregnum = "BAH 864";
car1.Id = 1; //check
mech1.AddCar(car1);
//mech1.AddCar(car1);
Car car2 = new Car();
car2.carmake = "Citroen";
car2.carmodelnum = "HJ30NAEJJ";
car2.carregnum = "IBE 554";
car2.Id = 1;
mech1.AddCar(car2);
Car car3 = new Car();
car3.carmake = "Toyota";
car3.carmodelnum = "HJ30NAEJJ";
car3.carregnum = "DAP 691";
car3.Id = 1;
mech1.AddCar(car3);
Car car4 = new Car();
car4.carmake = "Nissan";
car4.carmodelnum = "HJ30NAEJJ";
car4.carregnum = "EBD 482";
car4.Id = 1;
mech1.AddCar(car4);
Car car5 = new Car();
car5.carmake = "Rover";
car5.carmodelnum = "HJ30NAEJJ";
car5.carregnum = "BAD 505";
car5.Id = 1;
mech1.AddCar(car5);
customer2.Id = 2;
customer2.Name = "George Spiteri";
customer2.Address = "6, Dun A. Gambin St. Santa Lucija";
mech1.AddCustomer(customer2);
Car car6 = new Car();
car6.carmake = "Mercedes";
car6.carmodelnum = "HJ30NAEJJ";
car6.carregnum = "BAH 864";
car6.Id = 2;
mech1.AddCar(car6);
Car car7 = new Car();
car7.carmake = "BMW";
car7.carmodelnum = "HJ30NAEJJ";
car7.carregnum = "EFG 426";
car7.Id = 2;
mech1.AddCar(car7);
Car car8 = new Car();
car8.carmake = "Peugeot";
car8.carmodelnum = "HJ30NAEJJ";
car8.carregnum = "IHJ 376";
car8.Id = 2;
mech1.AddCar(car8);
Car car9 = new Car();
car9.carmake = "Mazda";
car9.carmodelnum = "HJ30NAEJJ";
car9.carregnum = "ADL 693";
car9.Id = 2;
mech1.AddCar(car9);
Car car10 = new Car();
car10.carmake = "Ford";
car10.carmodelnum = "HJ30NAEJJ";
car10.carregnum = "RGJ 486";
car10.Id = 2;
mech1.AddCar(car10);
When I debug to see if the cars are under the particular customer, they seem to be declared separately and the customers have no cars. Also is the Visit class implemented correctly? Where am i going wrong? thanks
Move all lists as well as the method AddCar to the base class like this:
class Human
{
public LinkedList<Customer> customerDetails;
public LinkedList<Visit> visitDetails;
public LinkedList<Car> carDetails;
public void AddCar(Car car)
{
carDetails.AddLast(car);
}
...
}
class Customer:public Human
{
...
}

RavenDB MultiMapReduce Sum not returning the correct value

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

How to create multiple list depending on data retrieved?

I am consuming a webservice for getting the data and i am success fully getting back the data
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{ String username = txtblock4.Text.Trim();
String hash = txtblock8.Text.Trim();
client.UploadStringAsync(new
Uri("http://www.picturelove.mobi/picturelove3/getmessages.php?loginType=N&email=" +
username + "&hash=" + hash), "Post");
client.UploadStringCompleted += new
UploadStringCompletedEventHandler(client_UploadStringCompleted);
}
I am parsing the xml response like below with two functions save message data and generate message data i am gettin the data in a list.
void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
txtblock10.Text = e.Error.Message.Trim();
else
txtblock10.Text = e.Result.Trim();
String XmlString = txtblock10.Text.Trim();
using (XmlReader reader = XmlReader.Create(new StringReader(XmlString)))
{
while (reader.ReadToFollowing("all_messages"))
{
while (reader.Read())
{
try
{
reader.ReadToFollowing("id");
string id = reader.ReadElementContentAsString();
reader.MoveToAttribute("from");
string n_from = reader.ReadElementContentAsString();
reader.MoveToAttribute("to");
string n_to = reader.ReadElementContentAsString();
reader.MoveToAttribute("time");
string n_time = reader.ReadElementContentAsString();
reader.MoveToAttribute("sub");
string n_sub = reader.ReadElementContentAsString();
reader.MoveToAttribute("ct");
string n_ct = reader.ReadElementContentAsString();
reader.MoveToAttribute("txt");
string n_txt = reader.ReadElementContentAsString();
reader.MoveToAttribute("msg_image");
string n_image = reader.ReadElementContentAsString();
reader.MoveToAttribute("gender");
string n_gender = reader.ReadElementContentAsString();
reader.MoveToAttribute("name");
string n_name = reader.ReadElementContentAsString();
reader.MoveToAttribute("avatar");
string n_avatar = reader.ReadElementContentAsString();
ObservableCollection<SampleData> dataSource = new ObservableCollection<SampleData>();
dataSource.Add(new SampleData() { Name = txtblock11.Text, Text = txtblock12.Text,
Time= txtblock13.Text, Picture = txtblock9.Text });
// listBox.Items.Add(new SampleData() { Name = txtblock11.Text, Text = txtblock8.Text,
Time = txtblock5.Text, Picture = txtblock12.Text });
SaveMessageData(new SampleData() { Name = txtblock11.Text, Text = txtblock12.Text, Time
= txtblock13.Text, Picture = txtblock9.Text });
// listBox1.ItemsSource =
this.GenerateMessageData();
}
catch
{
//MessageBox.Show("No New Messages For You", "No Message", MessageBoxButton.OK);
break;
}
}
}
}
}
}
public class SampleData
{
public string Name { get; set; }
public string Text { get; set; }
public string Time { get; set; }
public string Picture { get; set; }
}
public void SaveMessageData()
{
using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var isoStream = new IsolatedStorageFileStream("MyTextfile.txt", FileMode.Append,
isoStorage))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<SampleData>));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
List<SampleData> data = new List<SampleData>();
foreach (SampleData obj in Listbox.Items)
{
data.Add(obj);
}
data.Add(msg);
if (data != null)
serializer.Serialize(xmlWriter, data);
}
}
}
}
}
public void GenerateMessageData()
{
List<SampleData> data;// = new List<SampleData>();
try
{
using (IsolatedStorageFile myIsolatedStorage =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("MyTextfile.txt",
FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(List<SampleData>));
data = (List<SampleData>)serializer.Deserialize(stream);
this.Listbox.ItemsSource = data;
return data;
}
}
}
catch (Exception exp)
{
MessageBox.Show("No New Messages For You", "No Message", MessageBoxButton.OK);
}
return null;
}
But, The real problem is if there are two set of data(two messages) if i'm getting both are showing in the same list. How to manipulate or iterate multiple lists if there are multiple data?
If you need to merge two lists and there may be items which exist in both but you only want to appear in the merged list once, the easiest solution is to simply check if it's already in the list before adding it.