Error "unexpected token List" - apex

I am getting error "unexpected token List " while compiling the following code
trigger Lead_Casecloseafter on Lead (after update) {
// Collect ODST leads
id vRecordTypeId = [select Id from RecordType where name='ODST_Leads'];
set<id> vSetCaseId= new set<id>();
for (Lead vLead:trigger.new)
{
if (vLead.RecordTypeId == vRecordTypeId && vLead.IsConverted == true)
vSetCaseId.add (vLead.ODST_Case__c);
}
}
// Looking up associated Case
List <Case> vLstcase = new List ([select id,name,Case_Number__c,Status from ODST_Case__c where ID IN:vSetCaseId]);
for (Case vCase:vLstcase)
{
vCase.Status == 'Closed';
if(!vLstcase.isempty())
update vLstcase;
}
}

Judging by the rest of the code, it looks like you're missing an opening brace ({) after this line:
if (vLead.RecordTypeId == vRecordTypeId && vLead.IsConverted == true)
The closing brace immediately after the if closes the function (since there was no block opened for the if), causing the List line to be in an invalid context.

Related

Set custom filters for boost log sink with custom attribute & severity level

I have a log setup in which I have 2 types of log messages:
1 based solely on severity level
1 based solely on a custom tag attribute
These attributes are defined as follows:
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", trivial::severity_level)
BOOST_LOG_ATTRIBUTE_KEYWORD(tag_attr, "Tag", std::string)
I want to create a filter function that allows a message to be added to my log based on either of the 2 criteria (note that the log messages based on the custom tag attribute are always printed with severity level info, based on the trivial logger's severity levels).
So I want to have a filter, which allows a message based on if a message has the custom tag, and if it does not have it, based on the severity of the message.
I have tried to have a relative simple filter which does the following:
sink_->set_filter(
trivial::severity >= severityLevel
|| (expr::has_attr(tag_attr) && tag_attr == "JSON" && logJson_)
);
But as it is possible that the severityLevel can be either Debug, Info, Warning, Error or Fatal, if the level is configured as either Debug or Info, the custom tag attribute is ignored by the filter.
I have tried using a c++11 lambda, as following:
sink_->set_filter([this, severityLevel](const auto& attr_set) {
if (<condition for custom tag first>) {
return true;
} else if (<condition for severity level second>) {
return true;
} else {
return false;
}
});
But then I don't have an idea on how to actually check for my conditions. I have tried the following:
if (attr_set["Tag"].extract<std::string>() == "JSON" && logJson_) {
return true;
} else if (attr_set["Severity"].extract<trivial::severity_level>() >= severityLevel) {
return true;
} else {
return false;
}
But the compiler throws several errors about this:
Core/Source/Log/Logger.cpp: In lambda function:
Core/Source/Log/Logger.cpp:127:48: error: expected primary-expression before '>' token
if (attr_set["Tag"].extract<std::string>() == "JSON" && logJson_) {
^
Core/Source/Log/Logger.cpp:127:50: error: expected primary-expression before ')' token
if (attr_set["Tag"].extract<std::string>() == "JSON" && logJson_) {
^
Core/Source/Log/Logger.cpp:129:72: error: expected primary-expression before '>' token
} else if (attr_set["Severity"].extract<trivial::severity_level>() >= severityLevel) {
^
Core/Source/Log/Logger.cpp:129:74: error: expected primary-expression before ')' token
} else if (attr_set["Severity"].extract<trivial::severity_level>() >= severityLevel) {
^
Core/Source/Log/Logger.cpp: In lambda function:
Core/Source/Log/Logger.cpp:134:5: error: control reaches end of non-void function [-Werror=return-type]
});
^
cc1plus: all warnings being treated as errors
scons: *** [obj/release/Core/Source/Log/Logger.os] Error 1
====5 errors, 0 warnings====
I have been scouring the boost log documentation about extracting the attributes myself, but I cannot find the information I need.
EDIT:
For posterity, I'll add how I've solved my issue (with thanks to the given answer by Andrey):
sink_->set_filter([this, severityLevel](const auto& attr_set) {
if (attr_set[tag_attr] == "JSON") {
return logJson_;
} else if (attr_set[severity] >= severityLevel) {
return true;
} else {
return false;
}
});
The filter can be written in multiple ways, I will demonstrate a few alternatives.
First, using expression templates you can write it this way:
sink_->set_filter(
(expr::has_attr(tag_attr) && tag_attr == "JSON" && logJson_) ||
trivial::severity >= severityLevel
);
Following the normal short-circuiting rules of C++, the tag attribute will be tested first and if that condition succeeds, the severity will not be tested. If the tag is not present or not JSON or logJson_ is not true, then severity level is tested.
Note that the filter above will save copies of its arguments (including logJson_ and severityLevel) at the point of construction, so if you change logJson_ later on the filter will keep using the old value. This is an important difference from your later attempts with C++14 lambdas, which access logJson_ via the captured this pointer. If you actually want to save a reference to your member logJson_ in the filter, you can use phoenix::ref:
sink_->set_filter(
(expr::has_attr(tag_attr) && tag_attr == "JSON" && boost::phoenix::ref(logJson_)) ||
trivial::severity >= severityLevel
);
However, you should remember that the filter can be called concurrently in multiple threads, so the access to logJson_ is unprotected. You will have to implement your own thread synchronization if you want to update logJson_ in run time.
Barring multithreading issues, your second attempt with a lambda is almost correct. The compiler is complaining because the lambda function is a template, and the result of attr_set["Tag"] expression depends on one of the template parameters (namely, the type of attr_set). In this case, the programmer has to qualify that the following extract<std::string>() expression is a template instantiation and not a sequence of comparisons. This is done by adding a template keyword:
if (attr_set["Tag"].template extract<std::string>() == "JSON" && logJson_) {
return true;
} else if (attr_set["Severity"].template extract<trivial::severity_level>() >= severityLevel) {
return true;
} else {
return false;
}
Note that you could use a standalone function to the same effect, which wouldn't require the template qualification:
if (boost::log::extract<std::string>("Tag", attr_set) == "JSON" && logJson_) {
return true;
} else if (boost::log::extract<trivial::severity_level>("Severity", attr_set) >= severityLevel) {
return true;
} else {
return false;
}
Finally, the preferred way to extract attribute values is to leverage attribute keywords, which you declared previously. Not only this allows to avoid the template qualification quirk but it also removes a lot of code duplication.
BOOST_LOG_ATTRIBUTE_KEYWORD(severity, "Severity", trivial::severity_level)
BOOST_LOG_ATTRIBUTE_KEYWORD(tag_attr, "Tag", std::string)
if (attr_set[tag_attr] == "JSON" && logJson_) {
return true;
} else if (attr_set[severity] >= severityLevel) {
return true;
} else {
return false;
}
The attribute value name and type are inferred from the keyword declaration in this case. This use of attribute keywords is documented at the end of this section.

salesforce compare standard obj and custom object and assign value

I have custom obj "A" and Standard obj Case. Case standard obj has lookup to custom obj "A". there is a field between the two objects called Customer_ID__c. I wrote a Trigger (before Insert, Before Update) to associated the case record to the correct existing custom obj "A" record if "Case.Custom_Id__c" match the one in the Custom obj "A". Unfortunate it is not happening and I'm not sure where to look.
trigger IAACaseRelateASAP on Case (before insert, before update) {
Id recordtypes = [Select Id, name
From RecordType
Where SobjectType = 'Case'
AND Name = 'I Buy'
LIMIT 1].Id;
Set<String> casId = new Set<String>();
for(Case cs : Trigger.new)
{
if(cs.RecordtypeId == recordtypes && cs.Type == 'Contact Me')
{
if(cs.custm_Obj_A_Name__lookupfield__c == null && (cs.Customer_ID__c != null || cs.Customer_ID__c !='0'))
{
casId.add(cs.Customer_ID__c);
}
}
}
system.debug('Case Set Ids' + casId);
List<A__c> aList = [Select Customer_ID__c, Id
From A__c
Where Customer_ID__c IN: casId
AND
A__c != 'Provider'];
System.Debug('equals' + aList);
Map<String, A__c> aMapId = new Map<String, A__c>();
for(A__c aAcct : aList)
{
aMapId.put(aAcct.Customer_ID__c, aAcct);
}
for(Case cas : Trigger.new)
{
if(cas.RecordtypeId == recordtypes && cas.Type == 'Contact Me')
{
if(cas.custm_Obj_A_Name__lookupfield__c == null && (cas.Customer_ID__c != null || cas.Customer_ID__c !='0'))
{
if(aMapId.containsKey(cas.Customer_ID__c))
{
A__c aAcct = aMapId.get(cas.Customer_ID__c);
System.Debug('Case IAA ASAP Account value: ' + asapAcct);
}
}
}
}
}
It might be best when looping through your cases to build your set of Customer_ID__c ids to also build a List of cases with customer ids so that you don't have to loop through the entire new list a second time. There are a couple other issues with the trigger in general but I'll ignore those and just focus on what you asked. Think your issue is that you don't actually set the case field in this area:
if(aMapId.containsKey(cas.Customer_ID__c))
{
A__c aAcct = aMapId.get(cas.Customer_ID__c);
System.Debug('Case IAA ASAP Account value: ' + asapAcct);
}
It should be :
if(aMapId.containsKey(cas.Customer_ID__c))
{
cas.custm_Obj_A_Name__lookupfield__c = aMapId.get(cas.Customer_ID__c).Id;
}

Salesforce Lead Trigger CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY

I want to clone the Profile__c record. The lead has a profile__c associated with it. When conversion happens, the Profile_c on the lead is copied to the account created. What I need to do is a deep clone of the Profile__c on the new account created after the conversion. I am able to copy the profile_c over but cloning throws this error:
Error: System.DmlException: Update failed. First exception on row 0 with id 00QJ0000007dDmHMAU; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, profile: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_UPDATE_CONVERTED_LEAD, cannot reference converted lead: [] Trigger.profile:, column 1: [] (System Code)
trigger profile on Lead (after update) {
Map<Id, Lead> cl = new Map<Id,Lead>();
Lead parent;
List<Contact> clist = new List<Contact>();
Set<Id> convertedids = new Set<Id>();
//list of converted leads
for (Lead t:Trigger.new){
Lead ol = Trigger.oldMap.get(t.ID);
if(t.IsConverted == true && ol.isConverted == false)
{
cl.put(t.Id, t);
convertedids.add(t.ConvertedContactId);
}
}
Set<Id> leadIds = cl.keySet();
List<Profile__c> mp = [select Id, lock__c, RecordTypeId, reason__c, End_Date__c,startus__c , Opportunity__c, Account__c, Lead__c from Profile__c where Lead__c in :leadIds];
List<ID>AccountIDs = new List<ID>();
List<Profile__c>clonedList = new list<Profile__c>();
for (Profile__c mpi:mp){
parent = cl.get(mpi.Lead__c );
mpi.opportunity__c = parent.ConvertedOpportunityId;
mpi.account__c = parent.ConvertedAccountId;
AccountIDs.add(parent.ConvertedAccountId);
Profile__c profile = mpi.clone(false,true,false,false);
clonedList.add(profile);
mpi.lock__c= true;
mpi.reason__c= 'Converted';
}
update mp;
insert clonelist
}
You are doing insert operation(insert clonelist) in which you are accessing Converted lead Id value in a field. You can't use converted LeadId field in DML operations.
Below is the Sample code that will work-
trigger ConvertedLead_Trigger on Lead (after update) {
Map<Id, Lead> cl = new Map<Id,Lead>();
Lead parent;
List<Contact> clist = new List<Contact>();
Set<Id> convertedids = new Set<Id>();
//list of converted leads
for (Lead t:Trigger.new){
Lead ol = Trigger.oldMap.get(t.ID);
if(t.IsConverted == true && ol.isConverted == false)
{
cl.put(t.Id, t);
convertedids.add(t.ConvertedContactId);
}
}
Set<Id> leadIds = cl.keySet();
List<ConvertLeadTest__c> mp =[Select Id,Name,Lead__c, Account__c,Opportunity__c from ConvertLeadTest__c where Lead__c in :leadIds];
List<ConvertLeadTest__c> mp1=new List<ConvertLeadTest__c>();
List<ConvertLeadTest__c> mp2=new List<ConvertLeadTest__c>();
for(ConvertLeadTest__c cc:mp)
{
if(cl.containsKey(cc.Lead__c))
{
cc.Account__c=cl.get(cc.Lead__c).ConvertedAccountId;
cc.Opportunity__c=cl.get(cc.Lead__c).ConvertedOpportunityId;
mp1.add(cc);
mp2.add(new ConvertLeadTest__c(Account__c=cl.get(cc.Lead__c).ConvertedAccountId,Opportunity__c=cl.get(cc.Lead__c).ConvertedOpportunityId));
}
}
update mp;
insert mp2;
}
But if you write
ConvertLeadTest__c(Lead__c=cc.Lead__c,Account__c=cl.get(cc.Lead__c).ConvertedAccountId,Opportunity__c=cl.get(cc.Lead__c).ConvertedOpportunityId));
then it will throw error.
Hope this will help you.
Thanks :)
We are not able to perform any operation on the Lead once the lead is converted.
Anything you do to try o update the converted lead will give you error.
What eventually did it for me was after the conversion, I grabbed the convertedAccountIds. Since I was already copying Profile__c to the account after conversion, I just cloned the profile there and had to set the lead on that profile to null since it can't be updated

IQueryable in foreach - open DataReader error

When i run this code
public PartialViewResult GetHardware()
{
IQueryable<Hardware> hardware = db.Hardwares;
HardwareState hwState = new HardwareState();
IQueryable<IGrouping<string, Hardware>> groupByCategory = hardware.GroupBy(g => g.Category);
foreach (IGrouping<string, Hardware> group in groupByCategory)
{
hwState.GroupName = group.Key;
hwState.GroupUnitsCount = group.Count();
hwState.StorageReservedCount
= group.Where(m =>
m.Place.IsStorage == true &&
m.PlaceID != (int)Constants.HardwareState.Created &&
m.HardwareState == (int)Constants.HardwareState.Reserved).Count();
}
return PartialView(hwState);
}
I get an error about that the navigation property m.Place = null
when i transfer some of the text with the code of the foreach block
public PartialViewResult GetHardware()
{
IQueryable<Hardware> hardware = db.Hardwares;
HardwareState hwState = new HardwareState();
IQueryable<IGrouping<string, Hardware>> groupByCategory = hardware.GroupBy(g => g.Category);
hwState.StorageReservedCount
= hardware.Where(m =>
m.Place.IsStorage == true &&
m.PlaceID != (int)Constants.HardwareState.Created &&
m.HardwareState == (int)Constants.HardwareState.Reserved).Count();
foreach (IGrouping<string, Hardware> group in groupByCategory)
{
hwState.GroupName = group.Key;
hwState.GroupUnitsCount = group.Count();
}
return PartialView(hwState);
}
,the navigation property is not set to null and the error does not appear
Extension methods such as .AsQueryable or Include(x => x.Place) do not help me
How can i solve this problem?
UPDATE: If i change the type to IEnumerable instead IQueryable it begins to work!
but i would like to work with the IQueryable type
UPDATE2: I'm sorry, i did not put it correctly when i wrote that the error is an empty navigation property. Error that appears in fact
"There is already an open DataReader associated with this Command which must be closed first."
As described in this answer it is because: (quote)
"Another scenario when this always happens is when you iterate through
result of the query (IQueryable) and you will trigger lazy loading for
loaded entity inside the iteration."
But it does not say how to solve the problem without using ToList () or MARS

How to set a Lookup Field via a Salesforce Trigger

I want to set a Lookup Field using a salesforce apex trigger, but I keep getting an error:
System.StringException: Invalid id:
I have a custom object called Job__c. It has a custom pick list for accounts: Acct__c.
A user will populate Acct__c as John Deer, the trigger should add John Deer to the Account__c lookup field.
Here is the trigger:
trigger UpdateAccounts on Job__c (before insert) {
for (Job__c obj: trigger.new){
obj.Account__c = obj.Acct__c; //Exception is thrown here
}
Exception thrown:
System.StringException: Invalid id:
I tried something different:
List <Job__c> opListInsert = new List<Job__c>();
List <Job__c> opListUpdate = new List<Job__c>();
if(trigger.isInsert){
for(Job__c op:trigger.New){
if(op.Acct__c != Null){
op.Account__c = op.Acct__c;
opListInsert.add(op);
}
}
}
else if(trigger.isUpdate){
for(Job__c op:trigger.New){
if(op.Acct__c != Null && op.Acct__c !=trigger.oldMap.get(op.id).Acct__c){
op.Account__c = op.Acct__c;
opListUpdate.add(op);
}
}
}
That code throws:
Error:Apex trigger UpdateAccounts caused an unexpected exception, contact your
administrator: UpdateAccounts: execution of BeforeUpdate caused by:
System.StringException: Invalid id:
What am I doing wrong that it tells me it's an invalid ID?
Account__c is a look-up field, you cannot assign a string (the picklist field) to it. Instead you have to assign it an account id.
I am not sure why you're using the account names in the picklist field, but if you want to continue doing that then there's a simple solution that the account names are unique.
Get the id for the account selected in the query for the id, something like this:
list<account> acclist = [select id from account where name In yourNameList];
And then in the trigger reference the id
obj.account__c = accList[0].id;
Make use of maps , do not add the soql's inside for loop
You have to set your field with the ID of the object you want it to link to.
The salesforce browser page has a handy dandy tool that lets you put in incomplete information into the lookup field, and it fills it in for you automatically. This does not happen when values are assigned manually with an apex statement. You can only set the value to a valid and existing ID of the object the lookup was set to link to.
This code will grab the ID given name and do what you wanted:
trigger UpdateAcct on Job__c (before insert, before update) {
List<String> Accounts = new List<String>();
for (Job__c obj: trigger.new){
Accounts.add(obj.Acct__c);
}
list<Account> acctlist = [select Name from account where Name in :Accounts];
if (acctlist.size() > 0 ){
for (Integer i = 0; i < Trigger.new.size(); i++)
{
if (Trigger.new[i].Acct__c != null)
{
Trigger.new[i].Account__c = acctlist[i].ID;
}
else
{
Trigger.new[i].Account__c = null;
}
}
}
}