• BalajiRanganathan
  • PRO
  • 3284 Points
  • Member since 2014
  • Salesforce/Java Technical Architect


  • Chatter
    Feed
  • 105
    Best Answers
  • 0
    Likes Received
  • 36
    Likes Given
  • 0
    Questions
  • 586
    Replies
Hi All,

My visualforce controller is incrementing my shopping cart in strange ways. I've got an Apex class that is adding count variables when droping a list into a "Shopping Cart" Map. It will increment 1 no problem, but when I add 2 for the same item it will total to 4 instead of 3. What can I do in my controller and/or Visualforce to make this work. Also I noticed it was slow to load. How could I increase performance.

Apex
public class StoreFront2 {
    public String message { get; set; }
    List<DisplayMerchandise> products;
    Map<Id, DisplayMerchandise> cart;

    public PageReference shop(){
        handleTheBasket();
        message = 'You bought: ';
        for (DisplayMerchandise p:products){
            if(p.count > 0){
               message += p.merchandise.name + ' (' + p.count + ') ' ;
               }
            }
        return null;
    }

    public void handleTheBasket(){
        for(DisplayMerchandise c : products){
            if(c.count > 0){
            if(cart.containsKey(c.merchandise.Id)){
               
                cart.get(c.merchandise.Id).count += c.count;
                
            }
            else{
                cart.put(c.merchandise.Id, c);
            } 
        
        }
        }
        
    }
    
    public Map<Id, DisplayMerchandise> getCart() {
        if(cart == null){
            cart = new Map<Id, DisplayMerchandise>{};
                }
       
        return cart;
    }

    public class DisplayMerchandise {
        public Merchandise__c merchandise{get; set;}
        public Decimal count{get; set;}
        
        public DisplayMerchandise(Merchandise__c item){
            this.merchandise = item;
        }
    }

    public List<DisplayMerchandise> getProducts() {
        if (products == null){
            products = new List<DisplayMerchandise>{};


            for (Merchandise__c item :
            [SELECT id, name, description__c, price__c
            FROM Merchandise__c
            WHERE Total_Inventory__c > 0]) {
            products.add(new DisplayMerchandise(item));
            }
        }
        return products;
    }
}

Visualforce
<apex:page standardStylesheets="false" showHeader="false" sidebar="false" controller="StoreFront2">
  <apex:stylesheet value="{!URLFOR($Resource.styles)}"/>
  <h1>Store Front</h1>
  
  <apex:form >
      <apex:dataTable value="{!products}" var="pitem" rowClasses="odd,even">
          
          <apex:column headerValue="Product">
              <apex:outputText value="{!pitem.merchandise.name}" />
          </apex:column>
          <apex:column headervalue="Price">
              <apex:outputText value="{!pitem.merchandise.Price__c}" />
          </apex:column>
          <apex:column headerValue="#Items">
              <apex:inputText value="{!pitem.count}"/>
          </apex:column>
   
      </apex:dataTable>
      
      <br/>
      <apex:commandButton action="{!shop}" value="Add to Cart" reRender="msg,cart" />
  </apex:form>
  
    <apex:outputPanel id="msg">{!message}</apex:outputPanel><br/>    
    <h1>Your Basket</h1>
<form>    
     <apex:dataTable id="cart" value="{!cart}" var="carti" rowClasses="odd,even">
          
          <apex:column headerValue='Product'>
              <apex:outputText value="{!cart[carti].merchandise.name}" />
          </apex:column>
          <apex:column headervalue='Price'>
              <apex:outputText value="{!cart[carti].merchandise.price__c}" />
          </apex:column>
          <apex:column headerValue='#Items'>
              <apex:outputText value="{!cart[carti].count}"/>
          </apex:column>
   
      </apex:dataTable>
    </form>
    
  
</apex:page>

 
Hello all,

I have a trigger that one of y'all helped me build (many thanks!). The trigger works perfectly to change the case status when a FeedItem is posted witha  Parent ID of a case where the feed body ends with "Case closed".
As noted, the trigger works fine in the Sandbox, however my Apex Class used for testing is failing due to the following error:
System.QueryException: List has no rows for assignment to SObject

The Apex Trigger is:
trigger UpdateCaseCloseStatus on FeedItem (after insert) {
    
    List<Case> listOfCases = new List<Case>();
    
    for (FeedItem fi : Trigger.new) {
        
        //--- This retrieves the case for which feed has been entered.
        Case c = [select id from Case where Id = :fi.ParentId];

        //--- Now we check if the feed ends with text 'Case Closed'. We are checking case insensitive text.
        if (fi.Body.endsWithIgnoreCase('Case Closed')) {
            c.Status = 'Complete';
        }
        listOfCases.add(c);
    }
    update listOfCases;
}

The Apex Class is:
@isTest
public class TestFeedPost    {
    static testMethod void insertNewFeedPost()     {
        
        FeedItem feedToCreate = new FeedItem();
        
        feedToCreate.ParentId    =       '500q0000001Pavd';
        feedToCreate.Body        =       'Blah blah blah close case';
        feedToCreate.Type        =        'TextPost';
        
        insert feedToCreate;
        }
        }


The full error message is:
<span unselectable="on" "="" style="display: block; padding: 3px 4px; overflow: hidden; margin-left: 0px; color: rgb(34, 34, 34); font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: normal; white-space: nowrap; background-color: rgb(218, 240, 249);">
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateCaseCloseStatus: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.UpdateCaseCloseStatus: line 8, column 1: []



Any assistance would be greatly appreciated.

Thanks!
I have created two custom objects (A and B)and a junction object(AB). i.e. Both A and B have Many to Many relationship. Now I need to insert 5000 records. How can I automatically populate the relation in Junction object. DO I have to write any trigger or Do I have to do Manually mapping the records?

 
Is it possible to create a master-detail relationship between two standard objects? If yes, how?
  • March 12, 2015
  • Like
  • 0
I have two salesforce orgs A and B. I am want to get all Account records there in B org in Org A. I written code REST API. Eevrything workig fine. But how to user pass: /services/data/v29.0/queryAll/?q=SELECT+Name+from+Account. this use this funciton in REST API.

Below is my Code:

public class W_RestInvoke_Account2c{
    public String result{set;get;}
    fromJSON d1 {set;get;}
   // JSON2Apex d2            {set;get;}
    public String d3        {set;get;}     
    public String accesstkn {set;get;}     
    Account accrec          {set;get;}

public String clientid ;  

public void show(){

    Http p =new Http();
    HttpRequest request=new HttpRequest();
    request.setEndpoint('https://login.salesforce.com/services/oauth2/token');
    request.setMethod('POST');
    request.setBody('grant_type=password&client_id=tw&client_secret=7925616023235447130&username=cxxxm&password=xxx' );
    HttpResponse res=p.send(request);
    result=res.getBody();
  //string tknAccesstoken = (String) res.getAttribute(ACCESS_TOKEN); 

        d1 = (fromJSON)JSON.deserialize(result, fromJSON.class);
accesstkn = d1.access_token;
system.debug('VENKATESH______-->fromJSONvalues:Y'+ accesstkn );


HttpRequest request1= new HttpRequest();
request1.setEndpoint('https://ap1.salesforce.com/services/apexrest/RestAccount2');
request1.setMethod('GET');      
request1.setHeader('Authorization','OAuth '+accesstkn);
request1.setHeader('q','/services/data/v29.0/queryAll/?q=SELECT+Name+from+Account');
HttpResponse response=p.send(request1);
result= ''+response.getBody();

 

public class fromJSON{
public String id;   
public String issued_at;    
public String token_type;   
public String instance_url; 
public String signature;    
public String access_token; 

}
}


Pls help me where can use this /services/data/v29.0/queryAll/?q=SELECT+Name+from+Account function?
Hi, 
<table>
                    <tr>
                        <td>Action</td>
                        <td>Name</td>
                        <td>Phone</td>
                    </tr>

                    <apex:repeat value="{!listOfAccountRelatedWrapper}" var="m">

                        <tr>
                            <td>
                                <apex:inputCheckbox value="{!m.isSelected}" id="InputId" />
                            </td>
                            <td>
                                <apex:outputField value="{!m.con.Name}" id="adonProductName" />
                            </td>
                            <td>
                                <apex:outputField value="{!m.con.Phone}" id="adonProductQuality">
                                    <apex:inlineEditSupport event="ondblClick" showOnEdit="saveButton,cancelButton" hideOnEdit="editButton" />
                                </apex:outputField>
                            </td>
                        </tr>
                    </apex:repeat>

                    </table>

User-added image
I want to show
Action          Name       Phone
checkbox     www        12345(this is Editable field)

help me...
Hello,

I have an after trigger that fires when an Opportunity is updated.  I'm having an issue because when I look for the Account ID related to the Oppotunity, it is returning as Null even though the Opportunity is absolutely linked to an Account (system debug at line 25).  All the other variables in the debug statement return as expected.  Does anyone know why the Account field does not?  Thanks, 

Trigger:
ClassOpp2Account updater14 = new ClassOpp2Account();
            updater14.mgdUpdates(Trigger.new);



Trigger Class:
public class ClassOpp2Account{

    public void mgdUpdates(List<Opportunity> MgdAcctUpdates){

    Map<Id,Account> acctMap = new Map<Id,Account>();
    Set<id> Ids = new Set<id>();

    String recordTypeName = 'Renewals';
    Map<String,Schema.RecordTypeInfo> rtMapByName = Schema.SObjectType.Opportunity.getRecordTypeInfosByName();
    Schema.RecordTypeInfo rtInfo =  rtMapByName.get(recordTypeName);
    id recType = rtInfo.getRecordTypeId();

    List<Account> accountsToUpdate = new List<Account>();
        for (Opportunity opp : MgdAcctUpdates)
        {
                Ids.add(opp.Account.Id);
            }
     
     Map<Id,Account> acctMap2 = new Map<Id,Account>([SELECT Id,Name,Managed_Renewal_Date__c,Managed_Term__c,Managed_Value__c
                                                    FROM Account
                                                    WHERE Id in :Ids]);
     
        for (Opportunity opp2 : MgdAcctUpdates){
        
system.debug('***#*** IsClosed: '+opp2.IsClosed+' Stage: '+opp2.StageName+' Opp Rec Type: '+opp2.RecordTypeId+' Rec Type: '+recType+' Acct Name: '+opp2.Account);
            if(opp2.RecordTypeId == recType && opp2.IsClosed == true){

            if(acctMap2.containsKey(opp2.Account.Id)){

                Account acct = acctMap2.get(opp2.Account.Id);
            if(acctMap2.get(opp2.Account.Id).Managed_Renewal_Date__c < opp2.Renewal_Date_Next__c || acctMap2.get(opp2.Account.Id).Managed_Renewal_Date__c == null) {
                    acct.Managed_Renewal_Date__c = opp2.Renewal_Date_Next__c;
                    acct.Managed_Term__c = opp2.Term__c;
                    acct.Managed_Value__c = opp2.Final_Annualized_Amount__c;
            }
                 acctMap.put(acct.id,acct);
            }
            }
        }
        update acctMap.values();
        }
}

 
Example for creating Opportunity :
curl https://na1.salesforce.com/services/data/v20.0/sobjects/Opportunity/ -H "Authorization: Bearer token" -H "Content-Type: application/json" -d @newrecord.json -X PATCH
Example request body newrecord.json file :
{ "Name":"FFNEw","CloseDate":"3/2/2015","StageName":"Prospecting","Probability":10 }
My ASP.net code :
using (WebClient client = new WebClient())
{
client.Headers.Add("Authorization", "Bearer " + token.access_token); client.Headers.Add("Content-Type", "application/json");
var request = (HttpWebRequest)(HttpWebRequest.Create(token.instance_url + "/services/data/v20.0/sobjects/Opportunity/"));
request.Method = "POST";
using (var requestWriter = new StreamWriter(request.GetRequestStream()))
{
  requestWriter.Write(json);
  requestWriter.Flush();
  requestWriter.Close();
}
var response = request.GetResponse();
}
Getting Error 400 Bad Request in "request.GetResponse()".
I am able to create Account using same code. I don't Know what wrongs with Opportunity.
Hi All,
I am trying to impliment the bellow using forumla.
If(TODAY() > (StartDate + (Today -StartDate), 1, 0)
Ex: Today:21/Feb/2015
Start Date:21/Jan/2014
Formula: 21/Feb/2015 > (21/Jan/2014 + ( 1 ) )


Note: In above (Today -StartDate) will give me the Number of Years difference between the two.

How can i write a forumla for this senario?
Hey all.  I am trying to refine a search functionality I have developed.  I want the search string the user enters to search ALL FIELDS to return as many relevant results as possible.  However, I am expecting certain data to show that aren't.  For example, I have an account with the Account Name of "Worldwide Acme Holdings".  The user is entering the search string "acme".  There are lots of Contacts associated with that account.  However, the search results do not yield any of those contacts.  Here is my query:
 
allAccsCons = [FIND :searchString IN FIELDS RETURNING Contact(Name,Id,AccountId,Email,Phone,Account.Name),Account(Id,Name,Type,BillingCity,BillingState,Industry)];
It doesn't seem that the SOSL query is looking at the "Account.Name" value for the Contact sObject.  The account results themselves do contain the Account mentioned above.  But, I am wanting a contact list as well of all contacts who are part of that account. 

Am I doing something wrong here?  Technically the field with the Account Name label in SF is an Id/Lookup field.  Is that why?  Any viable workarounds?

Thanks!
 
Hi,

I tried writing the sample apex class to return list of strings. Below is the code and when I check the challenge - I get the error as "Challenge not yet complete... here's what's wrong: Executing the 'generateStringArray' method failed. Either the method does not exist, is not static, or does not return the proper number of strings.". What's wrong in the code?

public class StringArrayTest {
    public static List<String> generateStringArray(Integer len) {
 
        Integer inp = len;        
        List <String> Arrlist = new List<String>();
        for(Integer i=0; i < len; i++){
            Arrlist.add('Test: ' + i);
            system.debug(Arrlist.get(i));
          //  system.debug('len value: '  + inp);
        } 
        return Arrlist;
        
    }

}
Hi,

Can someone help, I keep hitting the same error, insert failed. DML operation on setup object is not permitted after you have updated a non-setup object(or vice versa: User, original object: Account:[].  I am trying to test that the account owner is the same, that the account owner is not the same anymore, so the account owner has changed. Help please.  This is my test class:

@isTest
private class testAccOwner {
    public static testMethod void testAccOwnerChange() 
    {
    test.startTest();
        
	Account acc = new Account(Name = 'test01', OwnerId = 'xxxxxxx001');

    insert acc;
      
        User testUser2 = [Select Id from User where IsActive = true limit 1];
        User testUser3 = [Select Id from User where IsActive = true limit 1];
         
    
    	User testUser1 = new User(alias = 'TstUsr1',Firstname='tst1', email='newuserDP@testorg.com', emailencodingkey='UTF-8', lastname='Tst11', languagelocalekey='en_US', localesidkey='en_US', profileid = 'xxxxxxx006', timezonesidkey='America/Los_Angeles', username='newuser11@testorg.com', UserRoleId = 'xxxxxxx006',Country_picklist__c = 'UNITED STATES',
        Global_Region__c  = 'US', DIRECTOR_NM__c=testUser2.id, ManagerId = testUser3.Id);
        insert testUser1;
        
        System.runAs(testUser1){
        
        acc.OwnerId = testUser1.Id;
        acc.OwnerId = 'xxxxxxx001';
        acc.Previous_Account_Owner__c = 'xxxxxxx001';
        acc.Previous_Account_Owner_s_Manager__c = testUser1.ManagerId;
        acc.New_Account_Owner_s_Manager__c = testUser2.ManagerId;
        acc.OwnerId = testUser2.Id;
        }
        update acc;
        /*System.runAs(u){
			Account acc1 = new Account();
            acc1.OwnerId = 'xxxxxxx001';
            acc1.Name = 'Test091';
            insert acc1;
            
            acc= [select id, ownerId from Account where id=:acc.id];
            system.assert(acc1.OwnerId == acc.OwnerId);
        }*/
        test.stopTest();
    }
}
I feel a bit stupid.  I have a pretty straightforward javascript custom button where I am trying to do a query and then iterate over the resulting set of objects.

My broken code is:
query_str = 'Select Id, ' + 
                'RecordType.Name, QB_Propagated__c ' +
                'FROM Opportunity WHERE ' +
                  'QB_Propagated__c=false AND ' + 
                  'RecordType.Name=\'Donation\' AND ' + 
                  'Id IN (\'' + idArray.toString().replace(/,/g, "','") + '\')';
alert(query_str);
ores = sforce.connection.query(query_str);
alert(ores);
alert('len: ' + ores.records.length);

The ores.records is defined and appears to be a list of entities that I want to iterate over (an alert(ores.records) gives me an object that starts {type:.....,} ), but my alert referencing the length of ores.records is undefined.

If I use the same query but do NOT include the AND ID IN ('sfid1','sfid2') in the query then the ores structure looks the same (to my eye!) but the code does work and I can refer to ores.records.length and get something meaningful.

In the "failing" version there is only one record that satisfies the condition.  If I extend my test so that two records satisfy my condition then I get the expected behavior.

Is it possible that I need two versions of code to deal with <=1 record returned from the query and >1 record?  I was hoping to just iterate over the length of the list.

-brian
 
Hi All,

I need little help in developing below pattern:

I tried so many things but keeping header as common means , we need to work with HTML tables .
So, i have used Html table with nested repeats, but I want that child line item should also come in different rows , but in my case , I am getting all line items in same row.Please suggest , how to resolve this??
column1     column2     column3       column4     column5
p1                  p2         plineitem1   plineitem12   plineitem112
a1                  a2
c1                  c2         clineitem1   clineitem11   plineitem112
                                  clineitem2   clineitem12   clineitem112
                                  clineitem3   clineitem13   clineitem112
d1                  d2         dlineitem1   dlineitem12   dlineitem112    

currently,

<table width="100%" cellspacing="0" cellpadding="0" style="border:solid 1px #cccccc"  class="list " rules="all" >
  <thead>
    <tr class="headerRow">
    <th class="headerRow"> column1  </th>
    <th class="headerRow"> column2</th>
      <th class="headerRow">column3</th>
      <th class="headerRow" >column4</th>
        <th class="headerRow" >column5</th>
</thead>

<tbody>

 <apex:repeat value="{!items_to_approve}" var="item_to_approve"  >

   <apex:repeat value="{!wrapper}" var="qlist"  >
   <tr class="dataRow">
    <td>{!item_to_approve.name}</td>
    <td>{!item_to_approve.id}</td>
    <td>{!qlist.qrec.id}</td>
<td>{!qlist.qrec.name}</td>
<td>{!qlist.qrec.phone}</td>
    </tr>

  </apex:repeat>
</apex:repeat>
</tbody>

</table>

but still , m not able to get the desired output.please help
  • February 12, 2015
  • Like
  • 0
I have an Apex Trigger that I am creating that is to count the number of Tasks that are on an Account, the code is listed below.
 
trigger SumTotalActivitesOnAccount on Task (after insert, after update, after delete) {

    set<Id> set_Id = new set<Id>();
    
    List<Account>acc_list = new List<Account>();
    
    if(Trigger.isInsert || Trigger.isUpdate) {
        for(Task T:trigger.new){
            set_Id.add(T.What);
        }
        
    }
    else if(Trigger.isDelete){
        for(Task T:Trigger.old){
            set_Id.add(T.What);
        }
        
    }
    
    if(Trigger.isAfter && (Trigger.isUpdate || Trigger.isInsert || Trigger.isDelete)){
        acc_list=[SELECT Id, Sum_Total_Activities__c, (SELECT Id, FROM Tasks) FROM Account WHERE Id IN :set_Id];
    
    for(Account acc: acc_list){
        if(acc.Tasks.size()>0)
            acc.Sum_Total_Activities__c = acc.Tasks.size();
        else
            acc.Sum_Total_Activities__c = 0;
    }
     if(!acc_list.isEmpty())
            update acc_list;
  }

}

I keep getting an error that states: Compile Error: unexpected token: 'FROM' at line 21 column 66

Any help would be greatly appreciated.
Hello gentlemen

I have 3 account fields.  If the values in all 3 meet a condition, then I want to checkbox a formula field.  Will it look like this?

IF ( ISPICKVAL ( Type, "Customer" ), True,

IF ( AND ( ISPICKVAL ( Status__c , "New" ), True,

IF ( AND ( ISPICKVAL ( Source__c , "Webinar" ), True, False )))

 I am getting an error as such :
"Attempt to de-reference a null object
Error is in expression '{!changevalue}' in page opportunitypagepicklistexample: Class.opportunityControllerpicklist.changevalue: line 17, column 1"
Please go through the code. 

VIsualForce Page code:
<apex:page standardController="opportunity" extensions="opportunityControllerpicklist"> 
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection title="Section 1">
<apex:inputField value="{!opp.stagename}">
<apex:actionSupport  action="{!changevalue}" event="onchange" />
</apex:inputfield>
</apex:pageBlockSection>

<apex:pageBlockSection title="Section 2"  columns="1" rendered="{!section2}">
<apex:inputField value="{!opp.type}"/>
<apex:inputField value="{!opp.leadsource}"/>
</apex:pageBlockSection>

<apex:pageBlockSection title="Section 3" rendered="{!section3}">
<apex:inputField value="{!opp.currentgenerators__c}"/>
<apex:inputField value="{!opp.deliveryinstallationstatus__c}"/>
<apex:pageBlockSection></apex:pageBlockSection>
<apex:inputField value="{!opp.name}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
COntroller Code:
Public class opportunityControllerpicklist
{
    public opportunityControllerpicklist(ApexPages.StandardController controller) 
    {
        opportunity opp = new opportunity();
        section2 = true;
        section3 = true;
    }
public opportunity opp{get;set;}
public boolean section2{get;set;}
public boolean section3{get;set;}
public void changevalue()
{
System.debug('----------'+opp.stagename);
if(opp.stagename == 'Qualification')
{
    section3 = true;
    section2 = false;
}
else if (opp.stagename == 'Prospecting')
{
    section2 = true;
    section3 = false;
}
else
{
section2 = true;
section3 = true;
}


}
}
We created an Apex Trigger on our Sandbox (a before insert, before update trigger on Contact which just basically updates some custom field). Tested it with an Apex class and Code Coverage is 100% (12/12).
But when we deploy it to Production validation fails.

Below is our Apex Class to test.


@isTest
public class TriggerTest {
 static testMethod void verifyTrigger (){
 User u1 = [SELECT Id FROM User WHERE Alias='alias'];
 System.RunAs(u1)
 {
 
    System.debug('Current User: ' + UserInfo.getUserName());
    System.debug('Current Profile: ' + UserInfo.getProfileId());

    List<Contact> contacts = new List<Contact>{};
 
     for(Integer i = 0; i < 1000; i++) {
     Contact a = new Contact(LastName = 'Test'+i, AccountId = 'xxxxxxxxxxxxxxx',Owner=u1 );
     contacts.add(a);
     }

     test.startTest();
     insert contacts; 
      
     test.stopTest();
  }
  
 }

}

Any ideas why? I have tried Compiling all classes. And even Run all from Developer Console but no luck.
I need to create a approval process in following way:

Lets say there are some formula fields department1, department2, department3 ...... department20 which populates as YES/NO based on some logic.

According to these department fields, the approval process will execute in following way:

Step1 - department1
Step2 - department2
Step3 - department3
Step4 - department4
Step5(Parallel approval required) - department5, department6, department7, department8,.... department15
Step6 - department16
Step - department17
Step - department18
Step - department19
Step - department20

Now my problem is that, there are 10 departments to be included in Step5 but the condition is that only those departments approval is required whose respective formula field say 'YES'.

In that case I have to create 10*10 steps only for Step5 to meet all the combinations, like if (department5 & department8 is YES) or if (department6 & department7 & department9 is YES) and so on.

Is there any way to accomplish such a requirement without creating so many steps?
Any help will be greatly appreciated.
trigger avgofresiduals on child__c (after insert, after update, after delete,after undelete) {

    //Set<ID> ids = Trigger.newMap.keySet();
   
    Set<Id> AcctIds = new Set<Id>();    
    //Set<Id> AcctIds = Trigger.newMap.keySet();    
    
    List<child__c > ConList = new List<child__c >();
    
    if(trigger.isInsert || trigger.isUPdate) {
        for(child__c Con : trigger.New) {
            AcctIds.add(Con.Deal__c);     
        }  
    }
    if(trigger.isDelete || trigger.isUndelete) {
        for(child__c  Con : trigger.Old) {
            AcctIds.add(Con.Deal__c);     
        }  
    }       
    
     Map<Id, List<child__c >> AcctContactList = new Map<Id, List<child__c >>();
     
    ConList = [SELECT Id, Deal__c, Volume__c,
               FROM child__c 
               WHERE Deal__c IN : AcctIds 
               ORDER BY CreatedDate DESC 
               LIMIT 3
               ];
               
   List<deal__c> AcctList = new List<deal__c>();
               
    double j=0;

    for(child__c  Con : ConList) {

            if(con.Volume__c!= null) {
                j += con.Volume__c;
            } 
    
                       
    }    
    AcctList = [SELECT volumesum 
                FROM deal__c
                WHERE Id IN : AcctIds
                ];
    
   
        List<child__c > ContList = new List<child__c >();
        ContList = AcctContactList.get(Acc.Id);
        Acc.volumesum = j;
        
       
    }
    update AcctList;

}
Before updating a field ABC, I need to check whether the field is passed as null/blank, if yes, then dont update it.

Can someone advise if there is a difference between the two options below, and if yes, what I should be aware of? I am interested if wither there is a best practice, potential compile errors, or anything else.

Option 1:
if ( null != ABC && '' != ABC ) {
               abc.ABC__c = ABC;               
            }

Option 2:
if ( ABC != null && ABC != '' ) {
               abc.ABC__c = ABC;               
            }

Thank you!
I have a trigger that works fine, it populates the fields it was designed to populate but when it run before insert it causes the id number to increment more than 1.  Below is my trigger code:
trigger ICNFill on BMCServiceDesk__Incident__c (before insert, before update) {
 List<BMCServiceDesk__Incident__c> ICNIncident = Trigger.new;
    
    String CircNo = ICNIncident[0].ICN_Circuit_No__c;
     if(String.isNotBlank(CircNo)) {
         
    Integer len;
        len = CircNo.length();
        if(len > 0) {
    
    List<BMCServiceDesk__BMC_BaseElement__c> ICNList = [Select ICN_Channel_No__c,
                                     ICN_Circuit_Status__c,
                                     ICN_Circuit_Type__c,
                                     ICN_Site_Business_Phone__c,
                                     ICN_Cell_Phone__c,
                                     ICN_Operation_Hours__c,
                                     ICN_Managed_By__c,
                                     ICN_Org_Name__c,
                                     ICN_Rate_Limit_Amount__c,
                                     ICN_Router_Interface__c,
                                     ICN_Router_Name__c,
                                     ICN_Site_Address__c,
                                     ICN_Site_City__c,
                                     ICN_Site_ID__c,
                                     ICN_Site_Name__c,
                                     ICN_Site_Phone__c,
                                     ICN_Site_Zip_Code__c,
                                     ICNZendRTC__c,
                                     ICNZendMSA__C,
                                     ICN_Parent_Circuit__c,
                                     ICNAendRTC__c,
                                     ICNAendMSA__c,
                                     ICN_Comments__c,
                                    ICN_First_Name__c,
                                     ICN_Last_Name__c,
                                      ICN_MLPP_MFR_VLAN_No__c                  
                                                        
             
                                     from BMCServiceDesk__BMC_BaseElement__c where ID = :CircNo];
   
   ICNIncident[0].ICN_Channel_No__c = ICNList[0].ICN_Channel_No__c;
   ICNIncident[0].ICN_Circuit_Status__c = ICNList[0].ICN_Circuit_Status__c;
   ICNIncident[0].ICN_Contact_Business_Phone__c = ICNList[0].ICN_Site_Business_Phone__c;
   ICNIncident[0].ICN_Contact_Cell_Phone__c = ICNList[0].ICN_Cell_Phone__c;

   ICNIncident[0].ICN_Managed_By__c = ICNList[0].ICN_Managed_By__c;
   ICNIncident[0].ICN_Org_Name__c = ICNList[0].ICN_Org_Name__c;

   ICNIncident[0].ICN_Rate_Limit_Amount__c = ICNList[0].ICN_Rate_Limit_Amount__c;
   ICNIncident[0].ICN_Router_Interface__c = ICNList[0].ICN_Router_Interface__c;
   ICNIncident[0].ICN_Router_Name__c = ICNList[0].ICN_Router_Name__c;
   ICNIncident[0].ICN_Site_Address1__c = ICNList[0].ICN_Site_Address__c;
   ICNIncident[0].ICN_Site_City__c = ICNList[0].ICN_Site_City__c;

   ICNIncident[0].ICN_Site_ID__c = ICNList[0].ICN_Site_ID__c;
   ICNIncident[0].ICN_Site_Name__c = ICNList[0].ICN_Site_Name__c;
   ICNIncident[0].ICN_Site_Phone__c = ICNList[0].ICN_Site_Phone__c;
   ICNIncident[0].ICN_Site_Zip_Code__c = ICNList[0].ICN_Site_Zip_Code__c;
   ICNIncident[0].ICNZendRTC__c = ICNList[0].ICNZendRTC__c;
   ICNIncident[0].ICNZendMSA__c = ICNList[0].ICNZendMSA__c;
   ICNIncident[0].ICNAendRTC__c = ICNList[0].ICNAendRTC__c;
   ICNIncident[0].ICNAendMSA__c = ICNList[0].ICNAendMSA__c;
   ICNIncident[0].ICN_Parent_Circuit__c = ICNList[0].ICN_Parent_Circuit__c;
   ICNIncident[0].ICNSite_Contact_First_Name__c = ICNList[0].ICN_First_Name__c;
   ICNIncident[0].ICNSite_Contact_Last_Name__c = ICNList[0].ICN_Last_Name__c;
   ICNIncident[0].ICN_Circuit_Type__c = ICNList[0].ICN_Circuit_Type__c;
   ICNIncident[0].ICNMLPP_MFR_VLAN_No__c = ICNList[0].ICN_MLPP_MFR_VLAN_No__c;
   ICNIncident[0].ICN_Comments__c = ICNList[0].ICN_Comments__c;
   
   }
   }
    
    
}

Any help would be greatly appreciated.  I'm new at this!!
I store the accessToken and refresh token so I can refresh it at some point in the future when the access token is no longer valid.  However, it seems that the refresh token would expired at some point or get invalidated automatically.  Can someone explain the lifetime of a refresh token?

in Digging_Deeper_into_OAuth_2.0_on_Force.com (https://developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com).  It is mentioned that it is only revoked by the user:
The refresh token represents the user's authorization to the application, and is valid until explicitly revoked by the user, via My Settings ➤ Personal ➤ Advanced User Details ➤ OAuth Connected Apps.
However, there is an edit in the same doc that mentiones that refresh token also have an expiration time:

The refresh token may have an indefinite lifetime, persisting for an admin-configured interval or until explicitly revoked by the end-user. The client application can store the refresh token, using it to periodically obtain fresh access tokens, but should be careful to protect it against unauthorized access, since, like a password, it can be repeatedly used to gain access to the resource server.
Since refresh tokens may expire or be revoked by the user outside the control of the client application, the client must handle failure to obtain an access token, typically by replaying the protocol from the start.
Hello,

I am working with flows in our test enviorment and the flow works from a button I created.  However, when I select the button to run the flow I get the below message.  I currently have to hit the back button on my browser to go back to the object and then I have to refresh it to show the results.  Is there a way to imilinate this message and refresh the object to show the flow results?  

User-added image

Thanks,

Aaron
Hi Experts,

I have a problem with email service in apex. When I reply to the salesforce generated email address, then in my email service handler the body contains all the previous replies and main email body(when the email was sent first time) along with the current reply.

Like:

    Test Notessssss......
    
    On Mon, May 4, 2015 at 11:58 AM, Pankaj <pankaj@gmail.com> wrote:
    Testjfdsfjdklsflkdsjflksdfjklsdfjlkdsfjsdklfj
    fjdslkfjsdklfjsdlkfjlsdkfjsdklfjdklsj

My reply body is Test Notesssssss..... only. But in email service handler I am getting the previous one as well.

Can someone suggest me how we can avoid the previous thread bodies?

Thanks in advance!
Hi All,

My visualforce controller is incrementing my shopping cart in strange ways. I've got an Apex class that is adding count variables when droping a list into a "Shopping Cart" Map. It will increment 1 no problem, but when I add 2 for the same item it will total to 4 instead of 3. What can I do in my controller and/or Visualforce to make this work. Also I noticed it was slow to load. How could I increase performance.

Apex
public class StoreFront2 {
    public String message { get; set; }
    List<DisplayMerchandise> products;
    Map<Id, DisplayMerchandise> cart;

    public PageReference shop(){
        handleTheBasket();
        message = 'You bought: ';
        for (DisplayMerchandise p:products){
            if(p.count > 0){
               message += p.merchandise.name + ' (' + p.count + ') ' ;
               }
            }
        return null;
    }

    public void handleTheBasket(){
        for(DisplayMerchandise c : products){
            if(c.count > 0){
            if(cart.containsKey(c.merchandise.Id)){
               
                cart.get(c.merchandise.Id).count += c.count;
                
            }
            else{
                cart.put(c.merchandise.Id, c);
            } 
        
        }
        }
        
    }
    
    public Map<Id, DisplayMerchandise> getCart() {
        if(cart == null){
            cart = new Map<Id, DisplayMerchandise>{};
                }
       
        return cart;
    }

    public class DisplayMerchandise {
        public Merchandise__c merchandise{get; set;}
        public Decimal count{get; set;}
        
        public DisplayMerchandise(Merchandise__c item){
            this.merchandise = item;
        }
    }

    public List<DisplayMerchandise> getProducts() {
        if (products == null){
            products = new List<DisplayMerchandise>{};


            for (Merchandise__c item :
            [SELECT id, name, description__c, price__c
            FROM Merchandise__c
            WHERE Total_Inventory__c > 0]) {
            products.add(new DisplayMerchandise(item));
            }
        }
        return products;
    }
}

Visualforce
<apex:page standardStylesheets="false" showHeader="false" sidebar="false" controller="StoreFront2">
  <apex:stylesheet value="{!URLFOR($Resource.styles)}"/>
  <h1>Store Front</h1>
  
  <apex:form >
      <apex:dataTable value="{!products}" var="pitem" rowClasses="odd,even">
          
          <apex:column headerValue="Product">
              <apex:outputText value="{!pitem.merchandise.name}" />
          </apex:column>
          <apex:column headervalue="Price">
              <apex:outputText value="{!pitem.merchandise.Price__c}" />
          </apex:column>
          <apex:column headerValue="#Items">
              <apex:inputText value="{!pitem.count}"/>
          </apex:column>
   
      </apex:dataTable>
      
      <br/>
      <apex:commandButton action="{!shop}" value="Add to Cart" reRender="msg,cart" />
  </apex:form>
  
    <apex:outputPanel id="msg">{!message}</apex:outputPanel><br/>    
    <h1>Your Basket</h1>
<form>    
     <apex:dataTable id="cart" value="{!cart}" var="carti" rowClasses="odd,even">
          
          <apex:column headerValue='Product'>
              <apex:outputText value="{!cart[carti].merchandise.name}" />
          </apex:column>
          <apex:column headervalue='Price'>
              <apex:outputText value="{!cart[carti].merchandise.price__c}" />
          </apex:column>
          <apex:column headerValue='#Items'>
              <apex:outputText value="{!cart[carti].count}"/>
          </apex:column>
   
      </apex:dataTable>
    </form>
    
  
</apex:page>

 
I've been able to get my APEX REST class working just fine in the Workbench and via cUrl calls.
But what I really want to do is have a script in our NetSuite environment make a call to my REST function.
I've been looking at the forcetk.js project but I'm unclear as to whether it's what I need or if I need to write something of my own jquery based code to do the authorization and make the call to my REST class.

Does anyone have any experience doing this and have any advice?
Is there any way to send a feedback form to the customers which consists of two links 'Satisfied' and 'Dissatisfied'. Where if the customer clicks on the link then the 'Customer feed back' field should auto populate against the case number. (Note:The Customers are not the users in salesforce)
Hi,

Please kindly help to resolve the above JSON Exception and also :
Unexpected character ('M' (code 77)): was expecting comma to separate OBJECT entries at input location.
Unexpected character ('P' (code 80)): was expecting comma to separate OBJECT entries at input location

All Help is Appreciated...!Thanks In advance...!
Hello all,

I have a trigger that one of y'all helped me build (many thanks!). The trigger works perfectly to change the case status when a FeedItem is posted witha  Parent ID of a case where the feed body ends with "Case closed".
As noted, the trigger works fine in the Sandbox, however my Apex Class used for testing is failing due to the following error:
System.QueryException: List has no rows for assignment to SObject

The Apex Trigger is:
trigger UpdateCaseCloseStatus on FeedItem (after insert) {
    
    List<Case> listOfCases = new List<Case>();
    
    for (FeedItem fi : Trigger.new) {
        
        //--- This retrieves the case for which feed has been entered.
        Case c = [select id from Case where Id = :fi.ParentId];

        //--- Now we check if the feed ends with text 'Case Closed'. We are checking case insensitive text.
        if (fi.Body.endsWithIgnoreCase('Case Closed')) {
            c.Status = 'Complete';
        }
        listOfCases.add(c);
    }
    update listOfCases;
}

The Apex Class is:
@isTest
public class TestFeedPost    {
    static testMethod void insertNewFeedPost()     {
        
        FeedItem feedToCreate = new FeedItem();
        
        feedToCreate.ParentId    =       '500q0000001Pavd';
        feedToCreate.Body        =       'Blah blah blah close case';
        feedToCreate.Type        =        'TextPost';
        
        insert feedToCreate;
        }
        }


The full error message is:
<span unselectable="on" "="" style="display: block; padding: 3px 4px; overflow: hidden; margin-left: 0px; color: rgb(34, 34, 34); font-family: Arial, Helvetica, sans-serif; font-size: 12px; line-height: normal; white-space: nowrap; background-color: rgb(218, 240, 249);">
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, UpdateCaseCloseStatus: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.UpdateCaseCloseStatus: line 8, column 1: []



Any assistance would be greatly appreciated.

Thanks!
I have created two custom objects (A and B)and a junction object(AB). i.e. Both A and B have Many to Many relationship. Now I need to insert 5000 records. How can I automatically populate the relation in Junction object. DO I have to write any trigger or Do I have to do Manually mapping the records?

 
Hey guys, so I have a trigger than runs whenever an address is updated or saved, to do reverse geocode and write the latitude and logitude to a field. The problem is, when a lot of records are updated at once, I run into the future call limit governer.....

See the code below: Any help is much appreciated.
 
/*// Trigger runs getLocation() on Accounts with no Geolocation

trigger SetGeolocation on Account (after insert, after update) {
    for (Account a : trigger.new)
    if (a.Location__Latitude__s == null)
          LocationCallouts.getLocation(a.id);
}*/

// Trigger runs getLocation() on Accounts with no Geolocation

trigger SetGeolocation on Account (after insert, after update) {
    for (Account a : trigger.new){
        if(system.isFuture() == FALSE){
          LocationCallouts.getLocation(a.id);
        }
    }
}

that's the trigger, which then runs this apex class:
 
public class LocationCallouts {

     @future (callout=true)  // future method needed to run callouts from Triggers
      static public void getLocation(id accountId){
        // gather account info
        Account a = [SELECT BillingCity,BillingCountry,BillingPostalCode,BillingState,BillingStreet FROM Account WHERE id =: accountId];

        // create an address string
        String address = '';
        if (a.BillingStreet != null)
            address += a.BillingStreet +', ';
        if (a.BillingCity != null)
            address += a.BillingCity +', ';
        if (a.BillingState != null)
            address += a.BillingState +' ';
        if (a.BillingPostalCode != null)
            address += a.BillingPostalCode +', ';
        if (a.BillingCountry != null)
            address += a.BillingCountry;

        address = EncodingUtil.urlEncode(address, 'UTF-8');

        // build callout
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://maps.googleapis.com/maps/api/geocode/json?address='+address+'&sensor=false');
        req.setMethod('GET');
        req.setTimeout(60000);

        try{
            // callout
            HttpResponse res = h.send(req);

            // parse coordinates from response
            JSONParser parser = JSON.createParser(res.getBody());
            double lat = null;
            double lon = null;
            while (parser.nextToken() != null) {
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
                    (parser.getText() == 'location')){
                       parser.nextToken(); // object start
                       while (parser.nextToken() != JSONToken.END_OBJECT){
                           String txt = parser.getText();
                           parser.nextToken();
                           if (txt == 'lat')
                               lat = parser.getDoubleValue();
                           else if (txt == 'lng')
                               lon = parser.getDoubleValue();
                       }

                }
            }

            // update coordinates if we get back
            if (lat != null){
                a.Location__Latitude__s = lat;
                a.Location__Longitude__s = lon;
                update a;
            }

        } catch (Exception e) {
        }
    }
}

This works very well, until you try to update a lot of records at once....when you do you run into the @future calls limit.


I had read that using a batch apex class can solve this, any advice on how to do that is appreciated.

I had posted a previous thread where another developer suggested I use a list to get around this, and it seemed to work, but after testing it, it broke the writing of geocode to the location field. See this thread: https://developer.salesforce.com/forums/ForumsMain?id=906F0000000B2h8IAC



 
Hi everyone, I'm having trouble with a test class. I'm passing a value to the target class variable but when the SOQL query executes, it returns "System.QueryException: List has no rows for assignment to SObject". Please help


Class
global class myClass{
public String AccountName{get;set;}
public Account accId{get;set;}
public String CNum{get;set;}

public VarsityAppInvoice(ApexPages.StandardController cAccount){         accId = (Account)cAccount.getRecord();         CNum = [Select Customer_Number__c FROM Account where id=:accId.id].Customer_Number__c;     }


   public Boolean getAccountStatus(){
     AccountName= [SELECT Name FROM Account WHERE Customer_Number__c=:CNum].Name;
     if(AccountName=null){
        return false;
     } else {
        return true
     }
   }

}

TestClass
@isTest
global class myClassTest{
static myClass con = new myClass();

public myClass(){
con.CNum='123456';
}

    @isTest static void testGetAccountStatus(){
            Boolean results = con.getAccountStatus();
            System.Debug(results);
     }

}

Even if I update con.CNum in the "testGetAccountStatus" method, I get the same error back, when the test runs. "System.QueryException: List has no rows for assignment to SObject"


 
  • March 28, 2015
  • Like
  • 0
Hi, I am building a client application to consume the Salesforce webservices using SOAP requests. I am getting the following error when i login itself. com.sforce.ws.ConnectionException: Failed to send request to https://login.salesforce.com/services/Soap/c/33.0/0DFj0000000L5Xv. Thisi is caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPaathBuilderException: unable to find valid certification path to requested target
    at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)

I know this is because I am not having the required certificate in my environment. From what I have been reading, all the certificates which I can generate in salesforce are for accessing external webservices from Salesforce. Can somebody direct me to the right certificate.

 
Hi Everyone, when the Status is 'Assigned' workflow sends an email to the owner of the record that the Work order is assigned to him and Is there any way that he just reply to that email with "Accepted" text so that the status field of the object will be changed to Accepted?
I have created two custom objects (A and B)and a junction object(AB). i.e. Both A and B have Many to Many relationship. Now I need to insert 5000 records. How can I automatically populate the relation in Junction object. DO I have to write any trigger or Do I have to do Manually mapping the records?

 

I have worked on providing users to upload multiple websites for internal facing website. 
But wondering what are the defined best practices in terms of functional and security best to enforce in terms of apex/visualforce layer in order to ensure malicious files are not uploaded via the public facing website built on the force.com platform?
Any thoughts and shareable experience would be greatly appreciated :)
 

  • March 13, 2015
  • Like
  • 1
We are experiencing an issue when making a web service callout using a certificate (self-signed). The external system hosting this web service is Microsoft 2012 server with IIS.
The error message from the IIS log is "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider" with error code 403.16

The error message received as a response to the call in SFDC is "Web service callout failed: Unexpected element. Parser was expecting element 'http://schemas.xmlsoap.org/soap/envelope/:Envelope' but found 'http://www.w3.org/1999/xhtml:html'"

Has anybody come across such issue ?
I have a Workflow that is settings fields using formula's that reference Custom Settings fields.  UI all works OK.  Apex Tests are causing an internal server error.

If I mark the test SeeAllData=True then, rather than creating the Custom Setting as part of the test data setup then all ok.  Create a new Custom Setting as part of test data markup - Internal Server Error.

Any ideas welcomed.
 
We have a force.com site and a community portal both with their own logins. For a user to logon to force.com site and community portal currently we have to maintain duplicate users accessing site and communities respectively.  I want to my force.com site members to access community portal but not all community users should have access to force.com site.
Hi,

We have to integrate our Salesforce Org with an external system (ES1). The integration requirement is as below:

ES1 has a custom object CO1 and ES1 is the MASTER for this object’ records. This object records need to be transferred to SFDC on an hourly basis. The volume of the records < 1000. For this requirement we are proposing the below solutions:

- Option 1: Automated data load - every one hour using Data Loader

- Option 2: Using ESI's API: The ES1 system's wsdl be consumed by SFDC and then salesforce will query the CO1 object every hour, fetches these record and upsert in Salesforce.


- Option 3: Using SOAP API: ES1 system will consume SFDC's enterprise wsdl and then connect with Salesforce programmatically. It will then upsert the CO1 object records every hour in Salesforce

Now which is the best option out of three above? Also if we chose option2, how can we run the integration every hour automatically?

Any help will be highly appreciated.

Thanks
 
 
Is there a time zone setting that can be set once and will automatically be adjusted when the time changes from Daylight to Standard time? All timestamps were behind by an hour after this past weekend. I changed default settings form Central Standard Time to Central Daylight Time. I would like it to be automatically adjusted to accomodate the change. Kind of like you don't have change your phone clock, it just happens!

Any ideas?
  • March 11, 2015
  • Like
  • 1
My company has a very extensive app (call it app1) being built in an enterprise org. Another department wants its own app (call it app2)  and also this app2 would need read only access to objects in app1. Would it be possible to build app2 as a managed package (we don't need to share code just data). If app2 somehow has to be merged with app1 then builds and release management becomes quite complex and I would like to avoid that. Any help here would be appreciated. 
  • March 11, 2015
  • Like
  • 1
Hi,

I've implemented OAuth for our Salesforce integration over the last couple of years.  During that time we've been supporting over 100 different Salesforce orgs.  However, even though all of them are authenticating using the same OAuth flow, I've noticed that some orgs have expired token errors from time to time.  However, this seems inconsistent.  Some orgs have never needed to reauthenticate, while some need to reauthenticate every few months.
Recently we had a new org that seems to need to reauthenticate every few days, which obviously isn't going to work.  Are there additional settings at the org level (security perhaps?) that would cause this inconsistency?  Has anyone else experienced this?  What methods could be used to troubleshoot?

Thanks,
tim
I have created a community and want to publish it so users can login to the community. However, I do not see the 'manage' button the documents refer to. Please let me know how I can bring it back so I can publish my community.
Currently working on the "Creating Wizards with Visual Workflow" and the missing piece for me is to find a way to create more than one record.

I'm having success with updating the Account records, but once I try and implement a way to create Contact records, I either get the error message on run or nothing gets updated on the Contacts side. I'm not including Opportunity records until I can figure out how to create multiple records off of the same screen.

Right now, my flow has a screen with the fields, pointing to a record lookup for Accounts, pointing to a decision about whether the Account is null or not, and then finally, a pointer to the create records for Accounts.

My main question is: how do I implement the record lookup for Contacts? Where in my flow would I start the process for creating records for Contacts?

Apologies if I'm doing this all wrong.
I have contacted the support desk (Open - #11703579) as i wanted to make change to my comapny domai. I wiould like to have a customized URL for ymy company login. 

To access salesfore we use https://login.salesforce.com link. I want to customize my like for my company.

I would like to use either one link mentioned below
https://SamsungNetworkSupport.salesforce.com or https://SamsungNetworkSupport.my.salesforce.com

Please provide direction in order to achive above result. 

Prakrut Mehta
 
If I have 200 roles and I need to share an object (Account) so that everyone in Role 1 can see any record owned by someone else in Role 1. How can we do this for all Roles 1-200; without going over the 100 sharing rule limit on the Account?
Hi Guys!

Is there an alternative way on how to create a Time Based Assignment Rule?

I am creating a scheduling system that a person would have to work 5 days in a week. I am trying to eliminate case age after the 5th day for the case that was assigned to them on the 6th and 7th day.How can I create a function that will alow me to transfer the assigned cases to the other user on his/her 6th and 7th day?

Thank you in advance.
All,
I need to make my sales summary code more efficient. Once we hit 9,000 trades on a single Account, the system hits the CPU Limit governor limit, even in a batch job. Anybody have any ideas on the code below? Perhaps moving each calculation in the For loop under each  corresponding map? I'm not sure the best way to change this code, but any help would be greatly appreciated.

Debug log shows errors at random at lines 73, 79, or 92 in the Class and every time on line 4 in the trigger.
CPU Time varies on the number of trades inserted at a time, but even at 1 trade I can get up to 25000 out of 10000 (more than double).

Class:
public class Account_RollupTrades {
    public Static Account_Setting__c setting = Account_Setting__c.getInstance();
    public Static boolean inprog = false;

    public static void execute (Set<Id> accountIds, List<Account> accountsList) {
        Map<Id, Account> accounts = new Map<Id, Account> (AccountsList);
        system.debug ('execute');
        if(setting.Disable_RollupTrades__c != true) {
            //Map<Id, Account> accounts = new Map<Id, Account>();
            for(Id accountId:accountIds) {
                system.debug(accountid);
                accounts.put(accountId,
                   new Account(
                       Id=accountId,
                       /**YTD_NIOR_I_Sales__c = 0,         YTD_NIOR_I_Shares__c = 0,         QTD_NIOR_I_Sales__c = 0,         QTD_NIOR_I_Shares__c = 0,
                       MTD_NIOR_I_Sales__c = 0,         MTD_NIOR_I_Shares__c = 0,         PY_NIOR_I_Sales__c = 0,          PY_NIOR_I_Shares__c = 0,
                       Total_NIOR_I_Sales__c = 0,       Total_NIOR_I_Shares__c = 0,       YTD_NS_Income_Sales__c = 0,      YTD_NS_Income_Shares__c = 0,
                       QTD_NS_Income_Sales__c = 0,      QTD_NS_Income_Shares__c = 0,      MTD_NS_Income_Sales__c = 0,      MTD_NS_Income_Shares__c = 0,
                       PY_NS_Income_Sales__c = 0,       PY_NS_Income_Shares__c = 0,       Total_NS_Income_Sales__c = 0,    Total_NS_Income_Shares__c = 0,**/
                       Total_NS_HI_Sales__c = 0,       Total_NS_HI_Shares__c = 0,       YTD_NS_HI_Sales__c = 0,         YTD_NS_HI_Shares__c = 0,
                       QTD_NS_HI_Sales__c = 0,         QTD_NS_HI_Shares__c = 0,         MTD_NS_HI_Sales__c = 0,         MTD_NS_HI_Shares__c = 0,
                       PY_NS_HI_Sales__c = 0,          PY_NS_HI_Shares__c = 0,          Total_NS_Income_II_Sales__c = 0, Total_NS_Income_II_Shares__c = 0,
                       YTD_NS_Income_II_Sales__c = 0,   YTD_NS_Income_II_Shares__c = 0,   QTD_NS_Income_II_Sales__c = 0,   QTD_NS_Income_II_Shares__c = 0,
                       MTD_NS_Income_II_Sales__c = 0,   MTD_NS_Income_II_Shares__c = 0,   PY_NS_Income_II_Sales__c = 0,    PY_NS_Income_II_Shares__c = 0,
                       Rollup_Trades__c = DateTime.now()
                   )
                            );
            }
            Map<String, SObjectField[]>
                ytd = new map<string, sobjectfield[]> {
                    //'3910' => new sobjectfield[] { account.YTD_NIOR_I_Sales__c , account.YTD_NIOR_I_Shares__c},
                    //'3911' => new sobjectfield[] { account.YTD_NS_Income_Sales__c , account.YTD_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.YTD_NS_HI_Sales__c , account.YTD_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.YTD_NS_Income_II_Sales__c , account.YTD_NS_Income_II_Shares__c }    
                },
                qtd = new map<string, sobjectfield[]> {
                    //'3910' => new sobjectfield[] { account.QTD_NIOR_I_Sales__c , account.QTD_NIOR_I_Shares__c},
                    //'3911' => new sobjectfield[] { account.QTD_NS_Income_Sales__c , account.QTD_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.QTD_NS_HI_Sales__c , account.QTD_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.QTD_NS_Income_II_Sales__c , account.QTD_NS_Income_II_Shares__c }
                },
                mtd = new map<string, sobjectfield[]> {
                    //'3910' => new sobjectfield[] { account.MTD_NIOR_I_Sales__c , account.MTD_NIOR_I_Shares__c},
                    //'3911' => new sobjectfield[] { account.MTD_NS_Income_Sales__c , account.MTD_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.MTD_NS_HI_Sales__c , account.MTD_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.MTD_NS_Income_II_Sales__c , account.MTD_NS_Income_II_Shares__c }
                },
                py = new map<string, sobjectfield[]> {
                    //'3910' => new sobjectfield[] { account.PY_NIOR_I_Sales__c , account.PY_NIOR_I_Shares__c},
                    //'3911' => new sobjectfield[] { account.PY_NS_Income_Sales__c , account.PY_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.PY_NS_HI_Sales__c , account.PY_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.PY_NS_Income_II_Sales__c , account.PY_NS_Income_II_Shares__c }
                },
                total = new map<string, sobjectfield[]> {
                    //'3910' => new sobjectfield[] { account.Total_NIOR_I_Sales__c , account.Total_NIOR_I_Shares__c},
                    //'3911' => new sobjectfield[] { account.Total_NS_Income_Sales__c , account.Total_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.Total_NS_HI_Sales__c , account.Total_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.Total_NS_Income_II_Sales__c , account.Total_NS_Income_II_Shares__c }
                };
    
    // We make the select in a "for" so instead of selecting to many records at once hitting the heap size limit the for it will take only 200 records to work with at each iteration.
    for(Trades__c[] tradesList : [select Dollar_Amount_of_the_transaction__c, Fund_Number__c, Number_of_Shares_of_the_transaction__c, Resolved_Firm_Trading_ID__c, Resolved_Firm_Trading_IDs__c, Trade_Date__c from Trades__c where Resolved_Firm_Trading_ID__c in :accountIds and Fund_Number__c in (/**'3910', '3911',**/ '3912', '3915') and Dollar_Amount_of_the_transaction__c != null and Number_of_Shares_of_the_transaction__c != null and Trade_Date__c != null and Dollar_Amount_of_the_transaction__c >= 0 and Number_of_Shares_of_the_transaction__c >= 0 FOR UPDATE]){
        for(trades__c trade: tradesList) {
            
            if(date.today().year() == trade.trade_date__c.year()) {
                accounts.get(trade.Resolved_Firm_Trading_ID__c).put(ytd.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(ytd.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
                accounts.get(trade.Resolved_Firm_Trading_ID__c).put(ytd.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(ytd.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);
                //system.debug(ytd);
                //system.debug(LoggingLevel.DEBUG, + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime());
                
                //( (date.ValueOf(date.today().month()).divide(3, 0) == date.ValueOf(trade.trade_date__c.month()).divide(3, 0)) )
                if((((date.today().month() - 1) / 3) + 1) == (((trade.Trade_Date__c.month() - 1) / 3) + 1))   {
                    accounts.get(trade.Resolved_Firm_Trading_ID__c).put(qtd.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(qtd.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
                    accounts.get(trade.Resolved_Firm_Trading_ID__c).put(qtd.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(qtd.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);
                    //system.debug(qtd);
                    //system.debug(LoggingLevel.DEBUG, + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime());
                    
                    if(date.today().month()==trade.trade_date__c.month()) {
                        accounts.get(trade.Resolved_Firm_Trading_ID__c).put(mtd.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(mtd.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
                        accounts.get(trade.Resolved_Firm_Trading_ID__c).put(mtd.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(mtd.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);
                        //system.debug(mtd);
                        //system.debug(LoggingLevel.DEBUG, + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime());
                    }
                }
            } 
            else if(date.today().year()-1==trade.trade_date__c.year()) {
                accounts.get(trade.Resolved_Firm_Trading_ID__c).put(py.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(py.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
                accounts.get(trade.Resolved_Firm_Trading_ID__c).put(py.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(py.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);
                //system.debug(py);
                //system.debug(LoggingLevel.DEBUG, + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime());
            }
            accounts.get(trade.Resolved_Firm_Trading_ID__c).put(total.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(total.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
            accounts.get(trade.Resolved_Firm_Trading_ID__c).put(total.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(total.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);
            //system.debug(total);
            //system.debug(LoggingLevel.DEBUG, + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime());
        }
            }
        }
        inprog = true;
        update accounts.values();
        inprog = false;
    }
}
Trigger:
trigger Account_RollupTrades on Account (after update) {
    if(Account_RollupTrades.inprog == false) {
        //set<ID> sID = new set<ID> (trigger.newMap.keySet());
        Account_RollupTrades.execute(trigger.newMap.keySet(), trigger.new);
    }
}



 
Hi, we are having an issue with one of our clients using our integration package. We are at our wits end so I am reaching out here to see if anyone has run into a similiar scenario.

When running a simple query for example:

Select Id From CustomObject

We do this on a regular basis to delete and refresh all of the objects as we currently do not have a unique field on the records we are uploading. The query only is getting around 1 million records max which seems in not a terribly large amount. We only have this issue with one of our clients and only on their production org. They are one of our larger clients, but we have a few in their ball park that run fine.

I was curious if anyone has seen this behavior before? And if so how was the issue resolved. I read some posts that the recycle bin needs deleted, and our client said they had done it prior to an integration run.

I have also read that our query needs to be more selective and add a where clause. But in this case we would technically 'tricking' the SOQL to still retrieve the entire record set. For example:

Select Id From CustomObject where isDeleted = false
Hi,
We have been using the SOAP API calls for a couple of years without issue.
On one of our machines which was recently given a fresh image, we are unable to communicate with the SOAP interface when connecting to Salesforce within Python.
I've tried connecting to both: 
https://test.salesforce.com/services/Soap/u/32.0
and
https://login.salesforce.com/services/Soap/u/32.0

I have disabled all firewalls and still no luck from one machine on our network.
Is there an easy way to validate that Salesforce is even receiving the call from this machine as a standard Salesforce error message isn't being returned.
Thanks,
Steve
I have a trigger I wrote that works great when I test it in the UI, but my test is failing.  I get the following error:
Error Message	System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, triggerTest: execution of BeforeInsert

caused by: System.NullPointerException: Argument cannot be null.

Trigger.triggerTest: line 294, column 1: []
Stack Trace	Class.testtest.myUnitTest: line 61, column 1
If I'm understanding this correctly it says its failing when it tries to insert the opportunitylineitem because when the trigger tries to do "a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);" and it thinks No_Ordered__c or ListPrice is NULL.  I get this error whether or not I use a the test product or a real product already in the system that I know works fine when I test in the UI.  Please tell me what I am doing wrong.  Any help is appreciated.  Here is the code for the trigger and the test.  I trimmed down the test to test only one product.

TRIGGER
trigger triggerTest on OpportunityLineItem (before insert, before update) {

		decimal disc;
		decimal sub;
		decimal servamt;
		decimal billcalc;
		Integer quartercalc;
		Integer enddate;

		for(OpportunityLineItem a : Trigger.New){
			a.Quantity = (a.No_Ordered__c * a.Service_Duration__c);
			sub = (a.Quantity * a.UnitPrice);
			if(a.Discount != NULL){
				disc = (a.Discount * .01);
				a.TotalPrice = (sub - (sub * disc));
			}else{
				a.TotalPrice = sub;	
			}
			servamt = (a.Quantity / a.No_Ordered__c);
			a.Service_Amount__c = (a.TotalPrice / servamt);
			if(a.PB__c == 'Weekly'){
				if(a.Billing_Period__c == 'Weekly'){
					billcalc = 1;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 7);
					a.End_Date__c = a.ServiceDate.addDays(enddate);
				}else if(a.Billing_Period__c == 'Quarterly'){
					billcalc = 13;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 7);
					a.End_Date__c = a.ServiceDate.addDays(enddate);				
				}else if(a.Billing_Period__c == 'Semi-Annual'){
					billcalc = 26;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 7);
					a.End_Date__c = a.ServiceDate.addDays(enddate);				
				}else if(a.Billing_Period__c == 'Annual'){
					billcalc = 52;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);				
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 7);
					a.End_Date__c = a.ServiceDate.addDays(enddate);							
				}

			}else if(a.PB__c == 'Monthly' || a.PB__c == 'Monthly D'){
				if(a.Billing_Period__c == 'Monthly'){
					billcalc = 1;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addMonths(enddate);
				}else if(a.Billing_Period__c == 'Every Other Month'){
					billcalc = 2;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addMonths(enddate);
				}else if(a.Billing_Period__c == 'Quarterly'){
					billcalc = 3;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addMonths(enddate);
				}else if(a.Billing_Period__c == 'Semi-Annual'){
					billcalc = 6;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addMonths(enddate);
				}else if(a.Billing_Period__c == 'Annual'){
					billcalc = 12;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addMonths(enddate);
				}

			}else if(a.PB__c == 'Quarterly'){
				if(a.Billing_Period__c == 'Quarterly'){
					billcalc = 1;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 3);
					a.End_Date__c = a.ServiceDate.addMonths(enddate);
				}else if(a.Billing_Period__c == 'Semi-Annual'){
					billcalc = 2;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 3);
					a.End_Date__c = a.ServiceDate.addMonths(enddate);
				}else if(a.Billing_Period__c == 'Annual'){
					billcalc = 4;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 3);
					a.End_Date__c = a.ServiceDate.addMonths(enddate);
				}else if(a.Billing_Period__c == 'Monthly'){
					billcalc = 3;
					a.Billing_Amount__c = (a.Service_Amount__c / billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice / billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c / billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 3);
					a.End_Date__c = a.ServiceDate.addMonths(enddate);
				}

			}else if(a.PB__c == 'Annual'){
				if(a.Billing_Period__c == 'Annual'){
					billcalc = 1;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addYears(enddate);
				}else if(a.Billing_Period__c == 'Monthly'){
					billcalc = 12;
					a.Billing_Amount__c = (a.Service_Amount__c / billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice / billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c / billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addYears(enddate);
				}else if(a.Billing_Period__c == 'Every Other Month'){
					billcalc = 6;
					a.Billing_Amount__c = (a.Service_Amount__c / billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice / billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c / billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addYears(enddate);
				}else if(a.Billing_Period__c == 'Quarterly'){
					billcalc = 4;
					a.Billing_Amount__c = (a.Service_Amount__c / billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice / billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c / billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addYears(enddate);
				}else if(a.Billing_Period__c == 'Semi-Annual'){
					billcalc = 2;
					a.Billing_Amount__c = (a.Service_Amount__c / billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice / billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c / billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addYears(enddate);
				}

			}else if(a.PB__c == 'One Time' || a.PB__c == 'One Time D'){
				if(a.Billing_Period__c == 'Monthly'){
					billcalc = 1;
					a.Billing_Amount__c = (a.Service_Amount__c * billcalc);
					a.List_Price_Svc__c = (a.No_Ordered__c * a.ListPrice);
					a.List_Price_Bill__c = (a.ListPrice * billcalc);
					a.List_Price_Extd__c = (a.List_Price_Svc__c * billcalc);
					a.Billing_Savings__c = (a.Billing_Amount__c - a.List_Price_Extd__c);
					if(a.Billing_Savings__c >= 0){
						a.Billing_Savings__c = NULL;
					}
					a.Per_Item_Bill__c = (a.Billing_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Bill__c = (a.List_Price_Bill__c - a.Per_Item_Bill__c);
					a.Service_Savings__c = (a.Service_Amount__c - a.List_Price_Svc__c);
					if(a.Service_Savings__c >= 0){
						a.Service_Savings__c = NULL;
					}
					a.Per_Item_Svc__c = (a.Service_Amount__c / a.No_Ordered__c);
					a.Discount_Amount_Svc__c = (a.ListPrice - a.Per_Item_Svc__c);
					enddate = (a.Service_Duration__c.intValue() * 1);
					a.End_Date__c = a.ServiceDate.addDays(enddate);
				}

			}

		}


	}

TEST CLASS
 
/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest(SeeAllData=true)
private class testtest {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test

        Date now = date.today();
        integer day = now.day();
        
        // CREATE ACCOUNT
        Account newAccount = new Account(Name = 'Test Account', Phone='817-999-9999' );
        insert newAccount;

         // CREATE CONTACT
        Contact newContact = new Contact(LastName = 'Test Contact', AccountId = newAccount.Id );
        insert newContact; 

        // CREATE OPPORTUNITY
        Opportunity newOpp = new Opportunity(Name = 'Test Opportunity', CloseDate = System.today(), AccountId = newAccount.Id, Contact_Name__c = newContact.Id, StageName = 'Initial Interview' );
        insert newOpp;
        
        // GET STANDARD PRICEBOOK
		Pricebook2  standardPb = [select id, name, isActive from Pricebook2 where IsStandard = true limit 1];

		// CREATE CUSTOM PRICEBOOK
		Pricebook2 pbk1 = new Pricebook2 (Name='Test Pricebook Entry 1',Description='Test Pricebook Entry 1', isActive=true);
		insert pbk1;

		// CREATE PRODUCT
		Product2 prd1 = new Product2 (Name='Test Product Entry 1',Description='Test Product Entry 1',productCode = 'ABC', isActive = true, Pricing_Basis__c = 'Annual' );
		insert prd1;

		// CREATE PRICEBOOKENTRY
		PricebookEntry pbe1 = new PricebookEntry (Product2ID=prd1.id,Pricebook2ID=standardPb.id,UnitPrice=50, isActive=true);
		insert pbe1;


        // CREATE OPPORTUNITYPRODUCTS
        OpportunityLineItem newProdAnnual = new OpportunityLineItem (Billing_Period__c = 'Annual', OpportunityId = newOpp.Id, Service_Duration__c = 1, ServiceDate = now, End_Date__c = now, PricebookEntryId = pbe1.Id, No_Ordered__c = 1, UnitPrice = 50, Quantity = 1);       
        insert newProdAnnual;

        //QUERY
        OpportunityLineItem a =[SELECT ID, Quantity, TotalPrice, Discount, UnitPrice, Billing_Amount__c, List_Price_Svc__c, List_Price_Bill__c, List_Price_Extd__c, Billing_Savings__c, Per_Item_Bill__c, Discount_Amount_Bill__c, Service_Savings__c, Per_Item_Svc__c, Discount_Amount_Svc__c, End_Date__c, ServiceDate from OpportunityLineItem WHERE ID =: newProdAnnual.Id ];


        //VALIDATE DATA WAS UPDATED CORRECTLY

		//Annual
		System.assertEquals(a.Quantity, 1);
		System.assertEquals(a.TotalPrice, 50.00);
		System.assertEquals(a.Discount, 0);
		System.assertEquals(a.Billing_Amount__c, 50.00);
		System.assertEquals(a.List_Price_Svc__c, 50.00);
		System.assertEquals(a.List_Price_Bill__c, 50.00);
		System.assertEquals(a.List_Price_Extd__c, 50.00);
		System.assertEquals(a.Billing_Savings__c, NULL);
		System.assertEquals(a.Per_Item_Bill__c, 50.00);		
		System.assertEquals(a.Discount_Amount_Bill__c, 0.00);
		System.assertEquals(a.Service_Savings__c, NULL);
		System.assertEquals(a.Per_Item_Svc__c, 50.00);
		System.assertEquals(a.Discount_Amount_Svc__c, 0.00);
		System.assertEquals(a.End_Date__c, a.ServiceDate.addYears(1));

    }
}



 
  • March 03, 2015
  • Like
  • 1

Hello. I apologize if this is a duplicate issue, but I couldn't find a similar issue on the forums. I'm new here.

I have a custom object in Salesforce that cannot be queried. It always times out. It used to do that sometimes, but then it would work. Now, I cannot query it no matter what I do.
I tried:

  • Select Id From Object__c (Times out)
  • Select Id From Object__c Limit 5 (Times out)
  • Select Id From Other_Object__c (This works)

Any help is appreciated. Thank you.
Hi 

Can someone suggets me the best continous integration tool for to enhnace my development and deployment process or suggest me the best methodologies or available tools

Vijay